queries.ts

8.2 KB · raw

1import type { Database } from "bun:sqlite";2import { createHash } from "node:crypto";3import { inflateSync } from "node:zlib";4import type { ReleaseRecord } from "../bucket/repo.ts";5import { mirrorState } from "./store.ts";67export type Save = {8	id: string;9	parent: string;10	message: string;11	created_at: number;12	machine: string;13	agent: string;14	session: string;15	is_checkpoint: boolean;16};1718export type FileEntry = { path: string; hash: string; executable: boolean; size: number };1920/** The saves that touched each path up to one save, oldest first; `line` is every one of21 * them in line order. */22export type Touches = { line: Save[]; byPath: Map<string, Save[]> };2324export type RepoStats = { saves: number; lines: number; language: string; updated: number | null };2526const SAVE_COLUMNS = `id, COALESCE(parent, '') AS parent, message, created_at, machine,27	COALESCE(agent, '') AS agent, COALESCE(session, '') AS session, is_checkpoint = 1 AS is_checkpoint`;28const LINE_COLUMNS =29	"line.id, line.parent, line.message, line.created_at, line.machine, line.agent, line.session, line.is_checkpoint, line.n";30const ID_PREFIX = /^[0-9a-f]{6,12}$/;3132// Checkpoints are working marks, not history (§21.4): every list and count below leaves them out.33const NOT_CHECKPOINT = "is_checkpoint = 0";3435export function headId(db: Database): string | null {36	return mirrorState(db, "head");37}3839/** A page of saves, newest first. Rows land oldest first, so rowid is the order of the line. */40export function history(db: Database, limit: number, offset: number): Save[] {41	return db42		.query<Save, [number, number]>(43			`SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid DESC LIMIT ? OFFSET ?`,44		)45		.all(limit, offset)46		.map(asSave);47}4849/** Every save, oldest first, for the timeline. */50export function timeline(db: Database): Save[] {51	return db52		.query<Save, []>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid`)53		.all()54		.map(asSave);55}5657/** The save a unique prefix of 6–12 hex characters names (§6.1), or null when none or58 * several do. */59export function saveByPrefix(db: Database, prefix: string): Save | null {60	if (!ID_PREFIX.test(prefix)) return null;61	// A migrated save's whole six-character ID can also begin a twelve-character one.62	const exact = db63		.query<Save, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id = ?`)64		.get(prefix);65	if (exact) return asSave(exact);66	const rows = db67		.query<Save, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id LIKE ? || '%' LIMIT 2`)68		.all(prefix);69	return rows.length === 1 ? asSave(rows[0] as Save) : null;70}7172/** The nearest ancestor that is not a checkpoint: the parent a visitor can see (§21.4). */73export function visibleParent(db: Database, save: Save): Save | null {74	for (let id = save.parent; id !== ""; ) {75		const parent = saveByPrefix(db, id);76		if (!parent?.is_checkpoint) return parent;77		id = parent.parent;78	}79	return null;80}8182/** The reason a save is flagged, or null when it isn't: its newest flag or clear event wins (§10.1). */83export function flagReason(db: Database, saveId: string): string | null {84	const row = db85		.query<{ kind: string; reason: string }, [string]>(86			`SELECT kind, COALESCE(reason, '') AS reason FROM events87			WHERE save_id = ? AND kind IN ('flag', 'clear') ORDER BY created_at DESC, id DESC LIMIT 1`,88		)89		.get(saveId);90	return row?.kind === "flag" ? row.reason : null;91}9293/** How many strip events have landed: events are append-only, so this only ever grows. */94/**95 * What a save's tarball depends on besides the save: the strips landed, and the hidden paths and96 * epoch the mirror was built with. A change to any of them names a new key, so an old tarball is97 * never looked up again, whatever a late write or a failed cleanup leaves behind.98 */99export function tarballGeneration(db: Database): string {100	const built = `${mirrorState(db, "hidden") ?? ""}\n${mirrorState(db, "epoch") ?? ""}`;101	return `${stripCount(db)}-${createHash("sha256").update(built).digest("hex").slice(0, 12)}`;102}103104function stripCount(db: Database): number {105	return db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM events WHERE kind = 'strip'").get()106		?.n as number;107}108109export function filesAt(db: Database, saveId: string): FileEntry[] {110	return db111		.query<FileEntry, [string]>(112			`SELECT f.path, f.hash, f.executable = 1 AS executable, o.size FROM save_files f113			JOIN objects o ON o.hash = f.hash WHERE f.save_id = ? ORDER BY f.path`,114		)115		.all(saveId)116		.map((file) => ({ ...file, executable: Boolean(file.executable) }));117}118119export function fileAt(db: Database, saveId: string, path: string): FileEntry | null {120	const file = db121		.query<FileEntry, [string, string]>(122			`SELECT f.path, f.hash, f.executable = 1 AS executable, o.size FROM save_files f123			JOIN objects o ON o.hash = f.hash WHERE f.save_id = ? AND f.path = ?`,124		)125		.get(saveId, path);126	return file ? { ...file, executable: Boolean(file.executable) } : null;127}128129export function objectBytes(db: Database, hash: string): Uint8Array<ArrayBuffer> | null {130	const row = db131		.query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?")132		.get(hash);133	return row ? new Uint8Array(inflateSync(row.data)) : null;134}135136export function repoStats(db: Database): RepoStats {137	const row = db138		.query<{ saves: number; updated: number | null }, []>(139			`SELECT COUNT(*) AS saves, MAX(created_at) AS updated FROM saves WHERE ${NOT_CHECKPOINT}`,140		)141		.get() ?? { saves: 0, updated: null };142	return {143		saves: row.saves,144		updated: row.updated,145		lines: Number(mirrorState(db, "lines") ?? 0),146		language: mirrorState(db, "language") ?? "",147	};148}149150/**151 * Which saves touched each path on the line up to `saveId` (§21.5's detail panel). A save touched a path when152 * the path was added, changed or removed against the save before it; checkpoints are skipped, so a153 * change first recorded by a checkpoint counts at the next real save.154 */155export function fileTouches(db: Database, saveId: string): Touches {156	const rows = db157		.query<Save & { path: string; n: number }, { at: string }>(158			`WITH line AS (159				SELECT ${SAVE_COLUMNS}, LAG(id) OVER (ORDER BY rowid) AS prev, rowid AS n FROM saves160				WHERE ${NOT_CHECKPOINT} AND rowid <= (SELECT rowid FROM saves WHERE id = $at)161			)162			SELECT ${LINE_COLUMNS}, f.path FROM line JOIN save_files f ON f.save_id = line.id163			LEFT JOIN save_files p ON p.save_id = line.prev AND p.path = f.path164			WHERE p.hash IS NOT f.hash OR p.executable IS NOT f.executable165			UNION ALL166			SELECT ${LINE_COLUMNS}, p.path FROM line JOIN save_files p ON p.save_id = line.prev167			WHERE NOT EXISTS (SELECT 1 FROM save_files f WHERE f.save_id = line.id AND f.path = p.path)168			ORDER BY n`,169		)170		.all({ at: saveId });171	const saves = new Map<string, Save>();172	const byPath = new Map<string, Save[]>();173	for (const { path, n: _, ...row } of rows) {174		const save = saves.get(row.id) ?? asSave(row);175		saves.set(save.id, save);176		const touched = byPath.get(path);177		if (touched) touched.push(save);178		else byPath.set(path, [save]);179	}180	return { line: [...saves.values()], byPath };181}182183/** Lines per language at the newest real save, most first, vendored code left out as in the header's language. */184export function languageLines(db: Database): [string, number][] {185	return JSON.parse(mirrorState(db, "languages") ?? "[]") as [string, number][];186}187188/** Every distinct object (unique file contents) a real save refers to, at any point in history. */189export function objectHashes(db: Database): string[] {190	// From `objects`, probing save_files_hash: every save lists its whole tree, so a DISTINCT over191	// save_files reads saves × files rows (1.4 s for 1,083 saves on Tylee).192	return db193		.query<{ hash: string }, []>(194			`SELECT o.hash195			 FROM objects o196			 WHERE EXISTS (197				SELECT 1198				FROM save_files f199				JOIN saves s ON s.id = f.save_id200				WHERE f.hash = o.hash201				AND s.${NOT_CHECKPOINT}202			 )`,203		)204		.all()205		.map((row) => row.hash);206}207208/** Every release record the bucket holds, in no particular order. */209export function releaseRecords(db: Database): ReleaseRecord[] {210	return db211		.query<{ record: string }, []>("SELECT record FROM releases")212		.all()213		.map((row) => JSON.parse(row.record) as ReleaseRecord);214}215216function asSave(row: Save): Save {217	return { ...row, is_checkpoint: Boolean(row.is_checkpoint) };218}