{"draft":null,"from":7,"to":318,"files":[{"path":"server/src/issues/routes.ts","added":212,"removed":0,"diff":"--- /dev/null\n+++ b/server/src/issues/routes.ts\n@@ -0,0 +1,212 @@\n+// The issues routes, apart from the Durable Object so they run under node --test with a store on node:sqlite.\n+// Paths are the client's: /p/:project/<read> for reads, and /p/:project/a/:agent/<op> for an agent's writes and\n+// its own reads (waiting, asked, drafts, news). Who may call which path was decided before a request gets here.\n+\n+import { type Actor, IssuesError, type IssuesStore, who } from \"./store.ts\";\n+\n+/** The largest request body a write takes, in bytes: far above any text a write may hold. */\n+export const BODY_MAX = 1024 * 1024;\n+\n+export const json = (status: number, body: unknown): Response =>\n+\tnew Response(JSON.stringify(body), { status, headers: { \"content-type\": \"application/json\" } });\n+\n+/**\n+ * One request to a project's issues. `seatError` says why a new ask's `of` isn't an agent in the project, or null\n+ * when it is (or when the project can't say).\n+ */\n+export async function issuesRoute(\n+\tstore: IssuesStore,\n+\trequest: Request,\n+\tseatError?: (of: string) => Promise<string | null>,\n+): Promise<Response> {\n+\ttry {\n+\t\treturn await route(store, request, seatError);\n+\t} catch (e) {\n+\t\tif (e instanceof IssuesError) {\n+\t\t\tconst answer = json(e.status, { error: e.message });\n+\t\t\tif (e.retryAfter !== undefined) answer.headers.set(\"Retry-After\", String(e.retryAfter));\n+\t\t\treturn answer;\n+\t\t}\n+\t\tthrow e;\n+\t}\n+}\n+\n+async function route(\n+\tstore: IssuesStore,\n+\trequest: Request,\n+\tseatError?: (of: string) => Promise<string | null>,\n+): Promise<Response> {\n+\tconst url = new URL(request.url);\n+\tconst m = /^\\/p\\/([^/]+)(?:\\/a\\/([^/]+))?\\/(.+)$/.exec(url.pathname);\n+\tif (!m) return json(404, { error: \"no such issues route\" });\n+\tconst agent = m[2] === undefined ? undefined : decodeURIComponent(m[2]);\n+\tconst rest = m[3]!;\n+\tconst q = url.searchParams;\n+\tconst actor: Actor | undefined = agent !== undefined ? { agent } : undefined;\n+\tif (rest === \"attachments\" || rest.startsWith(\"attachments/\"))\n+\t\treturn json(501, { error: \"this server doesn't keep attachments\" });\n+\t// A reader sees only their own drafts.\n+\tif (request.method === \"GET\" && rest === \"drafts\") {\n+\t\tif (!actor) return json(403, { error: \"drafts are an agent's: /a/:agent/drafts\" });\n+\t\treturn json(200, { drafts: store.drafts(actor) });\n+\t}\n+\tif (request.method === \"GET\") {\n+\t\tif (actor) {\n+\t\t\t// An agent's own waiting list, which marks what it lists as seen.\n+\t\t\tif (rest === \"waiting\") return json(200, { asks: store.waiting(who(actor), who(actor)) });\n+\t\t\t// The asks an agent sent, open then the latest answered.\n+\t\t\tif (rest === \"asked\") return json(200, { asks: store.asked(who(actor)) });\n+\t\t\t// An agent's news here: answers, replies, @mentions, and changes on issues it watches, by others.\n+\t\t\tif (rest === \"news\") {\n+\t\t\t\tconst before = q.get(\"before\");\n+\t\t\t\treturn json(200, {\n+\t\t\t\t\tnews: store.newsFor(actor, [who(actor)], before === null ? undefined : Number(before) || undefined),\n+\t\t\t\t});\n+\t\t\t}\n+\t\t\treturn json(404, {\n+\t\t\t\terror: \"an agent's reads are waiting, asked, drafts and news; other reads have no /a/:agent/\",\n+\t\t\t});\n+\t\t}\n+\t\tif (rest === \"issues\") {\n+\t\t\tconst parent = q.get(\"parent\");\n+\t\t\treturn json(200, {\n+\t\t\t\tissues: store.list({\n+\t\t\t\t\t...(q.get(\"status\") ? { status: q.get(\"status\")! } : {}),\n+\t\t\t\t\t...(q.get(\"agent\") ? { agent: q.get(\"agent\")! } : {}),\n+\t\t\t\t\t...(parent ? { parent: Number(parent) } : {}),\n+\t\t\t\t\t// ?label=a,b (or label repeated): issues with every one of them.\n+\t\t\t\t\t...(q.getAll(\"label\").length > 0 ? { labels: q.getAll(\"label\").flatMap((l) => l.split(\",\")) } : {}),\n+\t\t\t\t\topen: q.get(\"open\") === \"1\",\n+\t\t\t\t}),\n+\t\t\t});\n+\t\t}\n+\t\tif (rest === \"labels\") return json(200, { labels: store.labelsInUse() });\n+\t\t// The change count: what a reader can cache issue reads under, cheap enough to ask every request.\n+\t\tif (rest === \"changes\") return json(200, { changes: store.changes() });\n+\t\tif (rest === \"search\") {\n+\t\t\tconst limit = Number(q.get(\"limit\") ?? \"20\");\n+\t\t\treturn json(200, { hits: store.search((q.get(\"q\") ?? \"\").slice(0, 200), Number.isInteger(limit) ? limit : 20) });\n+\t\t}\n+\t\tconst one = /^issue\\/(\\d+)$/.exec(rest);\n+\t\tif (one) return json(200, store.page(Number(one[1])));\n+\t\tif (rest === \"waiting\") return json(200, { asks: store.waiting(q.get(\"of\") ?? undefined) });\n+\t\tconst ask = /^ask\\/(\\d+)$/.exec(rest);\n+\t\tif (ask) return json(200, { ask: store.askThread(Number(ask[1])) });\n+\t\tif (rest === \"asked\") {\n+\t\t\tconst by = q.get(\"by\");\n+\t\t\tif (!by) return json(400, { error: \"asked needs ?by=<agent>\" });\n+\t\t\treturn json(200, { asks: store.asked(by) });\n+\t\t}\n+\t\tif (rest === \"answered\") {\n+\t\t\tconst of = q.get(\"of\");\n+\t\t\tif (!of) return json(400, { error: \"answered needs ?of=<agent>\" });\n+\t\t\treturn json(200, { asks: store.answered(of) });\n+\t\t}\n+\t\treturn json(404, { error: \"no such issues route\" });\n+\t}\n+\tif (request.method !== \"POST\") return json(405, { error: \"issues takes GET and POST\" });\n+\tif (!actor) return json(403, { error: \"a write is an agent's: /p/:project/a/:agent/<op>\" });\n+\tlet body: Record<string, unknown> = {};\n+\tconst raw = new TextDecoder().decode(await readCapped(request, BODY_MAX));\n+\tif (raw.trim() !== \"\") {\n+\t\ttry {\n+\t\t\tbody = JSON.parse(raw) as Record<string, unknown>;\n+\t\t} catch {\n+\t\t\treturn json(400, { error: \"the body is JSON\" });\n+\t\t}\n+\t\tif (typeof body !== \"object\" || body === null || Array.isArray(body))\n+\t\t\treturn json(400, { error: \"the body is a JSON object\" });\n+\t}\n+\t// Drafts and news marks make no news, so they don't count toward the writer's limit.\n+\tif (rest === \"draft\") return json(200, { ok: true, ...store.saveDraft(actor, body) });\n+\tconst deleting = /^draft\\/(\\d+)\\/delete$/.exec(rest);\n+\tif (deleting) {\n+\t\tstore.deleteDraft(actor, Number(deleting[1]));\n+\t\treturn json(200, { ok: true });\n+\t}\n+\tif (rest === \"news/read\") {\n+\t\tconst at = body.at === undefined ? Date.now() : body.at;\n+\t\tif (typeof at !== \"number\" || !Number.isFinite(at)) return json(400, { error: \"at is a time in milliseconds\" });\n+\t\treturn json(200, { ok: true, ...store.markNewsRead(actor, at) });\n+\t}\n+\tconst write = writeFor(store, actor, rest, body);\n+\tif (!write) return json(404, { error: \"no such issues route\" });\n+\t// An ask goes to an agent in the project.\n+\tif (rest === \"ask\" && seatError && typeof body.of === \"string\") {\n+\t\tconst refused = await seatError(body.of);\n+\t\tif (refused) return json(400, { error: refused });\n+\t}\n+\tstore.checkLimit(actor);\n+\tconst done = write();\n+\tstore.wrote(actor);\n+\t// Every write answers the change count it made, for the next read.\n+\treturn json(200, { ok: true, ...done, changes: store.changes() });\n+}\n+\n+/**\n+ * The body, read a chunk at a time and refused (413) the moment it passes `max`, so a body with no\n+ * Content-Length, or one that lies, never puts more than `max` in memory.\n+ */\n+export async function readCapped(request: Request, max: number): Promise<Uint8Array<ArrayBuffer>> {\n+\tconst declared = Number(request.headers.get(\"Content-Length\") ?? \"0\");\n+\tif (declared > max) throw new IssuesError(`the body is ${declared} bytes; the most is ${max}`, 413);\n+\tif (!request.body) return new Uint8Array(0);\n+\tconst reader = request.body.getReader();\n+\tconst parts: Uint8Array[] = [];\n+\tlet size = 0;\n+\tfor (;;) {\n+\t\tconst { done, value } = await reader.read();\n+\t\tif (done) break;\n+\t\tsize += value.length;\n+\t\tif (size > max) {\n+\t\t\tawait reader.cancel();\n+\t\t\tthrow new IssuesError(`the body is over ${max} bytes, the most there can be`, 413);\n+\t\t}\n+\t\tparts.push(value);\n+\t}\n+\tconst out = new Uint8Array(size);\n+\tlet at = 0;\n+\tfor (const part of parts) {\n+\t\tout.set(part, at);\n+\t\tat += part.length;\n+\t}\n+\treturn out;\n+}\n+\n+/** A write that can carry news, to run once the writer's limit allows it; undefined when no route matches. */\n+function writeFor(\n+\tstore: IssuesStore,\n+\tactor: Actor,\n+\trest: string,\n+\tbody: Record<string, unknown>,\n+): (() => object) | undefined {\n+\tif (rest === \"issue\") return () => store.open(actor, body);\n+\tif (rest === \"ask\") return () => store.ask(actor, body);\n+\tconst on = /^issue\\/(\\d+)\\/(comment|drop|edit|reopen|done)$/.exec(rest);\n+\tif (on) {\n+\t\tconst id = Number(on[1]);\n+\t\treturn () => {\n+\t\t\tif (on[2] === \"comment\") return store.comment(actor, id, body);\n+\t\t\tif (on[2] === \"edit\") return store.edit(actor, id, body);\n+\t\t\tif (on[2] === \"reopen\") return store.reopen(actor, id);\n+\t\t\tif (on[2] === \"done\") {\n+\t\t\t\tconst version = body.version;\n+\t\t\t\tif (version !== undefined && version !== null && typeof version !== \"number\")\n+\t\t\t\t\tthrow new IssuesError(\"version is a published version, 1 or more\");\n+\t\t\t\treturn store.markDone(actor, id, typeof version === \"number\" ? version : null);\n+\t\t\t}\n+\t\t\treturn store.drop(actor, id);\n+\t\t};\n+\t}\n+\tconst opening = /^draft\\/(\\d+)\\/open$/.exec(rest);\n+\tif (opening) return () => store.openDraft(actor, Number(opening[1]), body);\n+\tconst answer = /^answer\\/(\\d+)$/.exec(rest);\n+\tif (answer) return () => store.answer(actor, Number(answer[1]), body);\n+\tconst ack = /^ack\\/(\\d+)$/.exec(rest);\n+\tif (ack) return () => store.ack(actor, Number(ack[1]), body);\n+\tconst reply = /^reply\\/(\\d+)$/.exec(rest);\n+\tif (reply) return () => store.reply(actor, Number(reply[1]), body);\n+\tconst withdraw = /^withdraw\\/(\\d+)$/.exec(rest);\n+\tif (withdraw) return () => store.withdraw(actor, Number(withdraw[1]), body);\n+\treturn undefined;\n+}"}],"unmatched":[]}