1import { Database } from "bun:sqlite";2import type { Context, Hono } from "hono";3import { type EventRecord, SAVE_ID, type SaveFile, type SaveRecord } from "../bucket/repo.ts";4import { openPublicRepo, type PageContext } from "../pages/layout.ts";5import { type FileEntry, filesAt, headId, visibleObjects } from "./queries.ts";67const JSON_TYPE = "application/json; charset=UTF-8";8const TEXT_TYPE = "text/plain; charset=UTF-8";91011const FORMAT = "koh-remote 1";1213const NOT_FOUND = '{"error":"repo_not_found","message":"repo not found"}';14const OBJECT_HASH = /^[0-9a-f]{64}$/;1516171819const SAVE_CACHE = "private, max-age=60";20const OBJECT_CACHE = "private, max-age=31536000";21const DAY_CACHE = "private, max-age=86400";22const NO_CACHE = "no-cache";2324type SaveRow = {25 id: string;26 parent: string | null;27 message: string;28 created_at: number;29 machine: string;30 is_checkpoint: number;31 size_bytes: number;32 agent: string | null;33 session: string | null;34 restores: string | null;35 replayed_from: string | null;36};3738type EventRow = {39 id: string;40 kind: EventRecord["kind"];41 save_id: string | null;42 path: string | null;43 reason: string | null;44 created_at: number;45 machine: string;46};4748const SAVE_COLUMNS = `id, parent, message, created_at, machine, is_checkpoint, size_bytes, agent,49 session, restores, replayed_from`;50const EVENT_COLUMNS = "id, kind, save_id, path, reason, created_at, machine";515253function miss(c: Context): Response {54 return c.body(NOT_FOUND, 404, { "Content-Type": JSON_TYPE, "Cache-Control": "no-store" });55}565758596061export function registerKohRemote(app: Hono, ctx: PageContext): void {62 const serve = (c: Context, name: string, body: (mirror: Database) => Response): Response => {63 const repo = openPublicRepo(ctx, name);64 return repo ? body(repo.mirror) : miss(c);65 };66 const json = (c: Context, body: string, cache: string): Response =>67 c.body(body, 200, { "Content-Type": JSON_TYPE, "Cache-Control": cache });68 const text = (c: Context, body: string, cache: string): Response =>69 c.body(body, 200, { "Content-Type": TEXT_TYPE, "Cache-Control": cache });7071 app.get("/:repo/koh/format", (c) =>72 serve(c, c.req.param("repo"), () => text(c, FORMAT, DAY_CACHE)),73 );7475 app.get("/:repo/koh/head", (c) =>76 serve(c, c.req.param("repo"), (mirror) => {77 const head = headId(mirror);78 return head ? text(c, head, NO_CACHE) : miss(c);79 }),80 );8182 83 84 app.get("/:repo/koh/saves/:id", (c) =>85 serve(c, c.req.param("repo"), (mirror) => {86 const id = c.req.param("id");87 if (!SAVE_ID.test(id)) return miss(c);88 const row = mirror89 .query<SaveRow, [string]>(`SELECT ${SAVE_COLUMNS} FROM saves WHERE id = ?`)90 .get(id);91 return row ? json(c, saveRecord(row, filesAt(mirror, row.id)), SAVE_CACHE) : miss(c);92 }),93 );9495 96 97 98 app.get("/:repo/koh/objects/:hash", (c) =>99 serve(c, c.req.param("repo"), (mirror) => {100 const hash = c.req.param("hash");101 if (!OBJECT_HASH.test(hash) || !visibleObjects(mirror).has(hash)) return miss(c);102 const row = mirror103 .query<{ data: Uint8Array<ArrayBuffer> }, [string]>(104 "SELECT data FROM objects WHERE hash = ?",105 )106 .get(hash);107 return row108 ? c.body(row.data, 200, {109 "Content-Type": "application/octet-stream",110 "Cache-Control": OBJECT_CACHE,111 })112 : miss(c);113 }),114 );115116 117 118 119 const listIds = (c: Context, mirror: Database, table: "saves" | "events"): Response => {120 const ids = mirror.query<{ id: string }, []>(`SELECT id FROM ${table} ORDER BY id`).all();121 return text(c, ids.length > 0 ? `${ids.map((row) => row.id).join("\n")}\n` : "", NO_CACHE);122 };123124 app.get("/:repo/koh/saves", (c) =>125 serve(c, c.req.param("repo"), (mirror) => listIds(c, mirror, "saves")),126 );127128 app.get("/:repo/koh/objects", (c) =>129 serve(c, c.req.param("repo"), (mirror) => {130 const hashes = [...visibleObjects(mirror)].sort();131 return text(c, hashes.length > 0 ? `${hashes.join("\n")}\n` : "", NO_CACHE);132 }),133 );134135 app.get("/:repo/koh/events", (c) =>136 serve(c, c.req.param("repo"), (mirror) => listIds(c, mirror, "events")),137 );138139 app.get("/:repo/koh/events/:id", (c) =>140 serve(c, c.req.param("repo"), (mirror) => {141 const id = c.req.param("id");142 if (!SAVE_ID.test(id)) return miss(c);143 const row = mirror144 .query<EventRow, [string]>(`SELECT ${EVENT_COLUMNS} FROM events WHERE id = ?`)145 .get(id);146 return row ? json(c, eventRecord(row), DAY_CACHE) : miss(c);147 }),148 );149150 151 152 app.get("/:repo/koh/bundle", async (c) => {153 const repo = openPublicRepo(ctx, c.req.param("repo"));154 if (!repo) return miss(c);155 return c.body(stream(bundled(bundle(repo.mirror), await bundleSlot())), 200, {156 "Content-Type": "application/octet-stream",157 "Cache-Control": NO_CACHE,158 });159 });160}161162163164const BUNDLE_LIMIT = 2;165let bundling = 0;166const bundleQueue: (() => void)[] = [];167168169function bundleSlot(): Promise<() => void> {170 const release = () => {171 const next = bundleQueue.shift();172 if (next) next();173 else bundling--;174 };175 if (bundling < BUNDLE_LIMIT) {176 bundling++;177 return Promise.resolve(release);178 }179 const { promise, resolve } = Promise.withResolvers<() => void>();180 bundleQueue.push(() => resolve(release));181 return promise;182}183184185186function* bundled(chunks: Generator<Uint8Array>, release: () => void): Generator<Uint8Array> {187 try {188 yield* chunks;189 } finally {190 release();191 }192}193194function stream(chunks: Generator<Uint8Array>): ReadableStream<Uint8Array> {195 return new ReadableStream({196 pull(controller) {197 const next = chunks.next();198 if (next.done) controller.close();199 else controller.enqueue(next.value);200 },201 202 cancel() {203 chunks.return(undefined);204 },205 });206}207208209function* bundle(mirror: Database): Generator<Uint8Array> {210 const encoder = new TextEncoder();211 function* entry(key: string, bytes: Uint8Array): Generator<Uint8Array> {212 yield encoder.encode(`${key} ${bytes.length}\n`);213 yield bytes;214 }215 216 217 const reader = new Database(mirror.filename, { strict: true, readonly: true });218 const saves = reader.prepare<SaveRow, []>(`SELECT ${SAVE_COLUMNS} FROM saves`);219 const events = reader.prepare<EventRow, []>(`SELECT ${EVENT_COLUMNS} FROM events`);220 const objects = reader.prepare<{ hash: string; data: Uint8Array }, []>(221 "SELECT hash, data FROM objects",222 );223 try {224 reader.run("BEGIN DEFERRED");225 226 227 const visible = new Set<string>();228 for (const row of saves.iterate()) {229 const files = filesAt(reader, row.id);230 for (const file of files) visible.add(file.hash);231 yield* entry(`saves/${row.id}`, encoder.encode(saveRecord(row, files)));232 }233 for (const row of events.iterate()) {234 yield* entry(`events/${row.id}`, encoder.encode(eventRecord(row)));235 }236 for (const row of objects.iterate()) {237 if (visible.has(row.hash)) yield* entry(`objects/${row.hash}`, row.data);238 }239 reader.run("COMMIT");240 241 yield encoder.encode("end 0\n");242 } finally {243 saves.finalize();244 events.finalize();245 objects.finalize();246 247 if (reader.inTransaction) reader.run("ROLLBACK");248 reader.close();249 }250}251252253254function saveRecord(row: SaveRow, files: FileEntry[]): string {255 const record: SaveRecord = {256 id: row.id,257 parent: row.parent ?? "",258 message: row.message,259 created_at: row.created_at,260 machine: row.machine,261 is_checkpoint: row.is_checkpoint === 1,262 size_bytes: row.size_bytes,263 agent: row.agent ?? "",264 session: row.session ?? "",265 restores: row.restores ?? "",266 replayed_from: row.replayed_from ?? "",267 268 files: files.map(269 (file): SaveFile => ({ path: file.path, hash: file.hash, executable: file.executable }),270 ),271 };272 return JSON.stringify(record);273}274275function eventRecord(row: EventRow): string {276 const record: EventRecord = {277 id: row.id,278 kind: row.kind,279 save_id: row.save_id ?? "",280 path: row.path ?? "",281 reason: row.reason ?? "",282 created_at: row.created_at,283 machine: row.machine,284 };285 return JSON.stringify(record);286}