//! Creating saves. //! //! A save is a full snapshot: every tracked path with its object hash and //! executable bit, plus the message, time, machine and optional agent and //! session. Its ID is the first 12 hex characters of the Blake3 hash of the //! canonical record, computed once, at creation, and never recomputed — which //! is why `strip` can change a save's files and keep its ID. module history import strings import time import src.fmt import src.machine import src.snapshot import src.storage pub struct SaveInput { pub mut: message string agent string session string is_checkpoint bool restores string replayed_from string created_at i64 machine string // storing hears how many of the tree's files have been stored. storing snapshot.Counted = unsafe { nil } } pub const nothing_changed = 'nothing has changed since the last save' // save_worktree walks the working tree and records it. A plain save refuses // when the tree matches head; a checkpoint always records. The walk runs // before the lock, so other commands are not held up by the hashing. pub fn save_worktree(store &storage.Store, root string, ig snapshot.Ignore, input SaveInput) !Save { walked_head := head_id(store) files := snapshot.walk(store, root, ig)! return save_walked(store, root, input, walked_head, files) } // save_walked records a tree its caller already walked, so a save does not read // the whole tree twice. `walked_head` must be read before that walk: if another // command moved head meanwhile, save_walk reads the tree again under the lock // rather than recording a stale one. pub fn save_walked(store &storage.Store, root string, input SaveInput, walked_head string, walked []snapshot.FileEntry) !Save { store.begin()! save := save_walk(store, root, input, walked_head, walked) or { store.rollback() return err } store.end()! refresh_log_md(store) return save } // save_walk records a walk inside the caller's transaction. A restore still // writing its files is refused: the tree is half one save and half another. // When another command moved head after the walk, the walk is stale, and // recording it on the new head would quietly undo that command, so the tree // (and its ignore rules, which may have changed too) is read again under the // lock. fn save_walk(store &storage.Store, root string, input SaveInput, walked_head string, walked []snapshot.FileEntry) !Save { if snapshot.restore_pending(store) { return error(snapshot.restore_unfinished) } mut files := walked.clone() moved := head_id(store) != walked_head if moved { files = snapshot.walk(store, root, snapshot.load(root))! } if input.restores == '' && !input.is_checkpoint { if previous := head(store) { if snapshot.same_tree(files, files_of(store, previous.id)!) { if moved { // Another agent's save, made while this one waited for the // lock, already holds these changes. return error('${nothing_changed} — [${previous.id}] "${fmt.safe_text(previous.message)}" was saved a moment ago and already holds this tree') } return error(nothing_changed) } } } return record_save(store, root, files, input)! } // save_tree records an already-known tree. `root` is '' when the objects are // already in the store — a restore, or a replay during a steal. pub fn save_tree(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save { store.begin()! save := record_save(store, root, files, input) or { store.rollback() return err } store.end()! refresh_log_md(store) return save } // record_save writes one save inside the caller's transaction. A steal uses it // to land a whole replay — several saves, fetched objects and fetched events — // in a single step, so a failure leaves no half-combined line behind. pub fn record_save(store &storage.Store, root string, files []snapshot.FileEntry, input SaveInput) !Save { if root != '' { snapshot.store_objects(store, root, files, input.storing)! } return write_save(store, files, input)! } // write_save mints the ID, inserts the save and then moves head, inside the caller's transaction, so // the save's rows and head change together or not at all. The objects were stored before (record_save). fn write_save(store &storage.Store, files []snapshot.FileEntry, input SaveInput) !Save { created_at := if input.created_at > 0 { input.created_at } else { time.now().unix() } mut save := Save{ parent: head_id(store) message: input.message created_at: created_at machine: if input.machine != '' { input.machine } else { machine.name() } is_checkpoint: input.is_checkpoint size_bytes: tree_size(files) agent: input.agent session: input.session restores: input.restores replayed_from: input.replayed_from } // Two saves made in the same second with the same record would collide. // Bumping the clock keeps one line of history and keeps the ID unique. for { save.id = save_id(save, files) if by_id(store, save.id) == none { break } save.created_at++ } insert_save(store, save, files)! store.set_state(storage.head_key, save.id)! return save } // import_save records a save exactly as another machine made it: same ID, same // parent, same time, same files. `steal` and `migrate` use it; a save made here // goes through write_save instead, which mints the ID. A record carries no // sizes, so a file whose size is not known yet takes it from its object — the // manifest stores it and every later read avoids asking. pub fn import_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! { mut sized := files.clone() if sized.any(it.size == 0) { mut stmt := store.db.prepare('SELECT size FROM objects WHERE hash = ?')! defer { stmt.finalize() } for index in 0 .. sized.len { if sized[index].size != 0 { continue } stmt.bind_text(1, sized[index].hash)! if stmt.step()! { sized[index] = snapshot.FileEntry{ path: sized[index].path hash: sized[index].hash size: stmt.int(0) executable: sized[index].executable } } stmt.reset() } } insert_save(store, save, sized)! } // set_head moves the line's head without creating a save. Only fetching another // machine's saves does that: nothing is erased and nothing is re-recorded, // because those saves are already on the line. pub fn set_head(store &storage.Store, id string) ! { store.set_state(storage.head_key, id)! } // insert_save writes the save row, naming the root manifest built from its // files. Every object the tree names must already be here: the manifest has no // foreign key to `objects`, so this is the check that a half-written save // cannot exist. Its callers hold the transaction. fn insert_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! { mut manifest := save.manifest if manifest != '' { // A stolen save names the tree that came with it: the rows are here. store.manifest_body(manifest)! } else { manifest = store.manifest_tree(manifest_files(files))! } mut seen := map[string]bool{} mut lookup := store.db.prepare('SELECT 1 FROM objects WHERE hash = ?')! defer { lookup.finalize() } for file in files { if file.hash in seen { continue } seen[file.hash] = true lookup.bind_text(1, file.hash)! if !lookup.step()! { return error('save ${save.id} needs missing object ${file.hash}') } lookup.reset() } mut stmt := store.db.prepare('INSERT INTO saves (id, parent, manifest, message, created_at, machine, is_checkpoint, size_bytes, agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')! stmt.bind_text(1, save.id)! if save.parent == '' { stmt.bind_null(2)! } else { stmt.bind_text(2, save.parent)! } stmt.bind_text(3, manifest)! stmt.bind_text(4, save.message)! stmt.bind_int(5, save.created_at)! stmt.bind_text(6, save.machine)! stmt.bind_int(7, if save.is_checkpoint { 1 } else { 0 })! stmt.bind_int(8, save.size_bytes)! bind_optional(stmt, 9, save.agent)! bind_optional(stmt, 10, save.session)! bind_optional(stmt, 11, save.restores)! bind_optional(stmt, 12, save.replayed_from)! stmt.step()! stmt.finalize() } fn manifest_files(files []snapshot.FileEntry) []storage.ManifestFile { mut out := []storage.ManifestFile{cap: files.len} for file in files { out << storage.ManifestFile{ path: file.path hash: file.hash size: file.size executable: file.executable } } return out } fn bind_optional(stmt &storage.Stmt, index int, value string) ! { if value == '' { stmt.bind_null(index)! } else { stmt.bind_text(index, value)! } } // save_id is the first 12 hex characters of the Blake3 hash of the canonical // record: parent, message, time, machine, checkpoint mark, agent, session and // the sorted file list. pub fn save_id(save Save, files []snapshot.FileEntry) string { return storage.hash_hex(canonical(save, files).bytes())[..12] } fn canonical(save Save, files []snapshot.FileEntry) string { mut sb := strings.Builder{} sb.write_string('koh3-save-v1\n') put_field(mut sb, 'parent', save.parent) put_field(mut sb, 'message', save.message) put_field(mut sb, 'created', save.created_at.str()) put_field(mut sb, 'machine', save.machine) put_field(mut sb, 'checkpoint', if save.is_checkpoint { '1' } else { '0' }) put_field(mut sb, 'agent', save.agent) put_field(mut sb, 'session', save.session) put_field(mut sb, 'files', files.len.str()) for file in files { mark := if file.executable { 'x' } else { '-' } put_field(mut sb, 'file', '${mark}${file.hash} ${file.path}') } return sb.str() } // Length-prefixed fields keep the record unambiguous whatever a message or a // path contains. fn put_field(mut sb strings.Builder, name string, value string) { sb.write_string('${name}:${value.len}:') sb.write_string(value) sb.write_string('\n') } fn tree_size(files []snapshot.FileEntry) i64 { mut total := i64(0) for file in files { total += file.size } return total }