store.ts

11.5 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";6import { isTestPath } from "../describe/links.ts";78// Koh 3's schema (§5.1, `src/storage/storage.v`) minus `file_cache`, which only a working tree needs,9// plus `releases`: each version's release.json (§11.2) as read from the bucket, since that is bucket10// data too and pages and feeds need it on every request.11const SCHEMA_VERSION = 2;12const SCHEMA = `13CREATE TABLE objects (14	hash TEXT PRIMARY KEY,15	size INTEGER NOT NULL,16	data BLOB NOT NULL17);18CREATE TABLE saves (19	id            TEXT PRIMARY KEY,20	parent        TEXT REFERENCES saves(id),21	message       TEXT NOT NULL,22	created_at    INTEGER NOT NULL,23	machine       TEXT NOT NULL,24	is_checkpoint INTEGER NOT NULL DEFAULT 0,25	size_bytes    INTEGER NOT NULL DEFAULT 0,26	agent         TEXT,27	session       TEXT,28	restores      TEXT,29	replayed_from TEXT30);31CREATE TABLE save_files (32	save_id    TEXT NOT NULL REFERENCES saves(id),33	path       TEXT NOT NULL,34	hash       TEXT NOT NULL REFERENCES objects(hash),35	executable INTEGER NOT NULL DEFAULT 0,36	PRIMARY KEY (save_id, path)37);38CREATE TABLE events (39	id         TEXT PRIMARY KEY,40	kind       TEXT NOT NULL,41	save_id    TEXT,42	path       TEXT,43	reason     TEXT,44	created_at INTEGER NOT NULL,45	machine    TEXT NOT NULL46);47CREATE TABLE state (48	key   TEXT PRIMARY KEY,49	value TEXT NOT NULL50);51CREATE TABLE releases (52	version TEXT PRIMARY KEY,53	record  TEXT NOT NULL54);55CREATE INDEX saves_parent ON saves(parent);56CREATE INDEX save_files_hash ON save_files(hash);57`;5859/** An object as the bucket stores it: zlib bytes, already checked against its hash. */60export type StoredObject = { compressed: Uint8Array; size: number };6162/** What one sync brings in, landed in one transaction. Saves are oldest first. */63export type Landing = {64	head: string;65	releasesLatest: string;66	saves: SaveRecord[];67	objects: Map<string, StoredObject>;68	events: EventRecord[];69	releases: ReleaseRecord[];70	/** Escaped names of the paths these saves arrived without (§5.5, A3). */71	quarantined: string[];72	/** The operator's hidden paths (June, 2026-09-30), removed from every save like a strip. */73	hidden: string[];74};7576// A recount inflates every file at the newest save; a file this large is data, not lines of code.77const MAX_COUNTED = 8 * 1024 * 1024;7879// Display names for the header's language, by extension; data and docs formats never count.80const LANGUAGES: Record<string, string> = {81	ts: "TypeScript",82	tsx: "TypeScript",83	js: "JavaScript",84	mjs: "JavaScript",85	zig: "Zig",86	v: "V",87	rs: "Rust",88	go: "Go",89	py: "Python",90	c: "C",91	h: "C",92	cpp: "C++",93	cc: "C++",94	hpp: "C++",95	swift: "Swift",96	kt: "Kotlin",97	java: "Java",98	rb: "Ruby",99	lua: "Lua",100	sh: "Shell",101	nix: "Nix",102	css: "CSS",103	html: "HTML",104};105106// Vendored code is someone else's: counting Koh 3's bundled SQLite made it read as 290k lines of C.107const VENDORED = /(^|\/)(vendor|third_party|node_modules)\//;108// Bumped when what counts as a line changes, so every mirror recounts once when it opens.109const STATS_RULE = "source-only";110111const open = new Map<string, Database>();112113/** The mirror of one repo at `<dir>/<repo>.db`, created on first use and kept open. */114export function openMirror(dir: string, repo: string): Database {115	const path = join(dir, `${repo}.db`);116	const cached = open.get(path);117	if (cached) return cached;118	mkdirSync(dir, { recursive: true });119	const db = new Database(path, { strict: true });120	db.run("PRAGMA journal_mode = WAL");121	db.run("PRAGMA foreign_keys = ON");122	db.run("PRAGMA busy_timeout = 5000");123	const { user_version } = db.query<{ user_version: number }, []>("PRAGMA user_version").get() ?? {124		user_version: 0,125	};126	if (user_version !== 0 && user_version !== SCHEMA_VERSION) {127		db.close();128		throw new Error(129			`${path} has mirror schema version ${user_version}; this Kepr reads version ${SCHEMA_VERSION}. ` +130				"The mirror is disposable: delete it and the next sync rebuilds it from the bucket.",131		);132	}133	if (user_version === 0) {134		db.transaction(() => {135			db.run(SCHEMA);136			db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);137		})();138	}139	// Mirrors counted under an older rule are recounted now, not at the next save.140	if (mirrorState(db, "head") && mirrorState(db, "stats_rule") !== STATS_RULE) refreshStats(db);141	open.set(path, db);142	return db;143}144145export function mirrorState(db: Database, key: string): string | null {146	const row = db147		.query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?")148		.get(key);149	return row?.value ?? null;150}151152export function knownSave(db: Database, id: string): boolean {153	return db.query("SELECT 1 FROM saves WHERE id = ?").get(id) !== null;154}155156export function knownObject(db: Database, hash: string): boolean {157	return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null;158}159160export function knownEventIds(db: Database): Set<string> {161	const rows = db.query<{ id: string }, []>("SELECT id FROM events").all();162	return new Set(rows.map((row) => row.id));163}164165/** Drops a version deleted from the bucket; a sync only ever adds releases. */166export function forgetRelease(db: Database, version: string): void {167	db.query("DELETE FROM releases WHERE version = ?").run(version);168}169170export function knownReleases(db: Database): Set<string> {171	const rows = db.query<{ version: string }, []>("SELECT version FROM releases").all();172	return new Set(rows.map((row) => row.version));173}174175/** Lands a sync like Koh's steal: objects, events, saves, then every strip over every save. */176export function land(db: Database, landing: Landing): void {177	const putObject = db.query("INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)");178	const putEvent = db.query(179		"INSERT OR IGNORE INTO events (id, kind, save_id, path, reason, created_at, machine) VALUES " +180			"(?, ?, ?, ?, ?, ?, ?)",181	);182	const putSave = db.query(183		`INSERT OR IGNORE INTO saves (id, parent, message, created_at, machine, is_checkpoint, size_bytes,184			agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,185	);186	const putFile = db.query(187		"INSERT OR IGNORE INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)",188	);189	const putRelease = db.query("INSERT OR IGNORE INTO releases (version, record) VALUES (?, ?)");190	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");191	db.transaction(() => {192		for (const [hash, object] of landing.objects)193			putObject.run(hash, object.size, object.compressed);194		for (const e of landing.events) {195			putEvent.run(e.id, e.kind, e.save_id, e.path, e.reason, e.created_at, e.machine);196		}197		for (const s of landing.saves) {198			putSave.run(199				s.id,200				s.parent === "" ? null : s.parent,201				s.message,202				s.created_at,203				s.machine,204				s.is_checkpoint ? 1 : 0,205				s.size_bytes,206				s.agent,207				s.session,208				s.restores,209				s.replayed_from,210			);211			for (const f of s.files) putFile.run(s.id, f.path, f.hash, f.executable ? 1 : 0);212		}213		for (const r of landing.releases) putRelease.run(r.version, JSON.stringify(r));214		applyStrips(db);215		let hidden = 0;216		for (const path of landing.hidden) hidden += removePath(db, path, "");217		if (hidden > 0) db.run("DELETE FROM objects WHERE hash NOT IN (SELECT hash FROM save_files)");218		// In the same transaction as the removal, so the tarball key never names a list the rows219		// don't reflect yet.220		setState.run("hidden", landing.hidden.join("\n"));221		setState.run("head", landing.head);222		setState.run("releases_latest", landing.releasesLatest);223		const quarantined = new Set([...quarantinedPaths(db), ...landing.quarantined]);224		setState.run("quarantined", JSON.stringify([...quarantined].sort()));225	})();226	// Outside the transaction: the recount can inflate megabytes and needs no lock to be correct.227	refreshStats(db);228}229230/** Escaped names of every path this mirror's saves arrived without. */231export function quarantinedPaths(db: Database): string[] {232	return JSON.parse(mirrorState(db, "quarantined") ?? "[]");233}234235// §10.2: a strip of one save reaches that save; a strip of every save bans its path from all of236// history, whenever a save was made or arrives. Re-applying every strip is harmless, which is how a237// save that arrives after its strip event is covered too.238function applyStrips(db: Database): void {239	const strips = db240		.query<{ save_id: string; path: string }, []>(241			"SELECT save_id, path FROM events WHERE kind = 'strip'",242		)243		.all();244	if (strips.length === 0) return;245	for (const strip of strips) removePath(db, strip.path, strip.save_id);246	db.run("DELETE FROM objects WHERE hash NOT IN (SELECT hash FROM save_files)");247}248249/** Removes a path, file or folder, from one save or ('') every save; returns the rows removed. */250function removePath(db: Database, path: string, save: string): number {251	// Koh compares the prefix exactly, never with LIKE, so `_` and `%` in a path match only themselves.252	const dir = `${path.replace(/\/+$/, "")}/`;253	return db254		.query(255			`DELETE FROM save_files256			WHERE (path = $path OR substr(path, 1, length($dir)) = $dir)257			AND ($save = '' OR save_id = $save)`,258		)259		.run({ path, dir, save }).changes;260}261262/**263 * Empties a mirror in place so the next sync rebuilds it from the bucket, as a change to the264 * hidden paths needs. The file and its open handles stay, so a request holding one reads an empty265 * repo for a moment rather than failing. A new epoch keeps tarballs kept before it from matching.266 */267export function clearMirror(db: Database): void {268	db.transaction(() => {269		// Children before parents, for the foreign keys; every name is a table of SCHEMA's.270		for (const table of ["save_files", "events", "saves", "objects", "releases", "state"]) {271			db.run(`DELETE FROM ${table}`);272		}273		db.query("INSERT INTO state (key, value) VALUES ('epoch', ?)").run(crypto.randomUUID());274	})();275}276277// Lines and languages never change between syncs, so they are counted once here, not per view. They278// come from the newest real save, not `head`: a checkpoint's files are not public history (§21.4).279// Lines are source lines: files in a known language, tests left out; docs and data never count.280function refreshStats(db: Database): void {281	const save =282		db283			.query<{ id: string }, []>(284				"SELECT id FROM saves WHERE is_checkpoint = 0 ORDER BY rowid DESC LIMIT 1",285			)286			.get()?.id ?? "";287	const files = db288		.query<{ path: string; size: number; data: Uint8Array }, [string]>(289			"SELECT f.path, o.size, o.data FROM save_files f JOIN objects o ON o.hash = f.hash WHERE f.save_id = ?",290		)291		.all(save);292	let lines = 0;293	const byLanguage = new Map<string, number>();294	for (const file of files) {295		const language = LANGUAGES[file.path.split(".").pop() ?? ""];296		// Tests are not the program: counted, Koh 3's read as 18k lines of V where it has 11k.297		if (!language || VENDORED.test(file.path) || isTestPath(file.path)) continue;298		if (file.size > MAX_COUNTED) continue;299		const bytes = inflateSync(file.data);300		if (bytes.includes(0)) continue;301		let count = 0;302		for (const byte of bytes) if (byte === 10) count++;303		if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) count++;304		lines += count;305		byLanguage.set(language, (byLanguage.get(language) ?? 0) + count);306	}307	const languages = [...byLanguage].sort((a, b) => b[1] - a[1]);308	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");309	setState.run("lines", String(lines));310	setState.run("language", languages[0]?.[0] ?? "");311	setState.run("languages", JSON.stringify(languages));312	setState.run("stats_save", save);313	setState.run("stats_rule", STATS_RULE);314}