queries.ts

12.3 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 type { FileFacts } from "../describe/describe.ts";6import type { Outline } from "../describe/links.ts";7import { flattenManifest } from "./manifest.ts";8import { mirrorState } from "./store.ts";910export type Save = {11	id: string;12	parent: string;13	message: string;14	created_at: number;15	machine: string;16	agent: string;17	session: string;18	is_checkpoint: boolean;19};2021export type FileEntry = { path: string; hash: string; executable: boolean; size: number };2223/** The saves that touched each path up to one save, oldest first; `line` is every one of24 * them in line order. */25export type Touches = { line: Save[]; byPath: Map<string, Save[]> };2627export type RepoStats = { saves: number; lines: number; language: string; updated: number | null };2829const SAVE_COLUMNS = `id, COALESCE(parent, '') AS parent, message, created_at, machine,30	COALESCE(agent, '') AS agent, COALESCE(session, '') AS session, is_checkpoint = 1 AS is_checkpoint`;31const ID_PREFIX = /^[0-9a-f]{6,12}$/;3233// Checkpoints are working marks, not history (§21.4): every list and count below leaves them out.34const NOT_CHECKPOINT = "is_checkpoint = 0";3536export function headId(db: Database): string | null {37	return mirrorState(db, "head");38}3940/** A page of saves, newest first. Rows land oldest first, so rowid is the order of the line. */41export function history(db: Database, limit: number, offset: number): Save[] {42	return db43		.query<Save, [number, number]>(44			`SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid DESC LIMIT ? OFFSET ?`,45		)46		.all(limit, offset)47		.map(asSave);48}4950/** Every save, oldest first, for the timeline. */51export function timeline(db: Database): Save[] {52	return db53		.query<Save, []>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid`)54		.all()55		.map(asSave);56}5758/** The save a unique prefix of 6–12 hex characters names (§6.1), or null when none or59 * several do. */60export function saveByPrefix(db: Database, prefix: string): Save | null {61	if (!ID_PREFIX.test(prefix)) return null;62	// A migrated save's whole six-character ID can also begin a twelve-character one.63	const exact = db64		.query<Save, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id = ?`)65		.get(prefix);66	if (exact) return asSave(exact);67	const rows = db68		.query<Save, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id GLOB ? LIMIT 2`)69		.all(`${prefix}*`);70	return rows.length === 1 ? asSave(rows[0] as Save) : null;71}7273/** The nearest ancestor that is not a checkpoint: the parent a visitor can see (§21.4). */74export function visibleParent(db: Database, save: Save): Save | null {75	for (let id = save.parent; id !== ""; ) {76		const parent = saveByPrefix(db, id);77		if (!parent?.is_checkpoint) return parent;78		id = parent.parent;79	}80	return null;81}8283/** The reason a save is flagged, or null when it isn't: its newest flag or clear event wins (§10.1). */84export function flagReason(db: Database, saveId: string): string | null {85	const row = db86		.query<{ kind: string; reason: string }, [string]>(87			`SELECT kind, COALESCE(reason, '') AS reason FROM events88			WHERE save_id = ? AND kind IN ('flag', 'clear') ORDER BY created_at DESC, id DESC LIMIT 1`,89		)90		.get(saveId);91	return row?.kind === "flag" ? row.reason : null;92}9394/** How many strip events have landed: events are append-only, so this only ever grows. */95/**96 * What a save's tarball depends on besides the save: the strips landed, and the hidden paths and97 * epoch the mirror was built with. A change to any of them names a new key, so an old tarball is98 * never looked up again, whatever a late write or a failed cleanup leaves behind.99 */100export function tarballGeneration(db: Database): string {101	const built = `${mirrorState(db, "hidden") ?? ""}\n${mirrorState(db, "epoch") ?? ""}`;102	return `${stripCount(db)}-${createHash("sha256").update(built).digest("hex").slice(0, 12)}`;103}104105function stripCount(db: Database): number {106	return db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM events WHERE kind = 'strip'").get()107		?.n as number;108}109110type Strip = { save_id: string | null; path: string };111type Filters = { generation: string; hidden: string[]; strips: Strip[] };112113// Which paths the operator hides and which strips cover, read once per strip/hidden generation.114// A save's tree is never rewritten: the filter is applied as a save's files are read.115const filters = new WeakMap<Database, Filters>();116117function filtersAt(db: Database): Filters {118	const generation = tarballGeneration(db);119	const cached = filters.get(db);120	if (cached?.generation === generation) return cached;121	const fresh: Filters = {122		generation,123		hidden: (mirrorState(db, "hidden") ?? "").split("\n").filter(Boolean),124		strips: db.query<Strip, []>("SELECT save_id, path FROM events WHERE kind = 'strip'").all(),125	};126	filters.set(db, fresh);127	return fresh;128}129130// §10.2's path rule: a file or folder, or an `ANY_DEPTH` name at any depth.131function covers(entry: string, path: string): boolean {132	if (entry.startsWith("**/")) return `/${path}/`.includes(`/${entry.slice(3)}/`);133	return path === entry || path.startsWith(`${entry.replace(/\/+$/, "")}/`);134}135136function filesAtSave(db: Database, saveId: string, keepHidden: boolean): FileEntry[] {137	const root = db138		.query<{ manifest: string }, [string]>("SELECT manifest FROM saves WHERE id = ?")139		.get(saveId)?.manifest;140	if (root === undefined) return [];141	const current = filtersAt(db);142	// A path whose object the mirror never stored — an oversized one, a quarantined one — is not143	// served, as the join on `objects` used to leave it out.144	const exists = db.query<{ one: number }, [string]>("SELECT 1 AS one FROM objects WHERE hash = ?");145	return flattenManifest(db, root).filter(146		(file) =>147			(keepHidden || !current.hidden.some((entry) => covers(entry, file.path))) &&148			!current.strips.some(149				(strip) =>150					(strip.save_id === "" || strip.save_id === saveId) && covers(strip.path, file.path),151			) &&152			exists.get(file.hash) !== null,153	);154}155156/** The files at a save, sorted: what its manifest tree flattens to, less hidden and stripped paths. */157export function filesAt(db: Database, saveId: string): FileEntry[] {158	return filesAtSave(db, saveId, false);159}160161/** The files a strip leaves, hidden paths included: the objects unhiding must still find. */162export function storedFilesAt(db: Database, saveId: string): FileEntry[] {163	return filesAtSave(db, saveId, true);164}165166export function fileAt(db: Database, saveId: string, path: string): FileEntry | null {167	return filesAt(db, saveId).find((file) => file.path === path) ?? null;168}169170// A steal asks for the object list and then one object at a time; the set is the same for every171// request until a landing, a strip or a hidden list changes, which the generation and head name.172const visible = new WeakMap<Database, { key: string; hashes: Set<string> }>();173174/** Every object a visible file at some save refers to: the Koh routes serve only these. */175export function visibleObjects(db: Database): Set<string> {176	const key = `${tarballGeneration(db)}\n${mirrorState(db, "head") ?? ""}`;177	const cached = visible.get(db);178	if (cached?.key === key) return cached.hashes;179	const hashes = new Set<string>();180	const saves = db.query<{ id: string }, []>("SELECT id FROM saves").all();181	for (const save of saves) for (const file of filesAt(db, save.id)) hashes.add(file.hash);182	visible.set(db, { key, hashes });183	return hashes;184}185186export function objectBytes(db: Database, hash: string): Uint8Array<ArrayBuffer> | null {187	const row = db188		.query<{ data: Uint8Array }, [string]>("SELECT data FROM objects WHERE hash = ?")189		.get(hash);190	return row ? new Uint8Array(inflateSync(row.data)) : null;191}192193export function repoStats(db: Database): RepoStats {194	const row = db195		.query<{ saves: number; updated: number | null }, []>(196			`SELECT COUNT(*) AS saves, MAX(created_at) AS updated FROM saves WHERE ${NOT_CHECKPOINT}`,197		)198		.get() ?? { saves: 0, updated: null };199	return {200		saves: row.saves,201		updated: row.updated,202		lines: Number(mirrorState(db, "lines") ?? 0),203		language: mirrorState(db, "language") ?? "",204	};205}206207/**208 * Which saves touched each path on the line up to `saveId` (§21.5's detail panel), as recorded when209 * each save landed (`touches` in the mirror).210 */211export function fileTouches(db: Database, saveId: string): Touches {212	const at = { at: saveId };213	// The saves once, the touches as bare pairs: every touch row carrying its save's columns was214	// most of the Atlas's cost.215	const byRowid = new Map(216		db217			.query<Save & { n: number }, { at: string }>(218				`SELECT rowid AS n, ${SAVE_COLUMNS}219				FROM saves220				WHERE ${NOT_CHECKPOINT}221				AND rowid <= (SELECT rowid FROM saves WHERE id = $at)`,222			)223			.all(at)224			.map(({ n, ...row }) => [n, asSave(row)]),225	);226	const touched = db227		.query<{ path: string; n: number }, { at: string }>(228			`SELECT path, n229			FROM touches230			WHERE n <= (SELECT rowid FROM saves WHERE id = $at)231			ORDER BY n`,232		)233		.all(at);234	const line = new Set<Save>();235	const byPath = new Map<string, Save[]>();236	for (const { path, n } of touched) {237		const save = byRowid.get(n) as Save;238		line.add(save);239		const saves = byPath.get(path);240		if (saves) saves.push(save);241		else byPath.set(path, [save]);242	}243	return { line: [...line], byPath };244}245246type FactsRow = {247	lines: number | null;248	description: string | null;249	outline: string | null;250};251252function factsAt(db: Database, hash: string, path: string): FactsRow | null {253	return (254		db255			.query<FactsRow, [string, string]>(256				"SELECT lines, description, outline FROM facts WHERE hash = ? AND path = ?",257			)258			.get(hash, path) ?? null259	);260}261262/** The files at a save with what each says about itself, as recorded when it landed. */263export function filesWithFacts(db: Database, saveId: string): (FileEntry & FileFacts)[] {264	return filesAt(db, saveId).map((file) => {265		const facts = factsAt(db, file.hash, file.path);266		return {267			...file,268			lines: facts?.lines ?? null,269			description: facts?.description ?? null,270			outline: facts?.outline == null ? null : (JSON.parse(facts.outline) as Outline),271		};272	});273}274275/** One file's Atlas panel row, or null when the save shows no such file. */276export function panelFile(277	db: Database,278	saveId: string,279	path: string,280):281	| (FileEntry & { lines: number | null; description: string | null; outline: string | null })282	| null {283	if (path === ".kohignore") return null;284	const file = fileAt(db, saveId, path);285	if (!file) return null;286	const facts = factsAt(db, file.hash, file.path);287	return { ...file, ...(facts ?? { lines: null, description: null, outline: null }) };288}289290/** A folder's Atlas panel rows: every file under it at that save, sorted, less Koh's ignore file. */291export function panelFolder(292	db: Database,293	saveId: string,294	dir: string,295): { path: string; size: number; lines: number | null; description: string | null }[] {296	return filesAt(db, saveId)297		.filter((file) => file.path !== ".kohignore" && file.path.startsWith(`${dir}/`))298		.map((file) => {299			const facts = factsAt(db, file.hash, file.path);300			return {301				path: file.path,302				size: file.size,303				lines: facts?.lines ?? null,304				description: facts?.description ?? null,305			};306		});307}308309/** The file contents this repo's real saves refer to, as recounted when its saves land. */310export function knownObjects(db: Database): string[] {311	return db312		.query<{ hash: string }, []>("SELECT hash FROM known_objects")313		.all()314		.map((row) => row.hash);315}316317/** The newest real saves, newest first. */318export function newestSaves(db: Database, limit: number): Save[] {319	return db320		.query<Save, [number]>(321			`SELECT ${SAVE_COLUMNS} FROM saves WHERE ${NOT_CHECKPOINT} ORDER BY rowid DESC LIMIT ?`,322		)323		.all(limit)324		.map(asSave);325}326327/** Lines per language at the newest real save, most first, vendored code left out as in the header's language. */328export function languageLines(db: Database): [string, number][] {329	return JSON.parse(mirrorState(db, "languages") ?? "[]") as [string, number][];330}331332/** Every release record the bucket holds, in no particular order. */333export function releaseRecords(db: Database): ReleaseRecord[] {334	return db335		.query<{ record: string }, []>("SELECT record FROM releases")336		.all()337		.map((row) => JSON.parse(row.record) as ReleaseRecord);338}339340function asSave(row: Save): Save {341	return { ...row, is_checkpoint: Boolean(row.is_checkpoint) };342}