//! The `.koh` file: schema, connection settings and machine-local state. //! //! One file at the repo root holds everything — objects, saves, events and //! bookkeeping. There is no second source of truth, so there is nothing to //! rebuild, verify against, or recover. module storage import os pub const schema_version = 2 pub const file_name = '.koh' pub const busy_timeout_ms = 5000 // One save's file list is a tree of folder manifests, each named by the hash // of its canonical body, so identical folders are stored and shared once. const manifests_table = ' CREATE TABLE manifests ( hash TEXT PRIMARY KEY, body TEXT NOT NULL ) WITHOUT ROWID; ' const saves_table = ' CREATE TABLE saves ( id TEXT PRIMARY KEY, parent TEXT REFERENCES saves(id), manifest TEXT NOT NULL REFERENCES manifests(hash), message TEXT NOT NULL, created_at INTEGER NOT NULL, machine TEXT NOT NULL, is_checkpoint INTEGER NOT NULL DEFAULT 0, size_bytes INTEGER NOT NULL DEFAULT 0, agent TEXT, session TEXT, restores TEXT, replayed_from TEXT ); ' // Every fact Koh knows lives in these six tables. `state` and `file_cache` are // machine-local: they are never synced and may be dropped at any time. const schema = ' CREATE TABLE objects ( hash TEXT PRIMARY KEY, size INTEGER NOT NULL, data BLOB NOT NULL ); ' + manifests_table + saves_table + ' CREATE TABLE events ( id TEXT PRIMARY KEY, kind TEXT NOT NULL, save_id TEXT, path TEXT, reason TEXT, created_at INTEGER NOT NULL, machine TEXT NOT NULL ); CREATE TABLE state ( key TEXT PRIMARY KEY, value TEXT NOT NULL ); CREATE TABLE file_cache ( path TEXT PRIMARY KEY, size INTEGER NOT NULL, mtime_ns INTEGER NOT NULL, ctime_ns INTEGER NOT NULL, hash TEXT NOT NULL ); CREATE INDEX saves_parent ON saves(parent); ' pub const head_key = 'head' @[heap] pub struct Store { pub mut: db Db root string } // find_root walks up from `start` until it finds a `.koh` file. pub fn find_root(start string) ?string { mut dir := os.real_path(start) for { if os.is_file(os.join_path(dir, file_name)) { return dir } parent := os.dir(dir) if parent == dir || parent == '' { return none } dir = parent } return none } // open connects to the repo at `root`. A missing `.koh` is an error, not a // silent creation: `koh init` is the only thing that creates a repo. pub fn open(root string) !Store { return open_at(os.join_path(root, file_name), root) } // open_at connects to one database file that stands in for the repo's `.koh`. // Nothing but migration needs that. pub fn open_at(path string, root string) !Store { if !os.is_file(path) { return error('no ${file_name} in ${root} — run "koh init"') } db := connect(path, busy_timeout_ms)! apply_settings(db)! check_version(db)! return Store{ db: db root: root } } // create writes a new `.koh` in `root`. pub fn create(root string) !Store { return create_at(os.join_path(root, file_name), root) } // create_at writes a fresh schema into an explicit file. pub fn create_at(path string, root string) !Store { if os.is_file(path) { return error('${path} already exists') } db := connect(path, busy_timeout_ms)! apply_settings(db)! db.exec('BEGIN IMMEDIATE')! db.exec(schema)! db.exec('PRAGMA user_version = ${schema_version}')! db.exec('END')! return Store{ db: db root: root } } pub fn (s &Store) close() { s.db.close() } fn apply_settings(db &Db) ! { // WAL for crash safety, full sync so a finished save is on disk, foreign // keys so a half-written save cannot exist, and secure_delete so a deleted // row's bytes are zeroed rather than left in a free page. db.exec('PRAGMA journal_mode=WAL')! db.exec('PRAGMA synchronous=FULL')! db.exec('PRAGMA foreign_keys=ON')! db.exec('PRAGMA secure_delete=ON')! } fn check_version(db &Db) ! { mut stmt := db.prepare('PRAGMA user_version')! version := if stmt.step()! { stmt.int(0) } else { 0 } stmt.finalize() if version > schema_version { return error('this .koh was written by a newer koh (schema ${version}, this build knows ${schema_version})') } if version == schema_version { return } if version == 1 { return upgrade_1_to_2(db) } return error('this .koh needs an upgrade koh does not know how to do (schema ${version})') } // upgrade_1_to_2 turns `save_files` into per-folder manifests. Foreign keys // cannot change inside a transaction, so they are off around it; a failure // rolls back and leaves the version-1 file as it was. fn upgrade_1_to_2(db &Db) ! { db.exec('PRAGMA foreign_keys=OFF')! db.exec('BEGIN IMMEDIATE')! upgrade_steps(db) or { db.exec('ROLLBACK') or {} db.exec('PRAGMA foreign_keys=ON') or {} return err } db.exec('COMMIT')! db.exec('PRAGMA foreign_keys=ON')! // Dropping save_files freed its pages but left them in the file; a one-time // VACUUM hands that space back, and it cannot run inside the transaction. db.exec('VACUUM')! } struct V1Save { id string parent string message string created_at i64 machine string is_checkpoint bool size_bytes i64 agent string session string restores string replayed_from string } fn upgrade_steps(db &Db) ! { store := Store{ db: db } db.exec(manifests_table)! db.exec('ALTER TABLE saves RENAME TO saves_v1')! db.exec('DROP INDEX IF EXISTS saves_parent')! db.exec(saves_table)! db.exec('CREATE INDEX saves_parent ON saves(parent)')! mut saves := []V1Save{} mut old := db.prepare('SELECT id, parent, message, created_at, machine, is_checkpoint, size_bytes, agent, session, restores, replayed_from FROM saves_v1 ORDER BY id')! for old.step()! { saves << V1Save{ id: old.text(0) parent: old.text_or_none(1) or { '' } message: old.text(2) created_at: old.int(3) machine: old.text(4) is_checkpoint: old.int(5) != 0 size_bytes: old.int(6) agent: old.text_or_none(7) or { '' } session: old.text_or_none(8) or { '' } restores: old.text_or_none(9) or { '' } replayed_from: old.text_or_none(10) or { '' } } } old.finalize() mut files := db.prepare('SELECT path, hash, executable, COALESCE((SELECT size FROM objects WHERE objects.hash = save_files.hash), 0) FROM save_files WHERE save_id = ? ORDER BY path')! defer { files.finalize() } mut insert := db.prepare('INSERT INTO saves (id, parent, manifest, message, created_at, machine, is_checkpoint, size_bytes, agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')! defer { insert.finalize() } for save in saves { mut rows := []ManifestFile{} files.bind_text(1, save.id)! for files.step()! { rows << ManifestFile{ path: files.text(0) hash: files.text(1) size: files.int(3) executable: files.int(2) != 0 } } files.reset() root := store.manifest_tree(rows)! insert.bind_text(1, save.id)! bind_optional(insert, 2, save.parent)! insert.bind_text(3, root)! insert.bind_text(4, save.message)! insert.bind_int(5, save.created_at)! insert.bind_text(6, save.machine)! insert.bind_int(7, if save.is_checkpoint { 1 } else { 0 })! insert.bind_int(8, save.size_bytes)! bind_optional(insert, 9, save.agent)! bind_optional(insert, 10, save.session)! bind_optional(insert, 11, save.restores)! bind_optional(insert, 12, save.replayed_from)! insert.step()! insert.reset() } db.exec('DROP TABLE save_files')! db.exec('DROP TABLE saves_v1')! db.exec('PRAGMA user_version = ${schema_version}')! } // bind_optional writes NULL for an absent text, as the save columns expect. fn bind_optional(stmt &Stmt, index int, value string) ! { if value == '' { stmt.bind_null(index)! } else { stmt.bind_text(index, value)! } } // What any write says after waiting busy_timeout_ms for another writer. pub const busy = 'another koh command is writing to this repo — wait for it to finish, then run this again' // begin takes the write lock at once (IMMEDIATE), so a second writer waits busy_timeout_ms here // instead of failing part way through. pub fn (s &Store) begin() ! { s.db.exec('BEGIN IMMEDIATE')! } pub fn (s &Store) end() ! { s.db.exec('END')! } // rollback drops its own failure: the caller is already returning the error that sent it here. pub fn (s &Store) rollback() { s.db.exec('ROLLBACK') or {} } // stripped_paths are the paths a whole-history strip removed. A strip bans its path for good, // so no walk of the tree may pick it up again. pub fn (s &Store) stripped_paths() ![]string { mut stmt := s.db.prepare("SELECT DISTINCT path FROM events WHERE kind = 'strip' AND IFNULL(save_id, '') = ''")! defer { stmt.finalize() } mut paths := []string{} for stmt.step()! { paths << stmt.text(0) } return paths } // state reads a machine-local fact. A read error answers none, the same as unset. pub fn (s &Store) state(key string) ?string { mut stmt := s.db.prepare('SELECT value FROM state WHERE key = ?') or { return none } defer { stmt.finalize() } stmt.bind_text(1, key) or { return none } if stmt.step() or { return none } { return stmt.text(0) } return none } pub fn (s &Store) set_state(key string, value string) ! { mut stmt := s.db.prepare('INSERT INTO state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')! defer { stmt.finalize() } stmt.bind_text(1, key)! stmt.bind_text(2, value)! stmt.step()! } pub fn (s &Store) remove_state(key string) ! { mut stmt := s.db.prepare('DELETE FROM state WHERE key = ?')! defer { stmt.finalize() } stmt.bind_text(1, key)! stmt.step()! } // backup writes a consistent copy of the database. `VACUUM INTO` never copies // a WAL mid-write, which a raw file copy would. pub fn (s &Store) backup(path string) ! { if os.exists(path) { return error('${path} already exists') } s.db.exec("VACUUM INTO '${path.replace("'", "''")}'")! } // scrub rewrites the file and empties the write-ahead log, so the bytes a strip // freed leave neither the free pages nor the WAL frames. The checkpoint comes // first because VACUUM would otherwise carry the old frames along; the second // one moves VACUUM's own writes out of the WAL and truncates it. VACUUM cannot // run inside a transaction, so this is only called with none open. pub fn (s &Store) scrub() ! { s.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')! s.db.exec('VACUUM')! s.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')! } // integrity_check returns SQLite's complaints; empty means the file is sound. pub fn (s &Store) integrity_check() ![]string { mut problems := []string{} mut stmt := s.db.prepare('PRAGMA integrity_check')! defer { stmt.finalize() } for stmt.step()! { line := stmt.text(0) if line != 'ok' { problems << line } } return problems }