store.ts

9.6 KB · raw

1import { Database } from "bun:sqlite";2import { mkdirSync } from "node:fs";3import { join } from "node:path";4import { inflateSync } from "node:zlib";5import type { EventRecord, ReleaseRecord, SaveRecord } from "../bucket/repo.ts";67// Koh 3's schema (§5.1, `src/storage/storage.v`) minus `file_cache`, which only a working tree needs,8// plus `releases`: each version's release.json (§11.2) as read from the bucket, since that is bucket9// data too and pages and feeds need it on every request.10const SCHEMA_VERSION = 2;11const SCHEMA = `12CREATE TABLE objects (13	hash TEXT PRIMARY KEY,14	size INTEGER NOT NULL,15	data BLOB NOT NULL16);17CREATE TABLE saves (18	id            TEXT PRIMARY KEY,19	parent        TEXT REFERENCES saves(id),20	message       TEXT NOT NULL,21	created_at    INTEGER NOT NULL,22	machine       TEXT NOT NULL,23	is_checkpoint INTEGER NOT NULL DEFAULT 0,24	size_bytes    INTEGER NOT NULL DEFAULT 0,25	agent         TEXT,26	session       TEXT,27	restores      TEXT,28	replayed_from TEXT29);30CREATE TABLE save_files (31	save_id    TEXT NOT NULL REFERENCES saves(id),32	path       TEXT NOT NULL,33	hash       TEXT NOT NULL REFERENCES objects(hash),34	executable INTEGER NOT NULL DEFAULT 0,35	PRIMARY KEY (save_id, path)36);37CREATE TABLE events (38	id         TEXT PRIMARY KEY,39	kind       TEXT NOT NULL,40	save_id    TEXT,41	path       TEXT,42	reason     TEXT,43	created_at INTEGER NOT NULL,44	machine    TEXT NOT NULL45);46CREATE TABLE state (47	key   TEXT PRIMARY KEY,48	value TEXT NOT NULL49);50CREATE TABLE releases (51	version TEXT PRIMARY KEY,52	record  TEXT NOT NULL53);54CREATE INDEX saves_parent ON saves(parent);55CREATE INDEX save_files_hash ON save_files(hash);56`;5758/** An object as the bucket stores it: zlib bytes, already checked against its hash. */59export type StoredObject = { compressed: Uint8Array; size: number };6061/** What one sync brings in, landed in one transaction. Saves are oldest first. */62export type Landing = {63	head: string;64	releasesLatest: string;65	saves: SaveRecord[];66	objects: Map<string, StoredObject>;67	events: EventRecord[];68	releases: ReleaseRecord[];69	/** Escaped names of the paths these saves arrived without (§5.5, A3). */70	quarantined: string[];71};7273// A recount inflates every file at the newest save; a file this large is data, not lines of code.74const MAX_COUNTED = 8 * 1024 * 1024;7576// Display names for the header's language, by extension; data and docs formats never count.77const LANGUAGES: Record<string, string> = {78	ts: "TypeScript",79	tsx: "TypeScript",80	js: "JavaScript",81	mjs: "JavaScript",82	zig: "Zig",83	v: "V",84	rs: "Rust",85	go: "Go",86	py: "Python",87	c: "C",88	h: "C",89	cpp: "C++",90	cc: "C++",91	hpp: "C++",92	swift: "Swift",93	kt: "Kotlin",94	java: "Java",95	rb: "Ruby",96	lua: "Lua",97	sh: "Shell",98	nix: "Nix",99	css: "CSS",100	html: "HTML",101};102103// Vendored code is someone else's: counting Koh 3's bundled SQLite made it read as 290k lines of C.104const VENDORED = /(^|\/)(vendor|third_party|node_modules)\//;105106const open = new Map<string, Database>();107108/** The mirror of one repo at `<dir>/<repo>.db`, created on first use and kept open. */109export function openMirror(dir: string, repo: string): Database {110	const path = join(dir, `${repo}.db`);111	const cached = open.get(path);112	if (cached) return cached;113	mkdirSync(dir, { recursive: true });114	const db = new Database(path, { strict: true });115	db.run("PRAGMA journal_mode = WAL");116	db.run("PRAGMA foreign_keys = ON");117	db.run("PRAGMA busy_timeout = 5000");118	const { user_version } = db.query<{ user_version: number }, []>("PRAGMA user_version").get() ?? {119		user_version: 0,120	};121	if (user_version !== 0 && user_version !== SCHEMA_VERSION) {122		db.close();123		throw new Error(124			`${path} has mirror schema version ${user_version}; this Kepr reads version ${SCHEMA_VERSION}. ` +125				"The mirror is disposable: delete it and the next sync rebuilds it from the bucket.",126		);127	}128	if (user_version === 0) {129		db.transaction(() => {130			db.run(SCHEMA);131			db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);132		})();133	}134	// Mirrors whose stats predate `stats_save` (per-language lines, counted past checkpoints) are135	// recounted now, not at the next save.136	if (mirrorState(db, "head") && mirrorState(db, "stats_save") === null) refreshStats(db);137	open.set(path, db);138	return db;139}140141export function mirrorState(db: Database, key: string): string | null {142	const row = db143		.query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?")144		.get(key);145	return row?.value ?? null;146}147148export function knownSave(db: Database, id: string): boolean {149	return db.query("SELECT 1 FROM saves WHERE id = ?").get(id) !== null;150}151152export function knownObject(db: Database, hash: string): boolean {153	return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null;154}155156export function knownEventIds(db: Database): Set<string> {157	const rows = db.query<{ id: string }, []>("SELECT id FROM events").all();158	return new Set(rows.map((row) => row.id));159}160161export function knownReleases(db: Database): Set<string> {162	const rows = db.query<{ version: string }, []>("SELECT version FROM releases").all();163	return new Set(rows.map((row) => row.version));164}165166/** Lands a sync like Koh's steal: objects, events, saves, then every strip over every save. */167export function land(db: Database, landing: Landing): void {168	const putObject = db.query("INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)");169	const putEvent = db.query(170		"INSERT OR IGNORE INTO events (id, kind, save_id, path, reason, created_at, machine) VALUES " +171			"(?, ?, ?, ?, ?, ?, ?)",172	);173	const putSave = db.query(174		`INSERT OR IGNORE INTO saves (id, parent, message, created_at, machine, is_checkpoint, size_bytes,175			agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,176	);177	const putFile = db.query(178		"INSERT OR IGNORE INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)",179	);180	const putRelease = db.query("INSERT OR IGNORE INTO releases (version, record) VALUES (?, ?)");181	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");182	db.transaction(() => {183		for (const [hash, object] of landing.objects)184			putObject.run(hash, object.size, object.compressed);185		for (const e of landing.events) {186			putEvent.run(e.id, e.kind, e.save_id, e.path, e.reason, e.created_at, e.machine);187		}188		for (const s of landing.saves) {189			putSave.run(190				s.id,191				s.parent === "" ? null : s.parent,192				s.message,193				s.created_at,194				s.machine,195				s.is_checkpoint ? 1 : 0,196				s.size_bytes,197				s.agent,198				s.session,199				s.restores,200				s.replayed_from,201			);202			for (const f of s.files) putFile.run(s.id, f.path, f.hash, f.executable ? 1 : 0);203		}204		for (const r of landing.releases) putRelease.run(r.version, JSON.stringify(r));205		applyStrips(db);206		setState.run("head", landing.head);207		setState.run("releases_latest", landing.releasesLatest);208		const quarantined = new Set([...quarantinedPaths(db), ...landing.quarantined]);209		setState.run("quarantined", JSON.stringify([...quarantined].sort()));210	})();211	// Outside the transaction: the recount can inflate megabytes and needs no lock to be correct.212	refreshStats(db);213}214215/** Escaped names of every path this mirror's saves arrived without. */216export function quarantinedPaths(db: Database): string[] {217	return JSON.parse(mirrorState(db, "quarantined") ?? "[]");218}219220// §10.2: a strip of one save reaches that save; a strip of every save bans its path from all of221// history, whenever a save was made or arrives. Re-applying every strip is harmless, which is how a222// save that arrives after its strip event is covered too.223function applyStrips(db: Database): void {224	const strips = db225		.query<{ save_id: string; path: string }, []>(226			"SELECT save_id, path FROM events WHERE kind = 'strip'",227		)228		.all();229	if (strips.length === 0) return;230	const remove = db.query(231		`DELETE FROM save_files232		WHERE (path = $path OR substr(path, 1, length($dir)) = $dir)233		AND ($save = '' OR save_id = $save)`,234	);235	for (const strip of strips) {236		// Koh compares the prefix exactly, never with LIKE, so `_` and `%` in a path match only themselves.237		const dir = `${strip.path.replace(/\/+$/, "")}/`;238		remove.run({ path: strip.path, dir, save: strip.save_id });239	}240	db.run("DELETE FROM objects WHERE hash NOT IN (SELECT hash FROM save_files)");241}242243// Lines and languages never change between syncs, so they are counted once here, not per view. They244// come from the newest real save, not `head`: a checkpoint's files are not public history (§21.4).245function refreshStats(db: Database): void {246	const save =247		db248			.query<{ id: string }, []>(249				"SELECT id FROM saves WHERE is_checkpoint = 0 ORDER BY rowid DESC LIMIT 1",250			)251			.get()?.id ?? "";252	const files = db253		.query<{ path: string; size: number; data: Uint8Array }, [string]>(254			"SELECT f.path, o.size, o.data FROM save_files f JOIN objects o ON o.hash = f.hash WHERE f.save_id = ?",255		)256		.all(save);257	let lines = 0;258	const byLanguage = new Map<string, number>();259	for (const file of files) {260		if (VENDORED.test(file.path) || file.size > MAX_COUNTED) continue;261		const bytes = inflateSync(file.data);262		if (bytes.includes(0)) continue;263		let count = 0;264		for (const byte of bytes) if (byte === 10) count++;265		if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) count++;266		lines += count;267		const language = LANGUAGES[file.path.split(".").pop() ?? ""];268		if (language) byLanguage.set(language, (byLanguage.get(language) ?? 0) + count);269	}270	const languages = [...byLanguage].sort((a, b) => b[1] - a[1]);271	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");272	setState.run("lines", String(lines));273	setState.run("language", languages[0]?.[0] ?? "");274	setState.run("languages", JSON.stringify(languages));275	setState.run("stats_save", save);276}