save.v

9.8 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	return save_walked(store, root, input, walked_head, files)41}4243// save_walked records a tree its caller already walked, so a save does not read44// the whole tree twice. `walked_head` must be read before that walk: if another45// command moved head meanwhile, save_walk reads the tree again under the lock46// rather than recording a stale one.47pub fn save_walked(store &storage.Store, root string, input SaveInput, walked_head string, walked []snapshot.FileEntry) !Save {48	store.begin()!49	save := save_walk(store, root, input, walked_head, walked) or {50		store.rollback()51		return err52	}53	store.end()!54	refresh_log_md(store)55	return save56}5758// save_walk records a walk inside the caller's transaction. A restore still59// writing its files is refused: the tree is half one save and half another.60// When another command moved head after the walk, the walk is stale, and61// recording it on the new head would quietly undo that command, so the tree62// (and its ignore rules, which may have changed too) is read again under the63// lock.64fn save_walk(store &storage.Store, root string, input SaveInput, walked_head string, walked []snapshot.FileEntry) !Save {65	if snapshot.restore_pending(store) {66		return error(snapshot.restore_unfinished)67	}68	mut files := walked.clone()69	moved := head_id(store) != walked_head70	if moved {71		files = snapshot.walk(store, root, snapshot.load(root))!72	}73	if input.restores == '' && !input.is_checkpoint {74		if previous := head(store) {75			if snapshot.same_tree(files, files_of(store, previous.id)!) {76				if moved {77					// Another agent's save, made while this one waited for the78					// lock, already holds these changes.79					return error('${nothing_changed} — [${previous.id}] "${fmt.safe_text(previous.message)}" was saved a moment ago and already holds this tree')80				}81				return error(nothing_changed)82			}83		}84	}85	return record_save(store, root, files, input)!86}8788// save_tree records an already-known tree. `root` is '' when the objects are89// already in the store — a restore, or a replay during a steal.90pub fn save_tree(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save {91	store.begin()!92	save := record_save(store, root, files, input) or {93		store.rollback()94		return err95	}96	store.end()!97	refresh_log_md(store)98	return save99}100101// record_save writes one save inside the caller's transaction. A steal uses it102// to land a whole replay — several saves, fetched objects and fetched events —103// in a single step, so a failure leaves no half-combined line behind.104pub fn record_save(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save {105	if root != '' {106		snapshot.store_objects(store, root, files, input.storing)!107	}108	return write_save(store, files, input)!109}110111// write_save mints the ID, inserts the save and then moves head, inside the caller's transaction, so112// the save's rows and head change together or not at all. The objects were stored before (record_save).113fn write_save(store &storage.Store, files []snapshot.FileEntry, input SaveInput) !Save {114	created_at := if input.created_at > 0 { input.created_at } else { time.now().unix() }115	mut save := Save{116		parent:        head_id(store)117		message:       input.message118		created_at:    created_at119		machine:       if input.machine != '' { input.machine } else { machine.name() }120		is_checkpoint: input.is_checkpoint121		size_bytes:    tree_size(files)122		agent:         input.agent123		session:       input.session124		restores:      input.restores125		replayed_from: input.replayed_from126	}127	// Two saves made in the same second with the same record would collide.128	// Bumping the clock keeps one line of history and keeps the ID unique.129	for {130		save.id = save_id(save, files)131		if by_id(store, save.id) == none {132			break133		}134		save.created_at++135	}136	insert_save(store, save, files)!137	store.set_state(storage.head_key, save.id)!138	return save139}140141// import_save records a save exactly as another machine made it: same ID, same142// parent, same time, same files. `steal` and `migrate` use it; a save made here143// goes through write_save instead, which mints the ID. A record carries no144// sizes, so a file whose size is not known yet takes it from its object — the145// manifest stores it and every later read avoids asking.146pub fn import_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {147	mut sized := files.clone()148	if sized.any(it.size == 0) {149		mut stmt := store.db.prepare('SELECT size FROM objects WHERE hash = ?')!150		defer {151			stmt.finalize()152		}153		for index in 0 .. sized.len {154			if sized[index].size != 0 {155				continue156			}157			stmt.bind_text(1, sized[index].hash)!158			if stmt.step()! {159				sized[index] = snapshot.FileEntry{160					path:       sized[index].path161					hash:       sized[index].hash162					size:       stmt.int(0)163					executable: sized[index].executable164				}165			}166			stmt.reset()167		}168	}169	insert_save(store, save, sized)!170}171172// set_head moves the line's head without creating a save. Only fetching another173// machine's saves does that: nothing is erased and nothing is re-recorded,174// because those saves are already on the line.175pub fn set_head(store &storage.Store, id string) ! {176	store.set_state(storage.head_key, id)!177}178179// insert_save writes the save row, naming the root manifest built from its180// files. Every object the tree names must already be here: the manifest has no181// foreign key to `objects`, so this is the check that a half-written save182// cannot exist. Its callers hold the transaction.183fn insert_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {184	mut manifest := save.manifest185	if manifest != '' {186		// A stolen save names the tree that came with it: the rows are here.187		store.manifest_body(manifest)!188	} else {189		manifest = store.manifest_tree(manifest_files(files))!190	}191	mut seen := map[string]bool{}192	mut lookup := store.db.prepare('SELECT 1 FROM objects WHERE hash = ?')!193	defer {194		lookup.finalize()195	}196	for file in files {197		if file.hash in seen {198			continue199		}200		seen[file.hash] = true201		lookup.bind_text(1, file.hash)!202		if !lookup.step()! {203			return error('save ${save.id} needs missing object ${file.hash}')204		}205		lookup.reset()206	}207	mut stmt := store.db.prepare('INSERT INTO saves (id, parent, manifest, message, created_at, machine,208		is_checkpoint, size_bytes, agent, session, restores, replayed_from)209		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!210	stmt.bind_text(1, save.id)!211	if save.parent == '' {212		stmt.bind_null(2)!213	} else {214		stmt.bind_text(2, save.parent)!215	}216	stmt.bind_text(3, manifest)!217	stmt.bind_text(4, save.message)!218	stmt.bind_int(5, save.created_at)!219	stmt.bind_text(6, save.machine)!220	stmt.bind_int(7, if save.is_checkpoint { 1 } else { 0 })!221	stmt.bind_int(8, save.size_bytes)!222	bind_optional(stmt, 9, save.agent)!223	bind_optional(stmt, 10, save.session)!224	bind_optional(stmt, 11, save.restores)!225	bind_optional(stmt, 12, save.replayed_from)!226	stmt.step()!227	stmt.finalize()228}229230fn manifest_files(files []snapshot.FileEntry) []storage.ManifestFile {231	mut out := []storage.ManifestFile{cap: files.len}232	for file in files {233		out << storage.ManifestFile{234			path:       file.path235			hash:       file.hash236			size:       file.size237			executable: file.executable238		}239	}240	return out241}242243fn bind_optional(stmt &storage.Stmt, index int, value string) ! {244	if value == '' {245		stmt.bind_null(index)!246	} else {247		stmt.bind_text(index, value)!248	}249}250251// save_id is the first 12 hex characters of the Blake3 hash of the canonical252// record: parent, message, time, machine, checkpoint mark, agent, session and253// the sorted file list.254pub fn save_id(save Save, files []snapshot.FileEntry) string {255	return storage.hash_hex(canonical(save, files).bytes())[..12]256}257258fn canonical(save Save, files []snapshot.FileEntry) string {259	mut sb := strings.Builder{}260	sb.write_string('koh3-save-v1\n')261	put_field(mut sb, 'parent', save.parent)262	put_field(mut sb, 'message', save.message)263	put_field(mut sb, 'created', save.created_at.str())264	put_field(mut sb, 'machine', save.machine)265	put_field(mut sb, 'checkpoint', if save.is_checkpoint { '1' } else { '0' })266	put_field(mut sb, 'agent', save.agent)267	put_field(mut sb, 'session', save.session)268	put_field(mut sb, 'files', files.len.str())269	for file in files {270		mark := if file.executable { 'x' } else { '-' }271		put_field(mut sb, 'file', '${mark}${file.hash} ${file.path}')272	}273	return sb.str()274}275276// Length-prefixed fields keep the record unambiguous whatever a message or a277// path contains.278fn put_field(mut sb strings.Builder, name string, value string) {279	sb.write_string('${name}:${value.len}:')280	sb.write_string(value)281	sb.write_string('\n')282}283284fn tree_size(files []snapshot.FileEntry) i64 {285	mut total := i64(0)286	for file in files {287		total += file.size288	}289	return total290}