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 };19202122export 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}$/;313233const NOT_CHECKPOINT = "is_checkpoint = 0";3435export function headId(db: Database): string | null {36 return mirrorState(db, "head");37}383940export 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}484950export 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}56575859export function saveByPrefix(db: Database, prefix: string): Save | null {60 if (!ID_PREFIX.test(prefix)) return null;61 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}717273export 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}818283export 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}9293949596979899export 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}149150151152153154155export 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}182183184export function languageLines(db: Database): [string, number][] {185 return JSON.parse(mirrorState(db, "languages") ?? "[]") as [string, number][];186}187188189export function objectHashes(db: Database): string[] {190 191 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}207208209export 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}