store.ts

7.4 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};8889// Vendored code is someone else's: counting Koh 3's bundled SQLite made it read as 290k lines of C.90const VENDORED = /(^|\/)(vendor|third_party|node_modules)\//;9192const open = new Map<string, Database>();9394/** The mirror of one repo at `<dir>/<repo>.db`, created on first use and kept open. */95export function openMirror(dir: string, repo: string): Database {96	const path = join(dir, `${repo}.db`);97	const cached = open.get(path);98	if (cached) return cached;99	mkdirSync(dir, { recursive: true });100	const db = new Database(path, { strict: true });101	db.run("PRAGMA journal_mode = WAL");102	db.run("PRAGMA foreign_keys = ON");103	db.run("PRAGMA busy_timeout = 5000");104	const { user_version } = db.query<{ user_version: number }, []>("PRAGMA user_version").get() ?? {105		user_version: 0,106	};107	if (user_version === 0) {108		db.transaction(() => {109			db.run(SCHEMA);110			db.run("PRAGMA user_version = 1");111		})();112	}113	open.set(path, db);114	return db;115}116117export function mirrorState(db: Database, key: string): string | null {118	const row = db119		.query<{ value: string }, [string]>("SELECT value FROM state WHERE key = ?")120		.get(key);121	return row?.value ?? null;122}123124export function knownSave(db: Database, id: string): boolean {125	return db.query("SELECT 1 FROM saves WHERE id = ?").get(id) !== null;126}127128export function knownObject(db: Database, hash: string): boolean {129	return db.query("SELECT 1 FROM objects WHERE hash = ?").get(hash) !== null;130}131132export function knownEventIds(db: Database): Set<string> {133	const rows = db.query<{ id: string }, []>("SELECT id FROM events").all();134	return new Set(rows.map((row) => row.id));135}136137/** Lands a sync like Koh's steal: objects, then events, then saves, then strips, all or nothing. */138export function land(db: Database, landing: Landing): void {139	const putObject = db.query("INSERT OR IGNORE INTO objects (hash, size, data) VALUES (?, ?, ?)");140	const putEvent = db.query(141		"INSERT OR IGNORE INTO events (id, kind, save_id, path, reason, created_at, machine) VALUES (?, ?, ?, ?, ?, ?, ?)",142	);143	const putSave = db.query(144		`INSERT OR IGNORE INTO saves (id, parent, message, created_at, machine, is_checkpoint, size_bytes,145			agent, session, restores, replayed_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,146	);147	const putFile = db.query(148		"INSERT OR IGNORE INTO save_files (save_id, path, hash, executable) VALUES (?, ?, ?, ?)",149	);150	db.transaction(() => {151		for (const [hash, object] of landing.objects)152			putObject.run(hash, object.size, object.compressed);153		for (const e of landing.events) {154			putEvent.run(e.id, e.kind, e.save_id, e.path, e.reason, e.created_at, e.machine);155		}156		for (const s of landing.saves) {157			putSave.run(158				s.id,159				s.parent === "" ? null : s.parent,160				s.message,161				s.created_at,162				s.machine,163				s.is_checkpoint ? 1 : 0,164				s.size_bytes,165				s.agent,166				s.session,167				s.restores,168				s.replayed_from,169			);170			for (const f of s.files) putFile.run(s.id, f.path, f.hash, f.executable ? 1 : 0);171		}172		applyStrips(db);173		db.query("INSERT OR REPLACE INTO state (key, value) VALUES ('head', ?)").run(landing.head);174		refreshStats(db, landing.head);175	})();176}177178// §10.2: a strip of one save reaches that save; a strip of every save reaches the saves made up to179// and including its own time, so a file saved again after the strip survives. Re-applying every180// strip is harmless, which lets a save that arrives after its strip event be covered too.181function applyStrips(db: Database): void {182	const strips = db183		.query<{ save_id: string; path: string; created_at: number }, []>(184			"SELECT save_id, path, created_at FROM events WHERE kind = 'strip'",185		)186		.all();187	if (strips.length === 0) return;188	const remove = db.query(189		`DELETE FROM save_files190		WHERE (path = $path OR substr(path, 1, length($dir)) = $dir)191		AND save_id IN (SELECT id FROM saves WHERE192			CASE WHEN $save = '' THEN created_at <= $at ELSE id = $save END)`,193	);194	for (const strip of strips) {195		// Koh compares the prefix exactly, never with LIKE, so `_` and `%` in a path match only themselves.196		const dir = `${strip.path.replace(/\/+$/, "")}/`;197		remove.run({ path: strip.path, dir, save: strip.save_id, at: strip.created_at });198	}199	db.run("DELETE FROM objects WHERE hash NOT IN (SELECT hash FROM save_files)");200}201202// Lines and language at `head` never change between syncs, so they are counted once here, not per view.203function refreshStats(db: Database, head: string): void {204	const files = db205		.query<{ path: string; data: Uint8Array }, [string]>(206			"SELECT f.path, o.data FROM save_files f JOIN objects o ON o.hash = f.hash WHERE f.save_id = ?",207		)208		.all(head);209	let lines = 0;210	const byLanguage = new Map<string, number>();211	for (const file of files) {212		if (VENDORED.test(file.path)) continue;213		const bytes = inflateSync(file.data);214		if (bytes.includes(0)) continue;215		let count = 0;216		for (const byte of bytes) if (byte === 10) count++;217		if (bytes.length > 0 && bytes[bytes.length - 1] !== 10) count++;218		lines += count;219		const language = LANGUAGES[file.path.split(".").pop() ?? ""];220		if (language) byLanguage.set(language, (byLanguage.get(language) ?? 0) + count);221	}222	const language = [...byLanguage].sort((a, b) => b[1] - a[1])[0]?.[0] ?? "";223	const setState = db.query("INSERT OR REPLACE INTO state (key, value) VALUES (?, ?)");224	setState.run("lines", String(lines));225	setState.run("language", language);226}