remote.ts

10.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", 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}161162// Two bundle streams at a time. A bundle is as big as the repo and every request shares the one163// thread, so a third waits its turn rather than starving the pages around it.164const BUNDLE_LIMIT = 2;165let bundling = 0;166const bundleQueue: (() => void)[] = [];167168/** A slot for one bundle stream, released when it ends, errors or is cancelled. */169function 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}183184/** A bundle's slot, released as its generator's own `finally` runs: at the end, on an error, and185 * when a cancelled stream returns it. */186function* 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		// A client that hangs up leaves the generator part way through; this finalizes its queries.202		cancel() {203			chunks.return(undefined);204		},205	});206}207208/** `<key> <length>\n` and that many bytes per entry, keyed as the single routes are; `end 0` last. */209function* 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	// One snapshot on a connection of its own: a strip landing mid-stream must not leave a save216	// naming an object this read omits, and a second steal must not nest in this one's transaction.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		// The objects a visible file refers to, gathered as the save records that name them stream:226		// a hidden or stripped path's object is left out, as it is left out of the record.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		// A connection cut between two entries would otherwise pass for the whole repo.241		yield encoder.encode("end 0\n");242	} finally {243		saves.finalize();244		events.finalize();245		objects.finalize();246		// A client that hangs up mid-stream would otherwise leave the snapshot open.247		if (reader.inTransaction) reader.run("ROLLBACK");248		reader.close();249	}250}251252// Field names and their order are Koh's, and every optional is an empty string, as `json2.encode`253// writes it: `koh steal` decodes this straight into its own record.254function 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		// Whatever the strips left: a path they removed is gone from the record too.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}