store.ts

7.2 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, 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.8const SCHEMA = `9CREATE TABLE objects (10	hash TEXT PRIMARY KEY,11	size INTEGER NOT NULL,12	data BLOB NOT NULL13);14CREATE TABLE saves (15	id            TEXT PRIMARY KEY,16	parent        TEXT REFERENCES saves(id),17	message       TEXT NOT NULL,18	created_at    INTEGER NOT NULL,19	machine       TEXT NOT NULL,20	is_checkpoint INTEGER NOT NULL DEFAULT 0,21	size_bytes    INTEGER NOT NULL DEFAULT 0,22	agent         TEXT,23	session       TEXT,24	restores      TEXT,25	replayed_from TEXT26);27CREATE TABLE save_files (28	save_id    TEXT NOT NULL REFERENCES saves(id),29	path       TEXT NOT NULL,30	hash       TEXT NOT NULL REFERENCES objects(hash),31	executable INTEGER NOT NULL DEFAULT 0,32	PRIMARY KEY (save_id, path)33);34CREATE TABLE events (35	id         TEXT PRIMARY KEY,36	kind       TEXT NOT NULL,37	save_id    TEXT,38	path       TEXT,39	reason     TEXT,40	created_at INTEGER NOT NULL,41	machine    TEXT NOT NULL42);43CREATE TABLE state (44	key   TEXT PRIMARY KEY,45	value TEXT NOT NULL46);47CREATE INDEX saves_parent ON saves(parent);48CREATE INDEX save_files_hash ON save_files(hash);49`;5051/** An object as the bucket stores it: zlib bytes, already checked against its hash. */52export type StoredObject = { compressed: Uint8Array; size: number };5354/** What one sync brings in, landed in one transaction. Saves are oldest first. */55export type Landing = {56	head: string;57	saves: SaveRecord[];58	objects: Map<string, StoredObject>;59	events: EventRecord[];60};6162// Display names for the header's language, by extension; data and docs formats never count.63const LANGUAGES: Record<string, string> = {64	ts: "TypeScript",65	tsx: "TypeScript",66	js: "JavaScript",67	mjs: "JavaScript",68	zig: "Zig",69	v: "V",70	rs: "Rust",71	go: "Go",72	py: "Python",73	c: "C",74	h: "C",75	cpp: "C++",76	cc: "C++",77	hpp: "C++",78	swift: "Swift",79	kt: "Kotlin",80	java: "Java",81	rb: "Ruby",82	lua: "Lua",83	sh: "Shell",84	nix: "Nix",85	css: "CSS",86	html: "HTML",87};8889const open = new Map<string, Database>();9091/** The mirror of one repo at `<dir>/<repo>.db`, created on first use and kept open. */92export function openMirror(dir: string, repo: string): Database {93	const path = join(dir, `${repo}.db`);94	const cached = open.get(path);95	if (cached) return cached;96	mkdirSync(dir, { recursive: true });97	const db = new Database(path, { strict: true });98	db.run("PRAGMA journal_mode = WAL");99	db.run("PRAGMA foreign_keys = ON");100	db.run("PRAGMA busy_timeout = 5000");101	const { user_version } = db.query<{ user_version: number }, []>("PRAGMA user_version").get() ?? {102		user_version: 0,103	};104	if (user_version === 0) {105		db.transaction(() => {106			db.run(SCHEMA);107			db.run("PRAGMA user_version = 1");108		})();109	}110	open.set(path, db);111	return db;112}113114export function mirrorState(db: Database, key: string): string | null {115	const row = db116		.query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?")117		.get(key);118	return row?.value ?? null;119}120121export function knownSave(db: Database, id: string): boolean {122	return db.query("SELECT 1 FROM saves WHERE id = ?").get(id) !== null;123}124125export function knownObject(db: Database, hash: string): boolean {126	return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null;127}128129export function knownEventIds(db: Database): Set<string> {130	const rows = db.query<{ id: string }, []>("SELECT id FROM events").all();131	return new Set(rows.map((row) => row.id));132}133134/** Lands a sync like Koh's steal: objects, then events, then saves, then strips, all or nothing. */135export function land(db: Database, landing: Landing): void {136	const putObject = db.query("INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)");137	const putEvent = db.query(138		"INSERT OR IGNORE INTO events (id, kind, save_id, path, reason, created_at, machine) VALUES (?, ?, ?, ?, ?, ?, ?)",139	);140	const putSave = db.query(141		`INSERT OR IGNORE INTO saves (id, parent, message, created_at, machine, is_checkpoint, size_bytes,142			agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,143	);144	const putFile = db.query(145		"INSERT OR IGNORE INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)",146	);147	db.transaction(() => {148		for (const [hash, object] of landing.objects)149			putObject.run(hash, object.size, object.compressed);150		for (const e of landing.events) {151			putEvent.run(e.id, e.kind, e.save_id, e.path, e.reason, e.created_at, e.machine);152		}153		for (const s of landing.saves) {154			putSave.run(155				s.id,156				s.parent === "" ? null : s.parent,157				s.message,158				s.created_at,159				s.machine,160				s.is_checkpoint ? 1 : 0,161				s.size_bytes,162				s.agent,163				s.session,164				s.restores,165				s.replayed_from,166			);167			for (const f of s.files) putFile.run(s.id, f.path, f.hash, f.executable ? 1 : 0);168		}169		applyStrips(db);170		db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('head', ?)").run(landing.head);171		refreshStats(db, landing.head);172	})();173}174175// §10.2: a strip of one save reaches that save; a strip of every save reaches the saves made up to176// and including its own time, so a file saved again after the strip survives. Re-applying every177// strip is harmless, which lets a save that arrives after its strip event be covered too.178function applyStrips(db: Database): void {179	const strips = db180		.query<{ save_id: string; path: string; created_at: number }, []>(181			"SELECT save_id, path, created_at FROM events WHERE kind = 'strip'",182		)183		.all();184	if (strips.length === 0) return;185	const remove = db.query(186		`DELETE FROM save_files187		WHERE (path = $path OR substr(path, 1, length($dir)) = $dir)188		AND save_id IN (SELECT id FROM saves WHERE189			CASE WHEN $save = '' THEN created_at <= $at ELSE id = $save END)`,190	);191	for (const strip of strips) {192		// Koh compares the prefix exactly, never with LIKE, so `_` and `%` in a path match only themselves.193		const dir = `${strip.path.replace(/\/+$/, "")}/`;194		remove.run({ path: strip.path, dir, save: strip.save_id, at: strip.created_at });195	}196	db.run("DELETE FROM objects WHERE hash NOT IN (SELECT hash FROM save_files)");197}198199// Lines and language at `head` never change between syncs, so they are counted once here, not per view.200function refreshStats(db: Database, head: string): void {201	const files = db202		.query<{ path: string; data: Uint8Array }, [string]>(203			"SELECT f.path, o.data FROM save_files f JOIN objects o ON o.hash = f.hash WHERE f.save_id = ?",204		)205		.all(head);206	let lines = 0;207	const byLanguage = new Map<string, number>();208	for (const file of files) {209		const bytes = inflateSync(file.data);210		if (bytes.includes(0)) continue;211		let count = 0;212		for (const byte of bytes) if (byte === 10) count++;213		if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) count++;214		lines += count;215		const language = LANGUAGES[file.path.split(".").pop() ?? ""];216		if (language) byLanguage.set(language, (byLanguage.get(language) ?? 0) + count);217	}218	const language = [...byLanguage].sort((a, b) => b[1] - a[1])[0]?.[0] ?? "";219	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");220	setState.run("lines", String(lines));221	setState.run("language", language);222}