store.ts

22.0 KB · raw

1import { Database } from "bun:sqlite";2import { existsSync, mkdirSync, readdirSync } from "node:fs";3import { join } from "node:path";4import { inflateSync } from "node:zlib";5import type { EventRecord, ReleaseRecord, SaveRecord } from "../bucket/repo.ts";6import { fileFacts } from "../describe/describe.ts";7import { isTestPath } from "../describe/links.ts";8import { declaredVersion } from "../describe/version.ts";910// Koh 3's schema (§5.1, `src/storage/storage.v`) minus `file_cache`, which only a working tree needs,11// plus `releases`: each version's release.json (§11.2) as read from the bucket, since that is bucket12// data too and pages and feeds need it on every request, `hidden_files`, and what the Atlas reads.13const SCHEMA_VERSION = 4;14// The operator's hidden rows, moved out of `save_files` rather than deleted, so a changed hidden15// list is applied in place, with nothing fetched again (2026-10-02).16const HIDDEN_FILES = `17CREATE TABLE hidden_files (18	save_id    TEXT NOT NULL REFERENCES saves(id),19	path       TEXT NOT NULL,20	hash       TEXT NOT NULL REFERENCES objects(hash),21	executable INTEGER NOT NULL DEFAULT 0,22	PRIMARY KEY (save_id, path)23);24`;25// What pages read, worked out as each save lands rather than on every view (2026-10-02): which26// real saves touched each path (added, changed or removed against the real save before; `n` is the27// touching save's rowid), what each file says about itself, and the objects real saves refer to.28const DERIVED = `29CREATE TABLE known_objects (hash TEXT PRIMARY KEY) WITHOUT ROWID;30CREATE TABLE touches (31	path TEXT NOT NULL,32	n    INTEGER NOT NULL33);34CREATE INDEX touches_n ON touches(n);35CREATE TABLE facts (36	hash        TEXT NOT NULL,37	path        TEXT NOT NULL,38	lines       INTEGER,39	description TEXT,40	outline     TEXT,41	PRIMARY KEY (hash, path)42);43`;44const SCHEMA = `45CREATE TABLE objects (46	hash TEXT PRIMARY KEY,47	size INTEGER NOT NULL,48	data BLOB NOT NULL49);50CREATE TABLE saves (51	id            TEXT PRIMARY KEY,52	parent        TEXT REFERENCES saves(id),53	message       TEXT NOT NULL,54	created_at    INTEGER NOT NULL,55	machine       TEXT NOT NULL,56	is_checkpoint INTEGER NOT NULL DEFAULT 0,57	size_bytes    INTEGER NOT NULL DEFAULT 0,58	agent         TEXT,59	session       TEXT,60	restores      TEXT,61	replayed_from TEXT62);63CREATE TABLE save_files (64	save_id    TEXT NOT NULL REFERENCES saves(id),65	path       TEXT NOT NULL,66	hash       TEXT NOT NULL REFERENCES objects(hash),67	executable INTEGER NOT NULL DEFAULT 0,68	PRIMARY KEY (save_id, path)69);70CREATE TABLE events (71	id         TEXT PRIMARY KEY,72	kind       TEXT NOT NULL,73	save_id    TEXT,74	path       TEXT,75	reason     TEXT,76	created_at INTEGER NOT NULL,77	machine    TEXT NOT NULL78);79CREATE TABLE state (80	key   TEXT PRIMARY KEY,81	value TEXT NOT NULL82);83CREATE TABLE releases (84	version TEXT PRIMARY KEY,85	record  TEXT NOT NULL86);87CREATE INDEX saves_parent ON saves(parent);88CREATE INDEX save_files_hash ON save_files(hash);89${HIDDEN_FILES}90${DERIVED}`;9192/** An object as the bucket stores it: zlib bytes, already checked against its hash. */93export type StoredObject = { compressed: Uint8Array; size: number };9495/** One batch of a sync, landed in one transaction. Saves are oldest first. */96export type Landing = {97	head: string;98	releasesLatest: string;99	saves: SaveRecord[];100	objects: Map<string, StoredObject>;101	events: EventRecord[];102	releases: ReleaseRecord[];103	/** Escaped names of the paths these saves arrived without (§5.5, A3). */104	quarantined: string[];105};106107/** Marks a hidden entry as a name matched at any depth rather than a path from the root. */108export const ANY_DEPTH = "**/";109110// No project declares its version in a file larger than this.111const MAX_MANIFEST = 1024 * 1024;112113// A recount inflates every file at the newest save; a file this large is data, not lines of code.114const MAX_COUNTED = 8 * 1024 * 1024;115116// Display names for the header's language, by extension; data and docs formats never count.117const LANGUAGES: Record<string, string> = {118	ts: "TypeScript",119	tsx: "TypeScript",120	js: "JavaScript",121	mjs: "JavaScript",122	zig: "Zig",123	v: "V",124	rs: "Rust",125	go: "Go",126	py: "Python",127	c: "C",128	h: "C",129	cpp: "C++",130	cc: "C++",131	hpp: "C++",132	swift: "Swift",133	kt: "Kotlin",134	java: "Java",135	rb: "Ruby",136	lua: "Lua",137	sh: "Shell",138	nix: "Nix",139	css: "CSS",140	html: "HTML",141};142143// Vendored code is someone else's: counting Koh 3's bundled SQLite made it read as 290k lines of C.144const VENDORED = /(^|\/)(vendor|third_party|node_modules)\//;145// Bumped when what the recount records changes, so every mirror recounts once when it opens.146const STATS_RULE = "source-only, known objects, declared version (ASCII whitespace, BOM)";147148const open = new Map<string, Database>();149150/** Closes a repo's mirror, so a rename can move its file. */151export function closeMirror(dir: string, repo: string): void {152	const path = join(dir, `${repo}.db`);153	open.get(path)?.close();154	open.delete(path);155}156157/**158 * Opens every mirror in `dir`, bringing each to this Kepr's schema: run at start, before Kepr159 * listens, so no request waits on a migration.160 */161export function openMirrors(dir: string): void {162	if (!existsSync(dir)) return;163	for (const name of readdirSync(dir)) if (name.endsWith(".db")) openMirror(dir, name.slice(0, -3));164}165166/** Closes every mirror this thread holds open; the next use of each opens it again. */167export function closeMirrors(): void {168	for (const db of open.values()) db.close();169	open.clear();170}171172/** The mirror of one repo at `<dir>/<repo>.db`, created on first use and kept open. */173export function openMirror(dir: string, repo: string): Database {174	const path = join(dir, `${repo}.db`);175	const cached = open.get(path);176	if (cached) return cached;177	mkdirSync(dir, { recursive: true });178	const db = new Database(path, { strict: true });179	db.run("PRAGMA journal_mode = WAL");180	db.run("PRAGMA foreign_keys = ON");181	db.run("PRAGMA busy_timeout = 5000");182	// A current mirror needs no lock; only creating or migrating one takes the write lock.183	const found = schemaVersion(db) === SCHEMA_VERSION ? SCHEMA_VERSION : upgrade(db);184	if (found !== 0 && found !== 2 && found !== 3 && found !== SCHEMA_VERSION) {185		db.close();186		throw new Error(187			`${path} has mirror schema version ${found}; this Kepr reads version ${SCHEMA_VERSION}. ` +188				"The mirror is disposable: delete it and the next sync rebuilds it from the bucket.",189		);190	}191	// A panel reads one path's touches; without this index every hover scans them (§21.5).192	db.run("CREATE INDEX IF NOT EXISTS touches_path ON touches(path, n)");193	// Mirrors counted under an older rule are recounted now, not at the next save.194	if (mirrorState(db, "head") && mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);195	open.set(path, db);196	return db;197}198199function schemaVersion(db: Database): number {200	return db.query<{ user_version: number }, []>("PRAGMA user_version").get()?.user_version ?? 0;201}202203/**204 * Creates or migrates a mirror and returns the version it found, read again under the write lock:205 * the request thread and the sync's both open mirrors, and must not both create or migrate one.206 */207function upgrade(db: Database): number {208	return db209		.transaction(() => {210			const found = schemaVersion(db);211			if (found === SCHEMA_VERSION || ![0, 2, 3].includes(found)) return found;212			if (found === 0) db.run(SCHEMA);213			if (found === 2) db.run(HIDDEN_FILES);214			if (found === 2 || found === 3) db.run(DERIVED);215			// Version 2 deleted hidden rows, so only the bucket can bring them back on unhide.216			if (found === 2 && mirrorState(db, "hidden")) clearMirror(db);217			else if (found !== 0) {218				recordTouches(db, 0);219				recordFacts(db, null);220			}221			db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);222			return found;223		})224		.immediate();225}226227export function mirrorState(db: Database, key: string): string | null {228	const row = db229		.query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?")230		.get(key);231	return row?.value ?? null;232}233234export function knownSave(db: Database, id: string): boolean {235	return db.query("SELECT 1 FROM saves WHERE id = ?").get(id) !== null;236}237238export function knownObject(db: Database, hash: string): boolean {239	return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null;240}241242export function knownEventIds(db: Database): Set<string> {243	const rows = db.query<{ id: string }, []>("SELECT id FROM events").all();244	return new Set(rows.map((row) => row.id));245}246247/** Drops a version deleted from the bucket; a sync only ever adds releases. */248export function forgetRelease(db: Database, version: string): void {249	db.query("DELETE FROM releases WHERE version = ?").run(version);250}251252/** Replaces a version's record after Kepr rewrote it in the bucket. */253export function replaceRelease(db: Database, record: ReleaseRecord): void {254	db.query("UPDATE releases SET record = ? WHERE version = ?").run(255		JSON.stringify(record),256		record.version,257	);258}259260export function knownReleases(db: Database): Set<string> {261	const rows = db.query<{ version: string }, []>("SELECT version FROM releases").all();262	return new Set(rows.map((row) => row.version));263}264265/** Stores objects on their own, ahead of the save that refers to them. */266export function storeObjects(db: Database, objects: Map<string, StoredObject>): void {267	const put = db.query("INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)");268	db.transaction(() => {269		for (const [hash, object] of objects) put.run(hash, object.size, object.compressed);270	})();271}272273/**274 * Lands a sync like Koh's steal: objects, events, saves, then every strip over every save. The new275 * saves are hidden by the list the mirror holds; `applyHidden` changes that list.276 */277export function land(db: Database, landing: Landing): void {278	const putEvent = db.query(279		"INSERT OR IGNORE INTO events (id, kind, save_id, path, reason, created_at, machine) VALUES " +280			"(?, ?, ?, ?, ?, ?, ?)",281	);282	const putSave = db.query(283		`INSERT OR IGNORE INTO saves (id, parent, message, created_at, machine, is_checkpoint, size_bytes,284			agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,285	);286	const putFile = db.query(287		"INSERT OR IGNORE INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)",288	);289	const putRelease = db.query("INSERT OR IGNORE INTO releases (version, record) VALUES (?, ?)");290	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");291	// Immediate: a landing with nothing new reads before it writes, and the request thread writes292	// mirrors too (a deleted release).293	db.transaction(() => {294		storeObjects(db, landing.objects);295		for (const e of landing.events) {296			putEvent.run(e.id, e.kind, e.save_id, e.path, e.reason, e.created_at, e.machine);297		}298		for (const s of landing.saves) {299			putSave.run(300				s.id,301				s.parent === "" ? null : s.parent,302				s.message,303				s.created_at,304				s.machine,305				s.is_checkpoint ? 1 : 0,306				s.size_bytes,307				s.agent,308				s.session,309				s.restores,310				s.replayed_from,311			);312			for (const f of s.files) putFile.run(s.id, f.path, f.hash, f.executable ? 1 : 0);313		}314		for (const r of landing.releases) putRelease.run(r.version, JSON.stringify(r));315		const stripped = applyStrips(db);316		const landed = landing.saves.map((save) => save.id);317		hideRows(db, hiddenList(db), landed);318		// A strip can reach any save, so every save's touches are worked out again after one.319		recordTouches(db, stripped ? 0 : Number(mirrorState(db, "touches_to") ?? 0));320		recordFacts(db, landed);321		setState.run("head", landing.head);322		setState.run("releases_latest", landing.releasesLatest);323		const quarantined = new Set([...quarantinedPaths(db), ...landing.quarantined]);324		setState.run("quarantined", JSON.stringify([...quarantined].sort()));325		staleStats(db);326	}).immediate();327	// Outside the transaction: the recount can inflate megabytes and needs no lock to be correct.328	refreshStats(db);329}330331/**332 * Makes `hidden` the mirror's hidden list: the operator's hidden paths (June, 2026-09-30) and the333 * names ignored in every repo (June, 2026-10-01), each as `ANY_DEPTH` + name. Rows move between334 * `save_files` and `hidden_files`, so it takes milliseconds and fetches nothing.335 */336export function applyHidden(db: Database, hidden: string[]): void {337	if (hiddenList(db).join("\n") === hidden.join("\n")) return;338	db.transaction(() => {339		db.run(340			`INSERT OR IGNORE INTO save_files (save_id, path, hash, executable)341			SELECT save_id, path, hash, executable FROM hidden_files`,342		);343		db.run("DELETE FROM hidden_files");344		hideRows(db, hidden, null);345		recordTouches(db, 0);346		recordFacts(db, null);347		staleStats(db);348	})();349	refreshStats(db);350}351352// Marks the counts out of date in the change's own transaction: if Kepr stops before the recount353// that follows, the mirror's next open does it.354function staleStats(db: Database): void {355	db.run("DELETE FROM state WHERE key = 'stats_rule'");356}357358/**359 * Records which real saves touched each path, for the saves after rowid `from`; 0 starts again.360 * A save touched a path when it was added, changed or removed against the real save before it;361 * checkpoints are skipped, so a change first recorded by a checkpoint counts at the next real save.362 */363function recordTouches(db: Database, from: number): void {364	if (from === 0) db.run("DELETE FROM touches");365	db.query(366		`WITH line AS (367			SELECT id, rowid AS n, LAG(id) OVER (ORDER BY rowid) AS prev368			FROM saves369			WHERE is_checkpoint = 0370		)371		INSERT INTO touches (path, n)372		SELECT f.path, line.n373		FROM line374		JOIN save_files f ON f.save_id = line.id375		LEFT JOIN save_files p ON p.save_id = line.prev AND p.path = f.path376		WHERE line.n > $from377		AND (p.hash IS NOT f.hash OR p.executable IS NOT f.executable)378		UNION ALL379		SELECT p.path, line.n380		FROM line381		JOIN save_files p ON p.save_id = line.prev382		WHERE line.n > $from383		AND NOT EXISTS (SELECT 1 FROM save_files f WHERE f.save_id = line.id AND f.path = p.path)`,384	).run({ from });385	const last = db.query<{ n: number | null }, []>("SELECT MAX(rowid) AS n FROM saves").get()?.n;386	db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('touches_to', ?)").run(387		String(last ?? 0),388	);389}390391/** Records what each file of the given saves, or (null) every save, says about itself, once per version and path. */392function recordFacts(db: Database, saves: string[] | null): void {393	const wanted = db394		.query<{ hash: string; path: string }, { all: number; saves: string }>(395			`SELECT DISTINCT f.hash, f.path396			FROM save_files f397			WHERE ($all = 1 OR f.save_id IN (SELECT value FROM json_each($saves)))398			AND NOT EXISTS (SELECT 1 FROM facts x WHERE x.hash = f.hash AND x.path = f.path)`,399		)400		.all({ all: saves === null ? 1 : 0, saves: JSON.stringify(saves ?? []) });401	const sizeOf = db.query<{ size: number }, [string]>("SELECT size FROM objects WHERE hash = ?");402	const dataOf = db.query<{ data: Uint8Array }, [string]>(403		"SELECT data FROM objects WHERE hash = ?",404	);405	const put = db.query(406		"INSERT OR IGNORE INTO facts (hash, path, lines, description, outline) VALUES (?, ?, ?, ?, ?)",407	);408	for (const { hash, path } of wanted) {409		const size = sizeOf.get(hash)?.size;410		if (size === undefined) continue;411		// The stored bytes are read only for a file small enough to describe.412		const read = () => inflateSync((dataOf.get(hash) as { data: Uint8Array }).data);413		const facts = fileFacts(path, size, read);414		put.run(415			hash,416			path,417			facts.lines,418			facts.description,419			facts.outline && JSON.stringify(facts.outline),420		);421	}422}423424function hiddenList(db: Database): string[] {425	return mirrorState(db, "hidden")?.split("\n").filter(Boolean) ?? [];426}427428// Moves the rows `hidden` matches, in the `saves` given or (null) every save, into `hidden_files`.429// The list is recorded in the same transaction, so the tarball key never names a list the rows430// don't reflect yet.431function hideRows(db: Database, hidden: string[], saves: string[] | null): void {432	for (const entry of hidden) {433		const { where, params } = pathMatch(entry);434		const scope = { ...params, all: saves === null ? 1 : 0, saves: JSON.stringify(saves ?? []) };435		const chosen = `${where} AND ($all = 1 OR save_id IN (SELECT value FROM json_each($saves)))`;436		db.query(437			`INSERT OR IGNORE INTO hidden_files (save_id, path, hash, executable)438			SELECT save_id, path, hash, executable FROM save_files439			WHERE ${chosen}`,440		).run(scope);441		db.query(`DELETE FROM save_files WHERE ${chosen}`).run(scope);442	}443	db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('hidden', ?)").run(hidden.join("\n"));444}445446/** Escaped names of every path this mirror's saves arrived without. */447export function quarantinedPaths(db: Database): string[] {448	return JSON.parse(mirrorState(db, "quarantined") ?? "[]");449}450451// §10.2: a strip of one save reaches that save; a strip of every save bans its path from all of452// history, whenever a save was made or arrives. Re-applying every strip is harmless, which is how a453// save that arrives after its strip event is covered too.454// Returns whether any save lost a file.455function applyStrips(db: Database): boolean {456	const strips = db457		.query<{ save_id: string; path: string }, []>(458			"SELECT save_id, path FROM events WHERE kind = 'strip'",459		)460		.all();461	if (strips.length === 0) return false;462	let removed = 0;463	for (const strip of strips) {464		const { where, params } = pathMatch(strip.path);465		// Hidden rows too, so unhiding never brings back what a strip removed.466		for (const table of ["save_files", "hidden_files"]) {467			removed += db468				.query(`DELETE FROM ${table} WHERE ${where} AND ($save = '' OR save_id = $save)`)469				.run({ ...params, save: strip.save_id }).changes;470		}471	}472	db.run(473		`DELETE FROM objects474		WHERE hash NOT IN (SELECT hash FROM save_files)475		AND hash NOT IN (SELECT hash FROM hidden_files)`,476	);477	db.run("DELETE FROM facts WHERE hash NOT IN (SELECT hash FROM objects)");478	return removed > 0;479}480481/** The SQL condition matching a path, file or folder, or an `ANY_DEPTH` name at any depth. */482function pathMatch(path: string): { where: string; params: Record<string, string> } {483	if (path.startsWith(ANY_DEPTH)) {484		return {485			where: "instr('/' || path || '/', $segment) > 0",486			params: { segment: `/${path.slice(ANY_DEPTH.length)}/` },487		};488	}489	// Koh compares the prefix exactly, never with LIKE, so `_` and `%` in a path match only themselves.490	return {491		where: "(path = $path OR substr(path, 1, length($dir)) = $dir)",492		params: { path, dir: `${path.replace(/\/+$/, "")}/` },493	};494}495496/**497 * Empties a mirror in place so the next sync rebuilds it from the bucket, as the move to schema498 * version 3 needs when hidden rows were deleted. The file and its open handles stay, so a request holding one reads an empty499 * repo for a moment rather than failing. A new epoch keeps tarballs kept before it from matching.500 */501export function clearMirror(db: Database): void {502	db.transaction(() => {503		// Children before parents, for the foreign keys; every name is a table of SCHEMA's.504		const tables = [505			"save_files",506			"hidden_files",507			"touches",508			"facts",509			"known_objects",510			"events",511			"saves",512			"objects",513			"releases",514			"state",515		];516		for (const table of tables) {517			db.run(`DELETE FROM ${table}`);518		}519		db.query("INSERT INTO state (key, value) VALUES ('epoch', ?)").run(crypto.randomUUID());520	})();521}522523// A file at a save as text, if it is there and small enough to be a manifest.524function smallFileText(db: Database, save: string, path: string): string | null {525	const row = db526		.query<{ size: number; data: Uint8Array }, [string, string]>(527			`SELECT o.size, o.data528			FROM save_files f529			JOIN objects o ON o.hash = f.hash530			WHERE f.save_id = ?531			AND f.path = ?`,532		)533		.get(save, path);534	return row && row.size <= MAX_MANIFEST535		? new TextDecoder("utf-8", { ignoreBOM: true }).decode(inflateSync(row.data))536		: null;537}538539// Lines and languages never change between syncs, so they are counted once here, not per view. They540// come from the newest real save, not `head`: a checkpoint's files are not public history (§21.4).541// Lines are source lines: files in a known language, tests left out; docs and data never count.542// Read and written under one write lock: both threads recount, and a recount must never publish543// what it read before another thread's newer one.544function refreshStats(db: Database): void {545	db.transaction(() => recount(db)).immediate();546}547548function recount(db: Database): void {549	const save =550		db551			.query<{ id: string }, []>(552				"SELECT id FROM saves WHERE is_checkpoint = 0 ORDER BY rowid DESC LIMIT 1",553			)554			.get()?.id ?? "";555	const files = db556		.query<{ path: string; size: number; data: Uint8Array }, [string]>(557			"SELECT f.path, o.size, o.data FROM save_files f JOIN objects o ON o.hash = f.hash WHERE f.save_id = ?",558		)559		.all(save);560	let lines = 0;561	const byLanguage = new Map<string, number>();562	for (const file of files) {563		const language = LANGUAGES[file.path.split(".").pop() ?? ""];564		// Tests are not the program: counted, Koh 3's read as 18k lines of V where it has 11k.565		if (!language || VENDORED.test(file.path) || isTestPath(file.path)) continue;566		if (file.size > MAX_COUNTED) continue;567		const bytes = inflateSync(file.data);568		if (bytes.includes(0)) continue;569		let count = 0;570		for (const byte of bytes) if (byte === 10) count++;571		if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) count++;572		lines += count;573		byLanguage.set(language, (byLanguage.get(language) ?? 0) + count);574	}575	const languages = [...byLanguage].sort((a, b) => b[1] - a[1]);576	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");577	setState.run("lines", String(lines));578	setState.run("language", languages[0]?.[0] ?? "");579	setState.run("languages", JSON.stringify(languages));580	setState.run("stats_save", save);581	setState.run("declared_version", declaredVersion((path) => smallFileText(db, save, path)) ?? "");582	// §21.1's "the library knows N things": the file contents any real save refers to, which the583	// front page unites across public repos. From `objects`, probing save_files_hash: a DISTINCT584	// over save_files reads saves × files rows.585	db.run("DELETE FROM known_objects");586	db.run(587		`INSERT INTO known_objects (hash)588		SELECT o.hash589		FROM objects o590		WHERE EXISTS (591			SELECT 1592			FROM save_files f593			JOIN saves s ON s.id = f.save_id594			WHERE f.hash = o.hash595			AND s.is_checkpoint = 0596		)`,597	);598	// Last, with the recount it names, so one cut short is done again at the next open.599	setState.run("stats_rule", STATS_RULE);600}