save.v

9.2 KB · raw

1//! Creating saves.2//!3//! A save is a full snapshot: every tracked path with its object hash and4//! executable bit, plus the message, time, machine and optional agent and5//! session. Its ID is the first 12 hex characters of the Blake3 hash of the6//! canonical record, computed once, at creation, and never recomputed — which7//! is why `strip` can change a save's files and keep its ID.89module history1011import strings12import time13import src.fmt14import src.machine15import src.snapshot16import src.storage1718pub struct SaveInput {19pub mut:20	message       string21	agent         string22	session       string23	is_checkpoint bool24	restores      string25	replayed_from string26	created_at    i6427	machine       string28	// storing hears how many of the tree's files have been stored.29	storing snapshot.Counted = unsafe { nil }30}3132pub const nothing_changed = 'nothing has changed since the last save'3334// save_worktree walks the working tree and records it. A plain save refuses35// when the tree matches head; a checkpoint always records. The walk runs36// before the lock, so other commands are not held up by the hashing.37pub fn save_worktree(store &storage.Store, root string, ig snapshot.Ignore, input SaveInput) !Save {38	walked_head := head_id(store)39	files := snapshot.walk(store, root, ig)!40	store.begin()!41	save := save_walk(store, root, input, walked_head, files) or {42		store.rollback()43		return err44	}45	store.end()!46	refresh_log_md(store)47	return save48}4950// save_walk records a walk inside the caller's transaction. A restore still51// writing its files is refused: the tree is half one save and half another.52// When another command moved head after the walk, the walk is stale, and53// recording it on the new head would quietly undo that command, so the tree54// (and its ignore rules, which may have changed too) is read again under the55// lock.56fn save_walk(store &storage.Store, root string, input SaveInput, walked_head string, walked []snapshot.FileEntry) !Save {57	if snapshot.restore_pending(store) {58		return error(snapshot.restore_unfinished)59	}60	mut files := walked.clone()61	moved := head_id(store) != walked_head62	if moved {63		files = snapshot.walk(store, root, snapshot.load(root))!64	}65	if input.restores == '' && !input.is_checkpoint {66		if previous := head(store) {67			if snapshot.same_tree(files, files_of(store, previous.id)!) {68				if moved {69					// Another agent's save, made while this one waited for the70					// lock, already holds these changes.71					return error('${nothing_changed} — [${previous.id}] "${fmt.safe_text(previous.message)}" was saved a moment ago and already holds this tree')72				}73				return error(nothing_changed)74			}75		}76	}77	return record_save(store, root, files, input)!78}7980// save_tree records an already-known tree. `root` is '' when the objects are81// already in the store — a restore, or a replay during a steal.82pub fn save_tree(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save {83	store.begin()!84	save := record_save(store, root, files, input) or {85		store.rollback()86		return err87	}88	store.end()!89	refresh_log_md(store)90	return save91}9293// record_save writes one save inside the caller's transaction. A steal uses it94// to land a whole replay — several saves, fetched objects and fetched events —95// in a single step, so a failure leaves no half-combined line behind.96pub fn record_save(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save {97	if root != '' {98		snapshot.store_objects(store, root, files, input.storing)!99	}100	return write_save(store, files, input)!101}102103// write_save mints the ID, inserts the save and then moves head, inside the caller's transaction, so104// the save's rows and head change together or not at all. The objects were stored before (record_save).105fn write_save(store &storage.Store, files []snapshot.FileEntry, input SaveInput) !Save {106	created_at := if input.created_at > 0 { input.created_at } else { time.now().unix() }107	mut save := Save{108		parent:        head_id(store)109		message:       input.message110		created_at:    created_at111		machine:       if input.machine != '' { input.machine } else { machine.name() }112		is_checkpoint: input.is_checkpoint113		size_bytes:    tree_size(files)114		agent:         input.agent115		session:       input.session116		restores:      input.restores117		replayed_from: input.replayed_from118	}119	// Two saves made in the same second with the same record would collide.120	// Bumping the clock keeps one line of history and keeps the ID unique.121	for {122		save.id = save_id(save, files)123		if by_id(store, save.id) == none {124			break125		}126		save.created_at++127	}128	insert_save(store, save, files)!129	store.set_state(storage.head_key, save.id)!130	return save131}132133// import_save records a save exactly as another machine made it: same ID, same134// parent, same time, same files. `steal` and `migrate` use it; a save made here135// goes through write_save instead, which mints the ID. A record carries no136// sizes, so a file whose size is not known yet takes it from its object — the137// manifest stores it and every later read avoids asking.138pub fn import_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {139	mut sized := files.clone()140	if sized.any(it.size == 0) {141		mut stmt := store.db.prepare('SELECT size FROM objects WHERE hash = ?')!142		defer {143			stmt.finalize()144		}145		for index in 0 .. sized.len {146			if sized[index].size != 0 {147				continue148			}149			stmt.bind_text(1, sized[index].hash)!150			if stmt.step()! {151				sized[index] = snapshot.FileEntry{152					path:       sized[index].path153					hash:       sized[index].hash154					size:       stmt.int(0)155					executable: sized[index].executable156				}157			}158			stmt.reset()159		}160	}161	insert_save(store, save, sized)!162}163164// set_head moves the line's head without creating a save. Only fetching another165// machine's saves does that: nothing is erased and nothing is re-recorded,166// because those saves are already on the line.167pub fn set_head(store &storage.Store, id string) ! {168	store.set_state(storage.head_key, id)!169}170171// insert_save writes the save row, naming the root manifest built from its172// files. Every object the tree names must already be here: the manifest has no173// foreign key to `objects`, so this is the check that a half-written save174// cannot exist. Its callers hold the transaction.175fn insert_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {176	manifest := store.manifest_tree(manifest_files(files))!177	mut seen := map[string]bool{}178	mut lookup := store.db.prepare('SELECT 1 FROM objects WHERE hash = ?')!179	defer {180		lookup.finalize()181	}182	for file in files {183		if file.hash in seen {184			continue185		}186		seen[file.hash] = true187		lookup.bind_text(1, file.hash)!188		if !lookup.step()! {189			return error('save ${save.id} needs missing object ${file.hash}')190		}191		lookup.reset()192	}193	mut stmt := store.db.prepare('INSERT INTO saves (id, parent, manifest, message, created_at, machine,194		is_checkpoint, size_bytes, agent, session, restores, replayed_from)195		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!196	stmt.bind_text(1, save.id)!197	if save.parent == '' {198		stmt.bind_null(2)!199	} else {200		stmt.bind_text(2, save.parent)!201	}202	stmt.bind_text(3, manifest)!203	stmt.bind_text(4, save.message)!204	stmt.bind_int(5, save.created_at)!205	stmt.bind_text(6, save.machine)!206	stmt.bind_int(7, if save.is_checkpoint { 1 } else { 0 })!207	stmt.bind_int(8, save.size_bytes)!208	bind_optional(stmt, 9, save.agent)!209	bind_optional(stmt, 10, save.session)!210	bind_optional(stmt, 11, save.restores)!211	bind_optional(stmt, 12, save.replayed_from)!212	stmt.step()!213	stmt.finalize()214}215216fn manifest_files(files []snapshot.FileEntry) []storage.ManifestFile {217	mut out := []storage.ManifestFile{cap: files.len}218	for file in files {219		out << storage.ManifestFile{220			path:       file.path221			hash:       file.hash222			size:       file.size223			executable: file.executable224		}225	}226	return out227}228229fn bind_optional(stmt &storage.Stmt, index int, value string) ! {230	if value == '' {231		stmt.bind_null(index)!232	} else {233		stmt.bind_text(index, value)!234	}235}236237// save_id is the first 12 hex characters of the Blake3 hash of the canonical238// record: parent, message, time, machine, checkpoint mark, agent, session and239// the sorted file list.240pub fn save_id(save Save, files []snapshot.FileEntry) string {241	return storage.hash_hex(canonical(save, files).bytes())[..12]242}243244fn canonical(save Save, files []snapshot.FileEntry) string {245	mut sb := strings.Builder{}246	sb.write_string('koh3-save-v1\n')247	put_field(mut sb, 'parent', save.parent)248	put_field(mut sb, 'message', save.message)249	put_field(mut sb, 'created', save.created_at.str())250	put_field(mut sb, 'machine', save.machine)251	put_field(mut sb, 'checkpoint', if save.is_checkpoint { '1' } else { '0' })252	put_field(mut sb, 'agent', save.agent)253	put_field(mut sb, 'session', save.session)254	put_field(mut sb, 'files', files.len.str())255	for file in files {256		mark := if file.executable { 'x' } else { '-' }257		put_field(mut sb, 'file', '${mark}${file.hash} ${file.path}')258	}259	return sb.str()260}261262// Length-prefixed fields keep the record unambiguous whatever a message or a263// path contains.264fn put_field(mut sb strings.Builder, name string, value string) {265	sb.write_string('${name}:${value.len}:')266	sb.write_string(value)267	sb.write_string('\n')268}269270fn tree_size(files []snapshot.FileEntry) i64 {271	mut total := i64(0)272	for file in files {273		total += file.size274	}275	return total276}