store.ts

21.1 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";9import { hashBody, manifestBody, manifestTree } from "./manifest.ts";10import { fileAt, filesAt, storedFilesAt } from "./queries.ts";1112// Koh 3's schema (§5.1, `src/storage/storage.v`) minus `file_cache`, which only a working tree needs,13// plus `releases`: each version's release.json (§11.2) as read from the bucket, since that is bucket14// data too and pages and feeds need it on every request, and what the Atlas reads.15const SCHEMA_VERSION = 5;16// What pages read, worked out as each save lands rather than on every view (2026-10-02): which17// real saves touched each path (added, changed or removed against the real save before; `n` is the18// touching save's rowid), what each file says about itself, and the objects real saves refer to.19const SCHEMA = `20CREATE TABLE objects (21	hash TEXT PRIMARY KEY,22	size INTEGER NOT NULL,23	data BLOB NOT NULL24);25CREATE TABLE saves (26	id            TEXT PRIMARY KEY,27	parent        TEXT REFERENCES saves(id),28	manifest      TEXT NOT NULL,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);39CREATE TABLE manifests (40	hash TEXT PRIMARY KEY,41	body TEXT NOT NULL42) WITHOUT ROWID;43CREATE TABLE events (44	id         TEXT PRIMARY KEY,45	kind       TEXT NOT NULL,46	save_id    TEXT,47	path       TEXT,48	reason     TEXT,49	created_at INTEGER NOT NULL,50	machine    TEXT NOT NULL51);52CREATE TABLE state (53	key   TEXT PRIMARY KEY,54	value TEXT NOT NULL55);56CREATE TABLE releases (57	version TEXT PRIMARY KEY,58	record  TEXT NOT NULL59);60CREATE TABLE known_objects (hash TEXT PRIMARY KEY) WITHOUT ROWID;61CREATE TABLE touches (62	path TEXT NOT NULL,63	n    INTEGER NOT NULL64);65CREATE INDEX touches_n ON touches(n);66CREATE INDEX touches_path ON touches(path, n);67CREATE TABLE facts (68	hash        TEXT NOT NULL,69	path        TEXT NOT NULL,70	lines       INTEGER,71	description TEXT,72	outline     TEXT,73	PRIMARY KEY (hash, path)74);75CREATE INDEX saves_parent ON saves(parent);76`;7778/**79 * Creates a mirror, or rebuilds a disposable one: a mirror of another schema is emptied and the80 * next sync lands the repo again. Run under the write lock, since the request thread and the81 * sync's both open mirrors and must not both create or rebuild one.82 */83function upgrade(db: Database): void {84	db.transaction(() => {85		if (schemaVersion(db) !== 0) {86			for (const { name } of db87				.query<{ name: string }, []>(88					"SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",89				)90				.all()) {91				db.run(`DROP TABLE "${name.replaceAll('"', '""')}"`);92			}93		}94		db.run(SCHEMA);95		// A new epoch keeps tarballs made before the rebuild from ever being looked up again.96		db.query("INSERT OR IGNORE INTO state (key, value) VALUES ('epoch', ?)").run(97			crypto.randomUUID(),98		);99		db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);100	}).immediate();101}102103/** An object as the bucket stores it: zlib bytes, already checked against its hash. */104export type StoredObject = { compressed: Uint8Array; size: number };105106/** One batch of a sync, landed in one transaction. Saves are oldest first. */107export type Landing = {108	head: string;109	releasesLatest: string;110	saves: SaveRecord[];111	/** Folder bodies the saves' trees name, as fetched from the bucket (§9.2, format 2). */112	manifests: Map<string, string>;113	objects: Map<string, StoredObject>;114	events: EventRecord[];115	releases: ReleaseRecord[];116	/** Escaped names of the paths these saves arrived without (§5.5, A3). */117	quarantined: string[];118};119120/** Marks a hidden entry as a name matched at any depth rather than a path from the root. */121export const ANY_DEPTH = "**/";122123// No project declares its version in a file larger than this.124const MAX_MANIFEST = 1024 * 1024;125126// A recount inflates every file at the newest save; a file this large is data, not lines of code.127const MAX_COUNTED = 8 * 1024 * 1024;128129// Display names for the header's language, by extension; data and docs formats never count.130const LANGUAGES: Record<string, string> = {131	ts: "TypeScript",132	tsx: "TypeScript",133	js: "JavaScript",134	mjs: "JavaScript",135	zig: "Zig",136	v: "V",137	rs: "Rust",138	go: "Go",139	py: "Python",140	c: "C",141	h: "C",142	cpp: "C++",143	cc: "C++",144	hpp: "C++",145	swift: "Swift",146	kt: "Kotlin",147	java: "Java",148	rb: "Ruby",149	lua: "Lua",150	sh: "Shell",151	nix: "Nix",152	css: "CSS",153	html: "HTML",154};155156// Vendored code is someone else's: counting Koh 3's bundled SQLite made it read as 290k lines of C.157const VENDORED = /(^|\/)(vendor|third_party|node_modules)\//;158// Bumped when what the recount records changes, so every mirror recounts once when it opens.159const STATS_RULE = "source-only, known objects, declared version (ASCII whitespace, BOM)";160161const open = new Map<string, Database>();162163/** Closes a repo's mirror, so a rename can move its file. */164export function closeMirror(dir: string, repo: string): void {165	const path = join(dir, `${repo}.db`);166	open.get(path)?.close();167	open.delete(path);168}169170/**171 * Opens every mirror in `dir`, bringing each to this Kepr's schema: run at start, before Kepr172 * listens, so no request waits on a migration.173 */174export function openMirrors(dir: string): void {175	if (!existsSync(dir)) return;176	for (const name of readdirSync(dir)) if (name.endsWith(".db")) openMirror(dir, name.slice(0, -3));177}178179/** Closes every mirror this thread holds open; the next use of each opens it again. */180export function closeMirrors(): void {181	for (const db of open.values()) db.close();182	open.clear();183}184185/** The mirror of one repo at `<dir>/<repo>.db`, created on first use and kept open. */186export function openMirror(dir: string, repo: string): Database {187	const path = join(dir, `${repo}.db`);188	const cached = open.get(path);189	if (cached) return cached;190	mkdirSync(dir, { recursive: true });191	const db = new Database(path, { strict: true });192	db.run("PRAGMA journal_mode = WAL");193	db.run("PRAGMA busy_timeout = 5000");194	// A current mirror needs no lock; only creating or rebuilding one takes the write lock.195	if (schemaVersion(db) !== SCHEMA_VERSION) upgrade(db);196	// Only now: a rebuild drops tables other rows still reference, which foreign keys would refuse.197	db.run("PRAGMA foreign_keys = ON");198	// Mirrors counted under an older rule are recounted now, not at the next save.199	if (mirrorState(db, "head") && mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);200	open.set(path, db);201	return db;202}203204function schemaVersion(db: Database): number {205	return db.query<{ user_version: number }, []>("PRAGMA user_version").get()?.user_version ?? 0;206}207208export function mirrorState(db: Database, key: string): string | null {209	const row = db210		.query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?")211		.get(key);212	return row?.value ?? null;213}214215export function knownSave(db: Database, id: string): boolean {216	return db.query("SELECT 1 FROM saves WHERE id = ?").get(id) !== null;217}218219export function knownObject(db: Database, hash: string): boolean {220	return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null;221}222223/** Whether a save's tree can be flattened without fetching anything. */224export function knownManifest(db: Database, hash: string): boolean {225	return db.query("SELECT 1 FROM manifests WHERE hash = ?").get(hash) !== null;226}227228export function knownEventIds(db: Database): Set<string> {229	const rows = db.query<{ id: string }, []>("SELECT id FROM events").all();230	return new Set(rows.map((row) => row.id));231}232233/** Drops a version deleted from the bucket; a sync only ever adds releases. */234export function forgetRelease(db: Database, version: string): void {235	db.query("DELETE FROM releases WHERE version = ?").run(version);236}237238/** Replaces a version's record after Kepr rewrote it in the bucket. */239export function replaceRelease(db: Database, record: ReleaseRecord): void {240	db.query("UPDATE releases SET record = ? WHERE version = ?").run(241		JSON.stringify(record),242		record.version,243	);244}245246export function knownReleases(db: Database): Set<string> {247	const rows = db.query<{ version: string }, []>("SELECT version FROM releases").all();248	return new Set(rows.map((row) => row.version));249}250251/** Stores objects on their own, ahead of the save that refers to them. */252export function storeObjects(db: Database, objects: Map<string, StoredObject>): void {253	const put = db.query("INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)");254	db.transaction(() => {255		for (const [hash, object] of objects) put.run(hash, object.size, object.compressed);256	})();257}258259/** Stores folder manifests on their own, ahead of the save that names them. */260export function storeManifests(db: Database, manifests: Map<string, string>): void {261	const put = db.query("INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)");262	db.transaction(() => {263		for (const [hash, body] of manifests) {264			if (hashBody(body) !== hash) throw new Error(`manifest ${hash} does not match its body`);265			put.run(hash, body);266		}267	})();268}269270/**271 * Lands a sync like Koh's steal: objects, events, manifests, saves, then the strips the batch272 * names. A version-2 save keeps the tree the bucket fetched; a version-1 record is converted once,273 * so every later read is the same. Trees are never rewritten: a strip is read-time, which is why a274 * strip landing walks the saves once (for touches and unreferenced objects) and no other landing does.275 */276export function land(db: Database, landing: Landing): void {277	const putEvent = db.query(278		"INSERT OR IGNORE INTO events (id, kind, save_id, path, reason, created_at, machine) VALUES " +279			"(?, ?, ?, ?, ?, ?, ?)",280	);281	const putSave = db.query(282		`INSERT OR IGNORE INTO saves (id, parent, manifest, message, created_at, machine,283			is_checkpoint, size_bytes, agent, session, restores, replayed_from)284			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,285	);286	const putManifest = db.query("INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)");287	const putRelease = db.query("INSERT OR IGNORE INTO releases (version, record) VALUES (?, ?)");288	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");289	const sizeOf = db.query<{ size: number }, [string]>("SELECT size FROM objects WHERE hash = ?");290	const stripped = landing.events.some((event) => event.kind === "strip");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		storeManifests(db, landing.manifests);299		for (const s of landing.saves) {300			let root = s.manifest ?? "";301			if (root === "") {302				const tree = manifestTree(s.files, (hash) => sizeOf.get(hash)?.size ?? null);303				for (const [hash, body] of tree.bodies) putManifest.run(hash, body);304				root = tree.root;305			} else if (manifestBody(db, root) === null) {306				throw new Error(`save ${s.id} names manifest ${root}, which did not land`);307			}308			putSave.run(309				s.id,310				s.parent === "" ? null : s.parent,311				root,312				s.message,313				s.created_at,314				s.machine,315				s.is_checkpoint ? 1 : 0,316				s.size_bytes,317				s.agent,318				s.session,319				s.restores,320				s.replayed_from,321			);322		}323		const landed = landing.saves.map((save) => save.id);324		for (const r of landing.releases) putRelease.run(r.version, JSON.stringify(r));325		if (stripped) dropStripped(db);326		else addKnownObjects(db, landing.saves);327		// A strip can reach any save, so every save's touches are worked out again after one.328		recordTouches(db, stripped ? 0 : Number(mirrorState(db, "touches_to") ?? 0));329		recordFacts(db, landed);330		setState.run("head", landing.head);331		setState.run("releases_latest", landing.releasesLatest);332		const quarantined = new Set([...quarantinedPaths(db), ...landing.quarantined]);333		setState.run("quarantined", JSON.stringify([...quarantined].sort()));334		const newest = newestRealSave(db);335		if (stripped || newest !== mirrorState(db, "stats_save")) staleStats(db);336	}).immediate();337	// Outside the transaction: the recount can inflate megabytes and needs no lock to be correct.338	if (mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);339}340341/**342 * Makes `hidden` the mirror's hidden list: the operator's hidden paths (June, 2026-09-30) and the343 * names ignored in every repo (June, 2026-10-01), each as `ANY_DEPTH` + name. Trees are never344 * rewritten, so the list lands at once and takes effect on the next read.345 */346export function applyHidden(db: Database, hidden: string[]): void {347	if (hiddenList(db).join("\n") === hidden.join("\n")) return;348	db.transaction(() => {349		db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('hidden', ?)").run(350			hidden.join("\n"),351		);352		recordTouches(db, 0);353		recordFacts(db, null);354		rebuildKnownObjects(db);355		staleStats(db);356	})();357	refreshStats(db);358}359360// Marks the counts out of date in the change's own transaction: if Kepr stops before the recount361// that follows, the mirror's next open does it.362function staleStats(db: Database): void {363	db.run("DELETE FROM state WHERE key = 'stats_rule'");364}365366function newestRealSave(db: Database): string {367	return (368		db369			.query<{ id: string }, []>(370				"SELECT id FROM saves WHERE is_checkpoint = 0 ORDER BY rowid DESC LIMIT 1",371			)372			.get()?.id ?? ""373	);374}375376/**377 * Records which real saves touched each path, for the saves after rowid `from`; 0 starts again.378 * A save touched a path when it was added, changed or removed against the real save before it;379 * checkpoints are skipped, so a change first recorded by a checkpoint counts at the next real save.380 */381function recordTouches(db: Database, from: number): void {382	if (from === 0) db.run("DELETE FROM touches");383	const previous = new Map<string, { hash: string; executable: boolean }>();384	const seed =385		from === 0386			? undefined387			: db388					.query<{ id: string }, [number]>(389						`SELECT id FROM saves390						WHERE is_checkpoint = 0 AND rowid <= ?391						ORDER BY rowid DESC LIMIT 1`,392					)393					.get(from)?.id;394	if (seed !== undefined) {395		for (const file of filesAt(db, seed)) previous.set(file.path, file);396	}397	const put = db.query("INSERT INTO touches (path, n) VALUES (?, ?)");398	const line = db399		.query<{ id: string; n: number }, [number]>(400			`SELECT id, rowid AS n FROM saves401			WHERE is_checkpoint = 0 AND rowid > ?402			ORDER BY rowid`,403		)404		.all(from);405	for (const save of line) {406		const current = new Map(filesAt(db, save.id).map((file) => [file.path, file]));407		for (const [path, file] of current) {408			const before = previous.get(path);409			if (!before || before.hash !== file.hash || before.executable !== file.executable) {410				put.run(path, save.n);411			}412		}413		for (const path of previous.keys()) if (!current.has(path)) put.run(path, save.n);414		previous.clear();415		for (const [path, file] of current) previous.set(path, file);416	}417	const last = db.query<{ n: number | null }, []>("SELECT MAX(rowid) AS n FROM saves").get()?.n;418	db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('touches_to', ?)").run(419		String(last ?? 0),420	);421}422423/**424 * Records what each file of the given saves (or, with null, every save) says about itself, once per425 * version and path. Only a pair the mirror has never described is inflated, so an ordinary landing426 * that re-lists unchanged files reads none of them.427 */428function recordFacts(db: Database, saves: string[] | null): void {429	const ids =430		saves ??431		db432			.query<{ id: string }, []>("SELECT id FROM saves ORDER BY rowid")433			.all()434			.map((r) => r.id);435	const has = db.query<{ one: number }, [string, string]>(436		"SELECT 1 AS one FROM facts WHERE hash = ? AND path = ?",437	);438	const dataOf = db.query<{ data: Uint8Array }, [string]>(439		"SELECT data FROM objects WHERE hash = ?",440	);441	const put = db.query(442		"INSERT OR IGNORE INTO facts (hash, path, lines, description, outline) VALUES (?, ?, ?, ?, ?)",443	);444	const seen = new Set<string>();445	for (const id of ids) {446		for (const file of filesAt(db, id)) {447			const key = `${file.hash}\n${file.path}`;448			if (seen.has(key)) continue;449			seen.add(key);450			if (has.get(file.hash, file.path)) continue;451			// The stored bytes are read only for a file small enough to describe.452			const facts = fileFacts(file.path, file.size, () => {453				const stored = dataOf.get(file.hash);454				if (stored === null) throw new Error(`object ${file.hash} is missing`);455				return inflateSync(stored.data);456			});457			put.run(458				file.hash,459				file.path,460				facts.lines,461				facts.description,462				facts.outline && JSON.stringify(facts.outline),463			);464		}465	}466}467468/** The objects real saves show, for the front page's "the library knows N things". */469function addKnownObjects(db: Database, saves: SaveRecord[]): void {470	const put = db.query("INSERT OR IGNORE INTO known_objects (hash) VALUES (?)");471	for (const save of saves) {472		// Checkpoints are working marks, not history (§21.4), as in the recount.473		if (save.is_checkpoint) continue;474		for (const file of filesAt(db, save.id)) put.run(file.hash);475	}476}477478function rebuildKnownObjects(db: Database): void {479	db.run("DELETE FROM known_objects");480	const put = db.query("INSERT OR IGNORE INTO known_objects (hash) VALUES (?)");481	const saves = db.query<{ id: string }, []>("SELECT id FROM saves WHERE is_checkpoint = 0").all();482	for (const save of saves) for (const file of filesAt(db, save.id)) put.run(file.hash);483}484485/**486 * Deletes the objects no save shows and no hidden path keeps, and recounts the objects real saves487 * show, so a strip erases what it removed. Only a landing that carries a strip event does this;488 * it is the one landing that walks the trees (for touches as well), and it rewrites no save's rows.489 */490function dropStripped(db: Database): void {491	const kept = new Set<string>();492	const saves = db.query<{ id: string }, []>("SELECT id FROM saves").all();493	for (const save of saves) for (const file of storedFilesAt(db, save.id)) kept.add(file.hash);494	const drop = db.query("DELETE FROM objects WHERE hash = ?");495	for (const row of db.query<{ hash: string }, []>("SELECT hash FROM objects").all()) {496		if (!kept.has(row.hash)) drop.run(row.hash);497	}498	db.run("DELETE FROM facts WHERE hash NOT IN (SELECT hash FROM objects)");499	rebuildKnownObjects(db);500}501502function hiddenList(db: Database): string[] {503	return mirrorState(db, "hidden")?.split("\n").filter(Boolean) ?? [];504}505506/** Escaped names of every path this mirror's saves arrived without. */507export function quarantinedPaths(db: Database): string[] {508	return JSON.parse(mirrorState(db, "quarantined") ?? "[]");509}510511// A file at a save as text, if it is there and small enough to be a manifest.512function smallFileText(db: Database, save: string, path: string): string | null {513	const file = fileAt(db, save, path);514	if (!file || file.size > MAX_MANIFEST) return null;515	const row = db516		.query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?")517		.get(file.hash);518	return row ? new TextDecoder("utf-8", { ignoreBOM: true }).decode(inflateSync(row.data)) : null;519}520521// Lines and languages never change between syncs, so they are counted once here, not per view. They522// come from the newest real save, not `head`: a checkpoint's files are not public history (§21.4).523// Lines are source lines: files in a known language, tests left out; docs and data never count.524// Read and written under one write lock: both threads recount, and a recount must never publish525// what it read before another thread's newer one.526function refreshStats(db: Database): void {527	db.transaction(() => recount(db)).immediate();528}529530function recount(db: Database): void {531	const save = newestRealSave(db);532	const files = save === "" ? [] : filesAt(db, save);533	const dataOf = db.query<{ data: Uint8Array }, [string]>(534		"SELECT data FROM objects WHERE hash = ?",535	);536	let lines = 0;537	const byLanguage = new Map<string, number>();538	for (const file of files) {539		const language = LANGUAGES[file.path.split(".").pop() ?? ""];540		// Tests are not the program: counted, Koh 3's read as 18k lines of V where it has 11k.541		if (!language || VENDORED.test(file.path) || isTestPath(file.path)) continue;542		if (file.size > MAX_COUNTED) continue;543		const stored = dataOf.get(file.hash);544		if (stored === null) continue;545		const bytes = inflateSync(stored.data);546		if (bytes.includes(0)) continue;547		let count = 0;548		for (const byte of bytes) if (byte === 10) count++;549		if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) count++;550		lines += count;551		byLanguage.set(language, (byLanguage.get(language) ?? 0) + count);552	}553	const languages = [...byLanguage].sort((a, b) => b[1] - a[1]);554	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");555	setState.run("lines", String(lines));556	setState.run("language", languages[0]?.[0] ?? "");557	setState.run("languages", JSON.stringify(languages));558	setState.run("stats_save", save);559	setState.run("declared_version", declaredVersion((path) => smallFileText(db, save, path)) ?? "");560	// Last, with the recount it names, so one cut short is done again at the next open.561	setState.run("stats_rule", STATS_RULE);562}