store.ts

21.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";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 foreign_keys = ON");194	db.run("PRAGMA busy_timeout = 5000");195	// A current mirror needs no lock; only creating or rebuilding one takes the write lock.196	if (schemaVersion(db) !== SCHEMA_VERSION) upgrade(db);197	// Mirrors counted under an older rule are recounted now, not at the next save.198	if (mirrorState(db, "head") && mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);199	open.set(path, db);200	return db;201}202203function schemaVersion(db: Database): number {204	return db.query<{ user_version: number }, []>("PRAGMA user_version").get()?.user_version ?? 0;205}206207export function mirrorState(db: Database, key: string): string | null {208	const row = db209		.query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?")210		.get(key);211	return row?.value ?? null;212}213214export function knownSave(db: Database, id: string): boolean {215	return db.query("SELECT 1 FROM saves WHERE id = ?").get(id) !== null;216}217218export function knownObject(db: Database, hash: string): boolean {219	return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null;220}221222/** Whether a save's tree can be flattened without fetching anything. */223export function knownManifest(db: Database, hash: string): boolean {224	return db.query("SELECT 1 FROM manifests WHERE hash = ?").get(hash) !== null;225}226227export function knownEventIds(db: Database): Set<string> {228	const rows = db.query<{ id: string }, []>("SELECT id FROM events").all();229	return new Set(rows.map((row) => row.id));230}231232/** Drops a version deleted from the bucket; a sync only ever adds releases. */233export function forgetRelease(db: Database, version: string): void {234	db.query("DELETE FROM releases WHERE version = ?").run(version);235}236237/** Replaces a version's record after Kepr rewrote it in the bucket. */238export function replaceRelease(db: Database, record: ReleaseRecord): void {239	db.query("UPDATE releases SET record = ? WHERE version = ?").run(240		JSON.stringify(record),241		record.version,242	);243}244245export function knownReleases(db: Database): Set<string> {246	const rows = db.query<{ version: string }, []>("SELECT version FROM releases").all();247	return new Set(rows.map((row) => row.version));248}249250/** Stores objects on their own, ahead of the save that refers to them. */251export function storeObjects(db: Database, objects: Map<string, StoredObject>): void {252	const put = db.query("INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)");253	db.transaction(() => {254		for (const [hash, object] of objects) put.run(hash, object.size, object.compressed);255	})();256}257258/** Stores folder manifests on their own, ahead of the save that names them. */259export function storeManifests(db: Database, manifests: Map<string, string>): void {260	const put = db.query("INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)");261	db.transaction(() => {262		for (const [hash, body] of manifests) {263			if (hashBody(body) !== hash) throw new Error(`manifest ${hash} does not match its body`);264			put.run(hash, body);265		}266	})();267}268269/**270 * Lands a sync like Koh's steal: objects, events, manifests, saves, then the strips the batch271 * names. A version-2 save keeps the tree the bucket fetched; a version-1 record is converted once,272 * so every later read is the same. Trees are never rewritten: a strip is read-time, which is why a273 * strip landing walks the saves once (for touches and unreferenced objects) and no other landing does.274 */275export function land(db: Database, landing: Landing): void {276	const putEvent = db.query(277		"INSERT OR IGNORE INTO events (id, kind, save_id, path, reason, created_at, machine) VALUES " +278			"(?, ?, ?, ?, ?, ?, ?)",279	);280	const putSave = db.query(281		`INSERT OR IGNORE INTO saves (id, parent, manifest, message, created_at, machine,282			is_checkpoint, size_bytes, agent, session, restores, replayed_from)283			VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,284	);285	const putManifest = db.query("INSERT OR IGNORE INTO manifests (hash, body) VALUES (?, ?)");286	const putRelease = db.query("INSERT OR IGNORE INTO releases (version, record) VALUES (?, ?)");287	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");288	const sizeOf = db.query<{ size: number }, [string]>("SELECT size FROM objects WHERE hash = ?");289	const stripped = landing.events.some((event) => event.kind === "strip");290	// Immediate: a landing with nothing new reads before it writes, and the request thread writes291	// mirrors too (a deleted release).292	db.transaction(() => {293		storeObjects(db, landing.objects);294		for (const e of landing.events) {295			putEvent.run(e.id, e.kind, e.save_id, e.path, e.reason, e.created_at, e.machine);296		}297		storeManifests(db, landing.manifests);298		for (const s of landing.saves) {299			let root = s.manifest ?? "";300			if (root === "") {301				const tree = manifestTree(s.files, (hash) => sizeOf.get(hash)?.size ?? null);302				for (const [hash, body] of tree.bodies) putManifest.run(hash, body);303				root = tree.root;304			} else if (manifestBody(db, root) === null) {305				throw new Error(`save ${s.id} names manifest ${root}, which did not land`);306			}307			putSave.run(308				s.id,309				s.parent === "" ? null : s.parent,310				root,311				s.message,312				s.created_at,313				s.machine,314				s.is_checkpoint ? 1 : 0,315				s.size_bytes,316				s.agent,317				s.session,318				s.restores,319				s.replayed_from,320			);321		}322		const landed = landing.saves.map((save) => save.id);323		for (const r of landing.releases) putRelease.run(r.version, JSON.stringify(r));324		if (stripped) dropStripped(db);325		else addKnownObjects(db, landing.saves);326		// A strip can reach any save, so every save's touches are worked out again after one.327		recordTouches(db, stripped ? 0 : Number(mirrorState(db, "touches_to") ?? 0));328		recordFacts(db, landed);329		setState.run("head", landing.head);330		setState.run("releases_latest", landing.releasesLatest);331		const quarantined = new Set([...quarantinedPaths(db), ...landing.quarantined]);332		setState.run("quarantined", JSON.stringify([...quarantined].sort()));333		const newest = newestRealSave(db);334		if (stripped || newest !== mirrorState(db, "stats_save")) staleStats(db);335	}).immediate();336	// Outside the transaction: the recount can inflate megabytes and needs no lock to be correct.337	if (mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);338}339340/**341 * Makes `hidden` the mirror's hidden list: the operator's hidden paths (June, 2026-09-30) and the342 * names ignored in every repo (June, 2026-10-01), each as `ANY_DEPTH` + name. Trees are never343 * rewritten, so the list lands at once and takes effect on the next read.344 */345export function applyHidden(db: Database, hidden: string[]): void {346	if (hiddenList(db).join("\n") === hidden.join("\n")) return;347	db.transaction(() => {348		db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('hidden', ?)").run(349			hidden.join("\n"),350		);351		recordTouches(db, 0);352		recordFacts(db, null);353		rebuildKnownObjects(db);354		staleStats(db);355	})();356	refreshStats(db);357}358359// Marks the counts out of date in the change's own transaction: if Kepr stops before the recount360// that follows, the mirror's next open does it.361function staleStats(db: Database): void {362	db.run("DELETE FROM state WHERE key = 'stats_rule'");363}364365function newestRealSave(db: Database): string {366	return (367		db368			.query<{ id: string }, []>(369				"SELECT id FROM saves WHERE is_checkpoint = 0 ORDER BY rowid DESC LIMIT 1",370			)371			.get()?.id ?? ""372	);373}374375/**376 * Records which real saves touched each path, for the saves after rowid `from`; 0 starts again.377 * A save touched a path when it was added, changed or removed against the real save before it;378 * checkpoints are skipped, so a change first recorded by a checkpoint counts at the next real save.379 */380function recordTouches(db: Database, from: number): void {381	if (from === 0) db.run("DELETE FROM touches");382	const previous = new Map<string, { hash: string; executable: boolean }>();383	const seed =384		from === 0385			? undefined386			: db387					.query<{ id: string }, [number]>(388						`SELECT id FROM saves389						WHERE is_checkpoint = 0 AND rowid <= ?390						ORDER BY rowid DESC LIMIT 1`,391					)392					.get(from)?.id;393	if (seed !== undefined) {394		for (const file of filesAt(db, seed)) previous.set(file.path, file);395	}396	const put = db.query("INSERT INTO touches (path, n) VALUES (?, ?)");397	const line = db398		.query<{ id: string; n: number }, [number]>(399			`SELECT id, rowid AS n FROM saves400			WHERE is_checkpoint = 0 AND rowid > ?401			ORDER BY rowid`,402		)403		.all(from);404	for (const save of line) {405		const current = new Map(filesAt(db, save.id).map((file) => [file.path, file]));406		for (const [path, file] of current) {407			const before = previous.get(path);408			if (!before || before.hash !== file.hash || before.executable !== file.executable) {409				put.run(path, save.n);410			}411		}412		for (const path of previous.keys()) if (!current.has(path)) put.run(path, save.n);413		previous.clear();414		for (const [path, file] of current) previous.set(path, file);415	}416	const last = db.query<{ n: number | null }, []>("SELECT MAX(rowid) AS n FROM saves").get()?.n;417	db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('touches_to', ?)").run(418		String(last ?? 0),419	);420}421422/**423 * Records what each file of the given saves (or, with null, every save) says about itself, once per424 * version and path. Only a pair the mirror has never described is inflated, so an ordinary landing425 * that re-lists unchanged files reads none of them.426 */427function recordFacts(db: Database, saves: string[] | null): void {428	const ids =429		saves ??430		db431			.query<{ id: string }, []>("SELECT id FROM saves ORDER BY rowid")432			.all()433			.map((r) => r.id);434	const has = db.query<{ one: number }, [string, string]>(435		"SELECT 1 AS one FROM facts WHERE hash = ? AND path = ?",436	);437	const dataOf = db.query<{ data: Uint8Array }, [string]>(438		"SELECT data FROM objects WHERE hash = ?",439	);440	const put = db.query(441		"INSERT OR IGNORE INTO facts (hash, path, lines, description, outline) VALUES (?, ?, ?, ?, ?)",442	);443	const seen = new Set<string>();444	for (const id of ids) {445		for (const file of filesAt(db, id)) {446			const key = `${file.hash}\n${file.path}`;447			if (seen.has(key)) continue;448			seen.add(key);449			if (has.get(file.hash, file.path)) continue;450			// The stored bytes are read only for a file small enough to describe.451			const facts = fileFacts(file.path, file.size, () => {452				const stored = dataOf.get(file.hash);453				if (stored === null) throw new Error(`object ${file.hash} is missing`);454				return inflateSync(stored.data);455			});456			put.run(457				file.hash,458				file.path,459				facts.lines,460				facts.description,461				facts.outline && JSON.stringify(facts.outline),462			);463		}464	}465}466467/** The objects real saves show, for the front page's "the library knows N things". */468function addKnownObjects(db: Database, saves: SaveRecord[]): void {469	const put = db.query("INSERT OR IGNORE INTO known_objects (hash) VALUES (?)");470	for (const save of saves) {471		// Checkpoints are working marks, not history (§21.4), as in the recount.472		if (save.is_checkpoint) continue;473		for (const file of filesAt(db, save.id)) put.run(file.hash);474	}475}476477function rebuildKnownObjects(db: Database): void {478	db.run("DELETE FROM known_objects");479	const put = db.query("INSERT OR IGNORE INTO known_objects (hash) VALUES (?)");480	const saves = db.query<{ id: string }, []>("SELECT id FROM saves WHERE is_checkpoint = 0").all();481	for (const save of saves) for (const file of filesAt(db, save.id)) put.run(file.hash);482}483484/**485 * Deletes the objects no save shows and no hidden path keeps, and recounts the objects real saves486 * show, so a strip erases what it removed. Only a landing that carries a strip event does this;487 * it is the one landing that walks the trees (for touches as well), and it rewrites no save's rows.488 */489function dropStripped(db: Database): void {490	const kept = new Set<string>();491	const saves = db.query<{ id: string }, []>("SELECT id FROM saves").all();492	for (const save of saves) for (const file of storedFilesAt(db, save.id)) kept.add(file.hash);493	const drop = db.query("DELETE FROM objects WHERE hash = ?");494	for (const row of db.query<{ hash: string }, []>("SELECT hash FROM objects").all()) {495		if (!kept.has(row.hash)) drop.run(row.hash);496	}497	db.run("DELETE FROM facts WHERE hash NOT IN (SELECT hash FROM objects)");498	rebuildKnownObjects(db);499}500501function hiddenList(db: Database): string[] {502	return mirrorState(db, "hidden")?.split("\n").filter(Boolean) ?? [];503}504505/** Escaped names of every path this mirror's saves arrived without. */506export function quarantinedPaths(db: Database): string[] {507	return JSON.parse(mirrorState(db, "quarantined") ?? "[]");508}509510// A file at a save as text, if it is there and small enough to be a manifest.511function smallFileText(db: Database, save: string, path: string): string | null {512	const file = fileAt(db, save, path);513	if (!file || file.size > MAX_MANIFEST) return null;514	const row = db515		.query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?")516		.get(file.hash);517	return row ? new TextDecoder("utf-8", { ignoreBOM: true }).decode(inflateSync(row.data)) : null;518}519520// Lines and languages never change between syncs, so they are counted once here, not per view. They521// come from the newest real save, not `head`: a checkpoint's files are not public history (§21.4).522// Lines are source lines: files in a known language, tests left out; docs and data never count.523// Read and written under one write lock: both threads recount, and a recount must never publish524// what it read before another thread's newer one.525function refreshStats(db: Database): void {526	db.transaction(() => recount(db)).immediate();527}528529function recount(db: Database): void {530	const save = newestRealSave(db);531	const files = save === "" ? [] : filesAt(db, save);532	const dataOf = db.query<{ data: Uint8Array }, [string]>(533		"SELECT data FROM objects WHERE hash = ?",534	);535	let lines = 0;536	const byLanguage = new Map<string, number>();537	for (const file of files) {538		const language = LANGUAGES[file.path.split(".").pop() ?? ""];539		// Tests are not the program: counted, Koh 3's read as 18k lines of V where it has 11k.540		if (!language || VENDORED.test(file.path) || isTestPath(file.path)) continue;541		if (file.size > MAX_COUNTED) continue;542		const stored = dataOf.get(file.hash);543		if (stored === null) continue;544		const bytes = inflateSync(stored.data);545		if (bytes.includes(0)) continue;546		let count = 0;547		for (const byte of bytes) if (byte === 10) count++;548		if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) count++;549		lines += count;550		byLanguage.set(language, (byLanguage.get(language) ?? 0) + count);551	}552	const languages = [...byLanguage].sort((a, b) => b[1] - a[1]);553	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");554	setState.run("lines", String(lines));555	setState.run("language", languages[0]?.[0] ?? "");556	setState.run("languages", JSON.stringify(languages));557	setState.run("stats_save", save);558	setState.run("declared_version", declaredVersion((path) => smallFileText(db, save, path)) ?? "");559	// Last, with the recount it names, so one cut short is done again at the next open.560	setState.run("stats_rule", STATS_RULE);561}