save.v

8.1 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(store, 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.136pub fn import_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {137	insert_save(store, save, files)!138}139140// set_head moves the line's head without creating a save. Only fetching another141// machine's saves does that: nothing is erased and nothing is re-recorded,142// because those saves are already on the line.143pub fn set_head(store &storage.Store, id string) ! {144	store.set_state(storage.head_key, id)!145}146147// insert_save writes the save row, then one row per file. Its callers hold the transaction.148fn insert_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {149	mut stmt := store.db.prepare('INSERT INTO saves (id, parent, message, created_at, machine,150		is_checkpoint, size_bytes, agent, session, restores, replayed_from)151		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!152	stmt.bind_text(1, save.id)!153	if save.parent == '' {154		stmt.bind_null(2)!155	} else {156		stmt.bind_text(2, save.parent)!157	}158	stmt.bind_text(3, save.message)!159	stmt.bind_int(4, save.created_at)!160	stmt.bind_text(5, save.machine)!161	stmt.bind_int(6, if save.is_checkpoint { 1 } else { 0 })!162	stmt.bind_int(7, save.size_bytes)!163	bind_optional(stmt, 8, save.agent)!164	bind_optional(stmt, 9, save.session)!165	bind_optional(stmt, 10, save.restores)!166	bind_optional(stmt, 11, save.replayed_from)!167	stmt.step()!168	stmt.finalize()169170	mut files_stmt :=171		store.db.prepare('INSERT INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)')!172	defer {173		files_stmt.finalize()174	}175	for file in files {176		files_stmt.bind_text(1, save.id)!177		files_stmt.bind_text(2, file.path)!178		files_stmt.bind_text(3, file.hash)!179		files_stmt.bind_int(4, if file.executable { 1 } else { 0 })!180		files_stmt.step()!181		// A statement that has returned DONE must be reset before rebinding.182		files_stmt.reset()183	}184}185186fn bind_optional(stmt &storage.Stmt, index int, value string) ! {187	if value == '' {188		stmt.bind_null(index)!189	} else {190		stmt.bind_text(index, value)!191	}192}193194// save_id is the first 12 hex characters of the Blake3 hash of the canonical195// record: parent, message, time, machine, checkpoint mark, agent, session and196// the sorted file list.197pub fn save_id(save Save, files []snapshot.FileEntry) string {198	return storage.hash_hex(canonical(save, files).bytes())[..12]199}200201fn canonical(save Save, files []snapshot.FileEntry) string {202	mut sb := strings.Builder{}203	sb.write_string('koh3-save-v1\n')204	put_field(mut sb, 'parent', save.parent)205	put_field(mut sb, 'message', save.message)206	put_field(mut sb, 'created', save.created_at.str())207	put_field(mut sb, 'machine', save.machine)208	put_field(mut sb, 'checkpoint', if save.is_checkpoint { '1' } else { '0' })209	put_field(mut sb, 'agent', save.agent)210	put_field(mut sb, 'session', save.session)211	put_field(mut sb, 'files', files.len.str())212	for file in files {213		mark := if file.executable { 'x' } else { '-' }214		put_field(mut sb, 'file', '${mark}${file.hash} ${file.path}')215	}216	return sb.str()217}218219// Length-prefixed fields keep the record unambiguous whatever a message or a220// path contains.221fn put_field(mut sb strings.Builder, name string, value string) {222	sb.write_string('${name}:${value.len}:')223	sb.write_string(value)224	sb.write_string('\n')225}226227fn tree_size(store &storage.Store, files []snapshot.FileEntry) i64 {228	mut total := i64(0)229	for file in files {230		total += store.object_size(file.hash) or { 0 }231	}232	return total233}