storage.v

10.7 KB · raw

1//! The `.koh` file: schema, connection settings and machine-local state.2//!3//! One file at the repo root holds everything — objects, saves, events and4//! bookkeeping. There is no second source of truth, so there is nothing to5//! rebuild, verify against, or recover.67module storage89import os1011pub const schema_version = 212pub const file_name = '.koh'13pub const busy_timeout_ms = 50001415// One save's file list is a tree of folder manifests, each named by the hash16// of its canonical body, so identical folders are stored and shared once.17const manifests_table = '18CREATE TABLE manifests (19	hash TEXT PRIMARY KEY,20	body TEXT NOT NULL21) WITHOUT ROWID;22'2324const saves_table = '25CREATE TABLE saves (26	id            TEXT PRIMARY KEY,27	parent        TEXT REFERENCES saves(id),28	manifest      TEXT NOT NULL REFERENCES manifests(hash),29	message       TEXT NOT NULL,30	created_at    INTEGER NOT NULL,31	machine       TEXT NOT NULL,32	is_checkpoint INTEGER NOT NULL DEFAULT 0,33	size_bytes    INTEGER NOT NULL DEFAULT 0,34	agent         TEXT,35	session       TEXT,36	restores      TEXT,37	replayed_from TEXT38);39'4041// Every fact Koh knows lives in these six tables. `state` and `file_cache` are42// machine-local: they are never synced and may be dropped at any time.43const schema = '44CREATE TABLE objects (45	hash       TEXT PRIMARY KEY,46	size       INTEGER NOT NULL,47	data       BLOB NOT NULL48);49' + manifests_table + saves_table + '50CREATE TABLE events (51	id         TEXT PRIMARY KEY,52	kind       TEXT NOT NULL,53	save_id    TEXT,54	path       TEXT,55	reason     TEXT,56	created_at INTEGER NOT NULL,57	machine    TEXT NOT NULL58);5960CREATE TABLE state (61	key   TEXT PRIMARY KEY,62	value TEXT NOT NULL63);6465CREATE TABLE file_cache (66	path     TEXT PRIMARY KEY,67	size     INTEGER NOT NULL,68	mtime_ns INTEGER NOT NULL,69	ctime_ns INTEGER NOT NULL,70	hash     TEXT NOT NULL71);7273CREATE INDEX saves_parent ON saves(parent);74'7576pub const head_key = 'head'7778@[heap]79pub struct Store {80pub mut:81	db   Db82	root string83}8485// find_root walks up from `start` until it finds a `.koh` file.86pub fn find_root(start string) ?string {87	mut dir := os.real_path(start)88	for {89		if os.is_file(os.join_path(dir, file_name)) {90			return dir91		}92		parent := os.dir(dir)93		if parent == dir || parent == '' {94			return none95		}96		dir = parent97	}98	return none99}100101// open connects to the repo at `root`. A missing `.koh` is an error, not a102// silent creation: `koh init` is the only thing that creates a repo.103pub fn open(root string) !Store {104	return open_at(os.join_path(root, file_name), root)105}106107// open_at connects to one database file that stands in for the repo's `.koh`.108// Nothing but migration needs that.109pub fn open_at(path string, root string) !Store {110	if !os.is_file(path) {111		return error('no ${file_name} in ${root} — run "koh init"')112	}113	db := connect(path, busy_timeout_ms)!114	apply_settings(db)!115	check_version(db)!116	return Store{117		db:   db118		root: root119	}120}121122// create writes a new `.koh` in `root`.123pub fn create(root string) !Store {124	return create_at(os.join_path(root, file_name), root)125}126127// create_at writes a fresh schema into an explicit file.128pub fn create_at(path string, root string) !Store {129	if os.is_file(path) {130		return error('${path} already exists')131	}132	db := connect(path, busy_timeout_ms)!133	apply_settings(db)!134	db.exec('BEGIN IMMEDIATE')!135	db.exec(schema)!136	db.exec('PRAGMA user_version = ${schema_version}')!137	db.exec('END')!138	return Store{139		db:   db140		root: root141	}142}143144pub fn (s &Store) close() {145	s.db.close()146}147148fn apply_settings(db &Db) ! {149	// WAL for crash safety, full sync so a finished save is on disk, foreign150	// keys so a half-written save cannot exist, and secure_delete so a deleted151	// row's bytes are zeroed rather than left in a free page.152	db.exec('PRAGMA journal_mode=WAL')!153	db.exec('PRAGMA synchronous=FULL')!154	db.exec('PRAGMA foreign_keys=ON')!155	db.exec('PRAGMA secure_delete=ON')!156}157158fn check_version(db &Db) ! {159	mut stmt := db.prepare('PRAGMA user_version')!160	version := if stmt.step()! { stmt.int(0) } else { 0 }161	stmt.finalize()162	if version > schema_version {163		return error('this .koh was written by a newer koh (schema ${version}, this build knows ${schema_version})')164	}165	if version == schema_version {166		return167	}168	if version == 1 {169		return upgrade_1_to_2(db)170	}171	return error('this .koh needs an upgrade koh does not know how to do (schema ${version})')172}173174// upgrade_1_to_2 turns `save_files` into per-folder manifests. Foreign keys175// cannot change inside a transaction, so they are off around it; a failure176// rolls back and leaves the version-1 file as it was.177fn upgrade_1_to_2(db &Db) ! {178	db.exec('PRAGMA foreign_keys=OFF')!179	db.exec('BEGIN IMMEDIATE')!180	upgrade_steps(db) or {181		db.exec('ROLLBACK') or {}182		db.exec('PRAGMA foreign_keys=ON') or {}183		return err184	}185	db.exec('COMMIT')!186	db.exec('PRAGMA foreign_keys=ON')!187	// Dropping save_files freed its pages but left them in the file; a one-time188	// VACUUM hands that space back, and it cannot run inside the transaction.189	db.exec('VACUUM')!190}191192struct V1Save {193	id            string194	parent        string195	message       string196	created_at    i64197	machine       string198	is_checkpoint bool199	size_bytes    i64200	agent         string201	session       string202	restores      string203	replayed_from string204}205206fn upgrade_steps(db &Db) ! {207	store := Store{208		db: db209	}210	db.exec(manifests_table)!211	db.exec('ALTER TABLE saves RENAME TO saves_v1')!212	db.exec('DROP INDEX IF EXISTS saves_parent')!213	db.exec(saves_table)!214	db.exec('CREATE INDEX saves_parent ON saves(parent)')!215	mut saves := []V1Save{}216	mut old := db.prepare('SELECT id, parent, message, created_at, machine, is_checkpoint, size_bytes,217		agent, session, restores, replayed_from FROM saves_v1 ORDER BY id')!218	for old.step()! {219		saves << V1Save{220			id:            old.text(0)221			parent:        old.text_or_none(1) or { '' }222			message:       old.text(2)223			created_at:    old.int(3)224			machine:       old.text(4)225			is_checkpoint: old.int(5) != 0226			size_bytes:    old.int(6)227			agent:         old.text_or_none(7) or { '' }228			session:       old.text_or_none(8) or { '' }229			restores:      old.text_or_none(9) or { '' }230			replayed_from: old.text_or_none(10) or { '' }231		}232	}233	old.finalize()234	mut files := db.prepare('SELECT path, hash, executable,235		COALESCE((SELECT size FROM objects WHERE objects.hash = save_files.hash), 0)236		FROM save_files WHERE save_id = ? ORDER BY path')!237	defer {238		files.finalize()239	}240	mut insert := db.prepare('INSERT INTO saves (id, parent, manifest, message, created_at, machine,241		is_checkpoint, size_bytes, agent, session, restores, replayed_from)242		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!243	defer {244		insert.finalize()245	}246	for save in saves {247		mut rows := []ManifestFile{}248		files.bind_text(1, save.id)!249		for files.step()! {250			rows << ManifestFile{251				path:       files.text(0)252				hash:       files.text(1)253				size:       files.int(3)254				executable: files.int(2) != 0255			}256		}257		files.reset()258		root := store.manifest_tree(rows)!259		insert.bind_text(1, save.id)!260		bind_optional(insert, 2, save.parent)!261		insert.bind_text(3, root)!262		insert.bind_text(4, save.message)!263		insert.bind_int(5, save.created_at)!264		insert.bind_text(6, save.machine)!265		insert.bind_int(7, if save.is_checkpoint { 1 } else { 0 })!266		insert.bind_int(8, save.size_bytes)!267		bind_optional(insert, 9, save.agent)!268		bind_optional(insert, 10, save.session)!269		bind_optional(insert, 11, save.restores)!270		bind_optional(insert, 12, save.replayed_from)!271		insert.step()!272		insert.reset()273	}274	db.exec('DROP TABLE save_files')!275	db.exec('DROP TABLE saves_v1')!276	db.exec('PRAGMA user_version = ${schema_version}')!277}278279// bind_optional writes NULL for an absent text, as the save columns expect.280fn bind_optional(stmt &Stmt, index int, value string) ! {281	if value == '' {282		stmt.bind_null(index)!283	} else {284		stmt.bind_text(index, value)!285	}286}287288// What any write says after waiting busy_timeout_ms for another writer.289pub const busy = 'another koh command is writing to this repo — wait for it to finish, then run this again'290291// begin takes the write lock at once (IMMEDIATE), so a second writer waits busy_timeout_ms here292// instead of failing part way through.293pub fn (s &Store) begin() ! {294	s.db.exec('BEGIN IMMEDIATE')!295}296297pub fn (s &Store) end() ! {298	s.db.exec('END')!299}300301// rollback drops its own failure: the caller is already returning the error that sent it here.302pub fn (s &Store) rollback() {303	s.db.exec('ROLLBACK') or {}304}305306// stripped_paths are the paths a whole-history strip removed. A strip bans its path for good,307// so no walk of the tree may pick it up again.308pub fn (s &Store) stripped_paths() ![]string {309	mut stmt := s.db.prepare("SELECT DISTINCT path FROM events WHERE kind = 'strip' AND IFNULL(save_id, '') = ''")!310	defer {311		stmt.finalize()312	}313	mut paths := []string{}314	for stmt.step()! {315		paths << stmt.text(0)316	}317	return paths318}319320// state reads a machine-local fact. A read error answers none, the same as unset.321pub fn (s &Store) state(key string) ?string {322	mut stmt := s.db.prepare('SELECT value FROM state WHERE key = ?') or { return none }323	defer {324		stmt.finalize()325	}326	stmt.bind_text(1, key) or { return none }327	if stmt.step() or { return none } {328		return stmt.text(0)329	}330	return none331}332333pub fn (s &Store) set_state(key string, value string) ! {334	mut stmt := s.db.prepare('INSERT INTO state (key, value) VALUES (?, ?)335		ON CONFLICT(key) DO UPDATE SET value = excluded.value')!336	defer {337		stmt.finalize()338	}339	stmt.bind_text(1, key)!340	stmt.bind_text(2, value)!341	stmt.step()!342}343344pub fn (s &Store) remove_state(key string) ! {345	mut stmt := s.db.prepare('DELETE FROM state WHERE key = ?')!346	defer {347		stmt.finalize()348	}349	stmt.bind_text(1, key)!350	stmt.step()!351}352353// backup writes a consistent copy of the database. `VACUUM INTO` never copies354// a WAL mid-write, which a raw file copy would.355pub fn (s &Store) backup(path string) ! {356	if os.exists(path) {357		return error('${path} already exists')358	}359	s.db.exec("VACUUM INTO '${path.replace("'", "''")}'")!360}361362// scrub rewrites the file and empties the write-ahead log, so the bytes a strip363// freed leave neither the free pages nor the WAL frames. The checkpoint comes364// first because VACUUM would otherwise carry the old frames along; the second365// one moves VACUUM's own writes out of the WAL and truncates it. VACUUM cannot366// run inside a transaction, so this is only called with none open.367pub fn (s &Store) scrub() ! {368	s.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')!369	s.db.exec('VACUUM')!370	s.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')!371}372373// integrity_check returns SQLite's complaints; empty means the file is sound.374pub fn (s &Store) integrity_check() ![]string {375	mut problems := []string{}376	mut stmt := s.db.prepare('PRAGMA integrity_check')!377	defer {378		stmt.finalize()379	}380	for stmt.step()! {381		line := stmt.text(0)382		if line != 'ok' {383			problems << line384		}385	}386	return problems387}