storage.v

9.8 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.151	db.exec('PRAGMA journal_mode=WAL')!152	db.exec('PRAGMA synchronous=FULL')!153	db.exec('PRAGMA foreign_keys=ON')!154}155156fn check_version(db &Db) ! {157	mut stmt := db.prepare('PRAGMA user_version')!158	version := if stmt.step()! { stmt.int(0) } else { 0 }159	stmt.finalize()160	if version > schema_version {161		return error('this .koh was written by a newer koh (schema ${version}, this build knows ${schema_version})')162	}163	if version == schema_version {164		return165	}166	if version == 1 {167		return upgrade_1_to_2(db)168	}169	return error('this .koh needs an upgrade koh does not know how to do (schema ${version})')170}171172// upgrade_1_to_2 turns `save_files` into per-folder manifests. Foreign keys173// cannot change inside a transaction, so they are off around it; a failure174// rolls back and leaves the version-1 file as it was.175fn upgrade_1_to_2(db &Db) ! {176	db.exec('PRAGMA foreign_keys=OFF')!177	db.exec('BEGIN IMMEDIATE')!178	upgrade_steps(db) or {179		db.exec('ROLLBACK') or {}180		db.exec('PRAGMA foreign_keys=ON') or {}181		return err182	}183	db.exec('COMMIT')!184	db.exec('PRAGMA foreign_keys=ON')!185}186187struct V1Save {188	id            string189	parent        string190	message       string191	created_at    i64192	machine       string193	is_checkpoint bool194	size_bytes    i64195	agent         string196	session       string197	restores      string198	replayed_from string199}200201fn upgrade_steps(db &Db) ! {202	store := Store{203		db: db204	}205	db.exec(manifests_table)!206	db.exec('ALTER TABLE saves RENAME TO saves_v1')!207	db.exec('DROP INDEX IF EXISTS saves_parent')!208	db.exec(saves_table)!209	db.exec('CREATE INDEX saves_parent ON saves(parent)')!210	mut saves := []V1Save{}211	mut old := db.prepare('SELECT id, parent, message, created_at, machine, is_checkpoint, size_bytes,212		agent, session, restores, replayed_from FROM saves_v1 ORDER BY id')!213	for old.step()! {214		saves << V1Save{215			id:            old.text(0)216			parent:        old.text_or_none(1) or { '' }217			message:       old.text(2)218			created_at:    old.int(3)219			machine:       old.text(4)220			is_checkpoint: old.int(5) != 0221			size_bytes:    old.int(6)222			agent:         old.text_or_none(7) or { '' }223			session:       old.text_or_none(8) or { '' }224			restores:      old.text_or_none(9) or { '' }225			replayed_from: old.text_or_none(10) or { '' }226		}227	}228	old.finalize()229	mut files := db.prepare('SELECT path, hash, executable,230		COALESCE((SELECT size FROM objects WHERE objects.hash = save_files.hash), 0)231		FROM save_files WHERE save_id = ? ORDER BY path')!232	defer {233		files.finalize()234	}235	mut insert := db.prepare('INSERT INTO saves (id, parent, manifest, message, created_at, machine,236		is_checkpoint, size_bytes, agent, session, restores, replayed_from)237		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')!238	defer {239		insert.finalize()240	}241	for save in saves {242		mut rows := []ManifestFile{}243		files.bind_text(1, save.id)!244		for files.step()! {245			rows << ManifestFile{246				path:       files.text(0)247				hash:       files.text(1)248				size:       files.int(3)249				executable: files.int(2) != 0250			}251		}252		files.reset()253		root := store.manifest_tree(rows)!254		insert.bind_text(1, save.id)!255		bind_optional(insert, 2, save.parent)!256		insert.bind_text(3, root)!257		insert.bind_text(4, save.message)!258		insert.bind_int(5, save.created_at)!259		insert.bind_text(6, save.machine)!260		insert.bind_int(7, if save.is_checkpoint { 1 } else { 0 })!261		insert.bind_int(8, save.size_bytes)!262		bind_optional(insert, 9, save.agent)!263		bind_optional(insert, 10, save.session)!264		bind_optional(insert, 11, save.restores)!265		bind_optional(insert, 12, save.replayed_from)!266		insert.step()!267		insert.reset()268	}269	db.exec('DROP TABLE save_files')!270	db.exec('DROP TABLE saves_v1')!271	db.exec('PRAGMA user_version = ${schema_version}')!272}273274// bind_optional writes NULL for an absent text, as the save columns expect.275fn bind_optional(stmt &Stmt, index int, value string) ! {276	if value == '' {277		stmt.bind_null(index)!278	} else {279		stmt.bind_text(index, value)!280	}281}282283// What any write says after waiting busy_timeout_ms for another writer.284pub const busy = 'another koh command is writing to this repo — wait for it to finish, then run this again'285286// begin takes the write lock at once (IMMEDIATE), so a second writer waits busy_timeout_ms here287// instead of failing part way through.288pub fn (s &Store) begin() ! {289	s.db.exec('BEGIN IMMEDIATE')!290}291292pub fn (s &Store) end() ! {293	s.db.exec('END')!294}295296// rollback drops its own failure: the caller is already returning the error that sent it here.297pub fn (s &Store) rollback() {298	s.db.exec('ROLLBACK') or {}299}300301// stripped_paths are the paths a whole-history strip removed. A strip bans its path for good,302// so no walk of the tree may pick it up again.303pub fn (s &Store) stripped_paths() ![]string {304	mut stmt := s.db.prepare("SELECT DISTINCT path FROM events WHERE kind = 'strip' AND IFNULL(save_id, '') = ''")!305	defer {306		stmt.finalize()307	}308	mut paths := []string{}309	for stmt.step()! {310		paths << stmt.text(0)311	}312	return paths313}314315// state reads a machine-local fact. A read error answers none, the same as unset.316pub fn (s &Store) state(key string) ?string {317	mut stmt := s.db.prepare('SELECT value FROM state WHERE key = ?') or { return none }318	defer {319		stmt.finalize()320	}321	stmt.bind_text(1, key) or { return none }322	if stmt.step() or { return none } {323		return stmt.text(0)324	}325	return none326}327328pub fn (s &Store) set_state(key string, value string) ! {329	mut stmt := s.db.prepare('INSERT INTO state (key, value) VALUES (?, ?)330		ON CONFLICT(key) DO UPDATE SET value = excluded.value')!331	defer {332		stmt.finalize()333	}334	stmt.bind_text(1, key)!335	stmt.bind_text(2, value)!336	stmt.step()!337}338339pub fn (s &Store) remove_state(key string) ! {340	mut stmt := s.db.prepare('DELETE FROM state WHERE key = ?')!341	defer {342		stmt.finalize()343	}344	stmt.bind_text(1, key)!345	stmt.step()!346}347348// backup writes a consistent copy of the database. `VACUUM INTO` never copies349// a WAL mid-write, which a raw file copy would.350pub fn (s &Store) backup(path string) ! {351	if os.exists(path) {352		return error('${path} already exists')353	}354	s.db.exec("VACUUM INTO '${path.replace("'", "''")}'")!355}356357// integrity_check returns SQLite's complaints; empty means the file is sound.358pub fn (s &Store) integrity_check() ![]string {359	mut problems := []string{}360	mut stmt := s.db.prepare('PRAGMA integrity_check')!361	defer {362		stmt.finalize()363	}364	for stmt.step()! {365		line := stmt.text(0)366		if line != 'ok' {367			problems << line368		}369	}370	return problems371}