remote.ts

9.5 KB · raw

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";9// §9.2's name for the layout. Koh trims whitespace before it compares, so no trailing newline is10// needed to agree with a bucket.11const FORMAT = "koh-remote 1";12// A private repo and an unknown one answer alike, to a person and to Koh (§20).13const NOT_FOUND = '{"error":"repo_not_found","message":"repo not found"}';14const OBJECT_HASH = /^[0-9a-f]{64}$/;15// The addendum's lifetimes — a save's record can still be rewritten by a strip, so a minute, and an16// object never changes once written but a strip can take it away, so a year rather than immutable.17// `private`, as the pages are: a repo can be turned private, and no shared cache may keep serving18// what it fetched while the repo was public (§20).19const 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";5152/** The one answer for a private repo, an unknown one, and a record the mirror does not hold. */53function miss(c: Context): Response {54	return c.body(NOT_FOUND, 404, { "Content-Type": JSON_TYPE, "Cache-Control": "no-store" });55}5657/**58 * §9.2's layout, read-only, for the repos a visitor can see: what `koh steal <host>/<repo>`59 * fetches, so the paths, the bytes and the field names are Koh's, not Kepr's (A2, part 2).60 */61export 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	// Checkpoints are served like any other save: the parent links of the saves around them need83	// them, even though the pages hide them (§21.4).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	// The object's stored bytes, zlib and all: `koh steal` inflates them itself and checks the hash.96	// Only objects a visible file refers to: a hidden or stripped path is never served, while its97	// object is kept for unhiding.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	// Koh lists `<repo>/saves` and `<repo>/objects` as well as its events: a steal walks the chain117	// it is given here, and fetches every object those saves name. Both lists follow the mirror, so118	// neither is cached.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	// The whole layout in one response, so a steal costs one request rather than one per key: a151	// 2,071-save repo took an hour of round trips. Streamed, because it is as big as the repo.152	app.get("/:repo/koh/bundle", (c) =>153		serve(c, c.req.param("repo"), (mirror) =>154			c.body(stream(bundle(mirror)), 200, {155				"Content-Type": "application/octet-stream",156				"Cache-Control": NO_CACHE,157			}),158		),159	);160}161162function stream(chunks: Generator<Uint8Array>): ReadableStream<Uint8Array> {163	return new ReadableStream({164		pull(controller) {165			const next = chunks.next();166			if (next.done) controller.close();167			else controller.enqueue(next.value);168		},169		// A client that hangs up leaves the generator part way through; this finalizes its queries.170		cancel() {171			chunks.return(undefined);172		},173	});174}175176/** `<key> <length>\n` and that many bytes per entry, keyed as the single routes are; `end 0` last. */177function* bundle(mirror: Database): Generator<Uint8Array> {178	const encoder = new TextEncoder();179	function* entry(key: string, bytes: Uint8Array): Generator<Uint8Array> {180		yield encoder.encode(`${key} ${bytes.length}\n`);181		yield bytes;182	}183	// One snapshot on a connection of its own: a strip landing mid-stream must not leave a save184	// naming an object this read omits, and a second steal must not nest in this one's transaction.185	const reader = new Database(mirror.filename, { strict: true, readonly: true });186	const saves = reader.prepare<SaveRow, []>(`SELECT ${SAVE_COLUMNS} FROM saves`);187	const events = reader.prepare<EventRow, []>(`SELECT ${EVENT_COLUMNS} FROM events`);188	const objects = reader.prepare<{ hash: string; data: Uint8Array }, []>(189		"SELECT hash, data FROM objects",190	);191	try {192		reader.run("BEGIN DEFERRED");193		// The objects a visible file refers to, gathered as the save records that name them stream:194		// a hidden or stripped path's object is left out, as it is left out of the record.195		const visible = new Set<string>();196		for (const row of saves.iterate()) {197			const files = filesAt(reader, row.id);198			for (const file of files) visible.add(file.hash);199			yield* entry(`saves/${row.id}`, encoder.encode(saveRecord(row, files)));200		}201		for (const row of events.iterate()) {202			yield* entry(`events/${row.id}`, encoder.encode(eventRecord(row)));203		}204		for (const row of objects.iterate()) {205			if (visible.has(row.hash)) yield* entry(`objects/${row.hash}`, row.data);206		}207		reader.run("COMMIT");208		// A connection cut between two entries would otherwise pass for the whole repo.209		yield encoder.encode("end 0\n");210	} finally {211		saves.finalize();212		events.finalize();213		objects.finalize();214		// A client that hangs up mid-stream would otherwise leave the snapshot open.215		if (reader.inTransaction) reader.run("ROLLBACK");216		reader.close();217	}218}219220// Field names and their order are Koh's, and every optional is an empty string, as `json2.encode`221// writes it: `koh steal` decodes this straight into its own record.222function saveRecord(row: SaveRow, files: FileEntry[]): string {223	const record: SaveRecord = {224		id: row.id,225		parent: row.parent ?? "",226		message: row.message,227		created_at: row.created_at,228		machine: row.machine,229		is_checkpoint: row.is_checkpoint === 1,230		size_bytes: row.size_bytes,231		agent: row.agent ?? "",232		session: row.session ?? "",233		restores: row.restores ?? "",234		replayed_from: row.replayed_from ?? "",235		// Whatever the strips left: a path they removed is gone from the record too.236		files: files.map(237			(file): SaveFile => ({ path: file.path, hash: file.hash, executable: file.executable }),238		),239	};240	return JSON.stringify(record);241}242243function eventRecord(row: EventRow): string {244	const record: EventRecord = {245		id: row.id,246		kind: row.kind,247		save_id: row.save_id ?? "",248		path: row.path ?? "",249		reason: row.reason ?? "",250		created_at: row.created_at,251		machine: row.machine,252	};253	return JSON.stringify(record);254}