diff --git a/pm-stack/aggregator/src/error-boundary.ts b/pm-stack/aggregator/src/error-boundary.ts new file mode 100644 index 0000000000..b4ac4377db --- /dev/null +++ b/pm-stack/aggregator/src/error-boundary.ts @@ -0,0 +1,49 @@ +// #1211: the aggregator's error-boundary responses. One place decides +// what a failed or unmatched request looks like, so page routes and +// API routes cannot drift apart again — the inconsistency this module +// exists to close: /item and /quota/service misses used to render +// "Not found" at HTTP 200, unknown page paths used to get the API's +// JSON 404, and a throwing handler used to reject the fetch outright +// (Bun.serve turns that into an unstyled connection-level failure +// with no render-health record). +// +// Bodies follow the server's existing fragment style: the bare +//

+ muted-paragraph shape the #1186 program 404 already renders. +// This module is deliberately free of server state so it is +// unit-testable without booting a server (the path-segment.ts +// precedent). + +export function isApiPath(path: string): boolean { + return path.startsWith("/api/"); +} + +/** The consistent not-found response: styled HTML 404 for page + * routes, JSON 404 for /api routes. */ +export function notFoundResponse(path: string): Response { + if (isApiPath(path)) { + return new Response(JSON.stringify({ error: "not found", path }, null, 2), { + status: 404, + headers: { "content-type": "application/json; charset=utf-8" }, + }); + } + return new Response(`

Not found

no page at ${path}

`, { + status: 404, + headers: { "content-type": "text/html; charset=utf-8" }, + }); +} + +/** The top-level error boundary's response for a handler throw: + * JSON 500 for /api routes, a styled 500 page for page routes. */ +export function errorBoundaryResponse(path: string, err: unknown): Response { + if (isApiPath(path)) { + const message = err instanceof Error ? err.message : String(err); + return new Response(JSON.stringify({ error: `internal error: ${message}` }, null, 2), { + status: 500, + headers: { "content-type": "application/json; charset=utf-8" }, + }); + } + return new Response( + `

Something went wrong

this page failed to render — the failure is recorded, and other pages are unaffected. health

`, + { status: 500, headers: { "content-type": "text/html; charset=utf-8" } }, + ); +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 59fce85d8f..d383d00c63 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -8,6 +8,7 @@ // apply actions; the dashboard only records them. import { stat } from "node:fs/promises"; import { decodePathSegment } from "./path-segment.ts"; +import { errorBoundaryResponse, notFoundResponse } from "./error-boundary.ts"; import { ActionsStore, validateNewAction } from "./actions.ts"; import { checkActionAgainstItem, effectiveNeedsOrder, effectiveStandingAuto, findTierItem } from "./tier-items.ts"; import { CommentsStore, validateNewComment } from "./comments.ts"; @@ -38,7 +39,7 @@ import { unavailableRoadmapReconciliation, type RoadmapReconciliation, } from "./roadmap-reconcile.ts"; -import type { DashComment, ProjectPoolItem, RefKey } from "./model.ts"; +import type { DashComment, ProjectPoolItem, QuotaView, RefKey, UsageView } from "./model.ts"; import { buildEpicRollups } from "./epics.ts"; import { buildProgramData, programRefs } from "./program.ts"; import { @@ -322,18 +323,29 @@ const PWA_MANIFEST = { ], }; +/** #1211: the fail-soft facet fallbacks — an empty view is the honest + * degraded form of a facet whose read threw (the renderers already + * banner absent data, e.g. buildAttention's tier-source-missing + * flag); a throwing facet must never 500 a whole page. */ +function emptyQuotaView(): QuotaView { + return { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }; +} +function emptyUsageView(): UsageView { + return { services: [], payg: [], charges: [], attention: [], domains: null, subscriptions: [], history: {} }; +} + async function boardContext() { - const board = await source.board(); + const board = await source.board().catch(() => []); const refs = allRefs(board); - const items = await source.items(refs); + const items = await source.items(refs).catch(() => new Map()); return { board, items }; } async function roadmapContext() { - const rows = await source.roadmap(); + const rows = await source.roadmap().catch(() => []); const refs = allRefs(rows); const [items, poolResult] = await Promise.all([ - source.items(refs), + source.items(refs).catch(() => new Map()), source.projects().then( (pool) => ({ pool, failed: false }), () => ({ pool: [] as ProjectPoolItem[], failed: true }), @@ -401,7 +413,11 @@ async function deriveWatchdogItems(diagnosis?: ReturnType []), + source.orchestration().catch(() => null), + source.coverage().catch(() => []), + ]); // Read the diagnosis AFTER orchestration() has run: the live source // recomputes it on every orchestration read (#1139). const diagnosis = source.diagnostics?.().orchestration; @@ -474,8 +490,8 @@ async function todayContext() { boardContext(), roadmapContext(), attentionContext(), - source.quota(), - source.orchestration(), + source.quota().catch(() => emptyQuotaView()), + source.orchestration().catch(() => null), ]); const diagnosis = source.diagnostics?.().orchestration; return { today: deriveToday(board, rows, items, summary, new Date(), diagnosis), view, coverage, quota }; @@ -488,7 +504,7 @@ async function overviewContext() { const [{ view }, pool, quota, health, { board }, actionsByObject] = await Promise.all([ attentionContext(), source.projects().catch(() => [] as ProjectPoolItem[]), - source.quota(), + source.quota().catch(() => emptyQuotaView()), healthContext(), boardContext(), actionsStore.byObject().catch(() => new Map()), @@ -685,17 +701,21 @@ async function handler(req: Request): Promise { } if (path === "/quota") { - const [quota, usage] = await Promise.all([source.quota(), source.usage()]); + const [quota, usage] = await Promise.all([ + source.quota().catch(() => emptyQuotaView()), + source.usage().catch(() => emptyUsageView()), + ]); return html(renderQuota(quota, prov(), usage, provDetail())); } const serviceMatch = /^\/quota\/service\/([\w-]+)$/.exec(path); if (serviceMatch) { - const usage = await source.usage(); + const usage = await source.usage().catch(() => emptyUsageView()); const svc = usage.services.find((s) => s.id === serviceMatch[1]); if (svc) return html(renderServiceDetail(svc, usage.history[svc.id] ?? [], prov(), provDetail())); return html( `

Not found

no SaaS service with id ${serviceMatch[1]} — back to Usage & billing

`, + 404, ); } @@ -1127,7 +1147,7 @@ async function handler(req: Request): Promise { if (id === null) { return json({ error: `malformed percent-encoding in path segment: ${itemMatch[1]}` }, 400); } - const [board, rows] = await Promise.all([source.board(), source.roadmap()]); + const [board, rows] = await Promise.all([source.board().catch(() => []), source.roadmap().catch(() => [])]); const subject = board.find((b) => b.id === id) ?? rows.find((r) => r.subject === id); if (subject) { const title = subject.title; @@ -1135,8 +1155,8 @@ async function handler(req: Request): Promise { const notes = "repo" in subject ? subject.notes : undefined; const refs = allRefs([subject]); const [items, comments, allComments, records, pool, allActions] = await Promise.all([ - source.items(refs), - source.comments(refs), + source.items(refs).catch(() => new Map()), + source.comments(refs).catch(() => []), commentsStore.all(), source.registry().catch(() => []), source.projects().catch(() => []), @@ -1171,10 +1191,10 @@ async function handler(req: Request): Promise { }; return html(renderItem(title, id, links, notes, items, comments, prov(), extras)); } - return html(`

Not found

no board item or roadmap row with subject ${id}

`); + return html(`

Not found

no board item or roadmap row with subject ${id}

`, 404); } - return json({ error: "not found", path }, 404); + return notFoundResponse(path); } /** @@ -1187,7 +1207,17 @@ async function handler(req: Request): Promise { */ async function fetchHandler(req: Request): Promise { - const res = await handler(req); + // #1211: the top-level error boundary. A throwing handler degrades + // to a styled 500 page (JSON for /api) instead of rejecting the + // fetch; the render-health record below still runs, accounting the + // failure as an unsuccessful render. + let res: Response; + try { + res = await handler(req); + } catch (err) { + console.error(`aggregator: handler failed for ${req.method} ${req.url}:`, err); + res = errorBoundaryResponse(new URL(req.url).pathname, err); + } if (req.method === "GET") { const route = manifestRouteFor(new URL(req.url).pathname); if (route && (res.headers.get("content-type") ?? "").includes("text/html")) { diff --git a/pm-stack/aggregator/test/error-boundary-1211.test.ts b/pm-stack/aggregator/test/error-boundary-1211.test.ts new file mode 100644 index 0000000000..0bf8a06a26 --- /dev/null +++ b/pm-stack/aggregator/test/error-boundary-1211.test.ts @@ -0,0 +1,106 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { spawn, type Subprocess } from "bun"; +import { errorBoundaryResponse, isApiPath, notFoundResponse } from "../src/error-boundary.ts"; + +// #1211: consistent not-found semantics + the top-level error +// boundary. Unit tests pin the boundary responses (server.ts's +// contexts are fail-soft per facet by construction, mirroring the +// /program route's catches; a throwing handler lands in +// fetchHandler's catch, which answers with errorBoundaryResponse) — +// the boot tests below pin the HTTP behavior end to end. + +describe("error-boundary responses (#1211)", () => { + test("isApiPath separates API routes from page routes", () => { + expect(isApiPath("/api/board.json")).toBe(true); + expect(isApiPath("/board")).toBe(false); + expect(isApiPath("/apiary")).toBe(false); + }); + + test("not found: page routes get styled HTML 404, APIs get JSON 404", async () => { + const page = notFoundResponse("/no-such-page"); + expect(page.status).toBe(404); + expect(page.headers.get("content-type")).toContain("text/html"); + expect(await page.text()).toContain("Not found"); + const api = notFoundResponse("/api/no-such"); + expect(api.status).toBe(404); + expect(api.headers.get("content-type")).toContain("application/json"); + expect(((await api.json()) as { error: string }).error).toBe("not found"); + }); + + test("error boundary: page routes get a styled 500, APIs get JSON 500 with the message", async () => { + const page = errorBoundaryResponse("/board", new Error("boom")); + expect(page.status).toBe(500); + expect(page.headers.get("content-type")).toContain("text/html"); + expect(await page.text()).toContain("Something went wrong"); + const api = errorBoundaryResponse("/api/board.json", new Error("boom")); + expect(api.status).toBe(500); + expect(((await api.json()) as { error: string }).error).toContain("boom"); + }); +}); + +let proc: Subprocess<"ignore", "pipe", "inherit"> | null = null; +let port = 0; + +beforeAll(async () => { + port = 4300 + Math.floor(Math.random() * 800); + proc = spawn({ + cmd: ["bun", "run", "src/server.ts"], + cwd: import.meta.dir + "/..", + env: { ...Bun.env, PM_AGG_PORT: String(port), PM_AGG_SOURCE: "fixtures" }, + stdout: "pipe", + stderr: "inherit", + }); + const deadline = Date.now() + 8000; + let ready = false; + while (Date.now() < deadline) { + try { + const res = await fetch(`http://127.0.0.1:${port}/api/health`); + if (res.ok) { + ready = true; + break; + } + } catch { + /* not up yet */ + } + await Bun.sleep(120); + } + expect(ready).toBe(true); +}); + +afterAll(() => { + proc?.kill(); +}); + +describe("consistent not-found semantics over HTTP (#1211)", () => { + test("/item and /quota/service misses are 404, not 200", async () => { + const item = await fetch(`http://127.0.0.1:${port}/item/no-such-item`); + expect(item.status).toBe(404); + expect(await item.text()).toContain("Not found"); + const svc = await fetch(`http://127.0.0.1:${port}/quota/service/no-such-service`); + expect(svc.status).toBe(404); + expect(await svc.text()).toContain("Not found"); + }); + + test("unknown page routes are styled HTML 404; unknown APIs are JSON 404", async () => { + const page = await fetch(`http://127.0.0.1:${port}/no-such-page`); + expect(page.status).toBe(404); + expect(page.headers.get("content-type")).toContain("text/html"); + expect(await page.text()).toContain("Not found"); + const api = await fetch(`http://127.0.0.1:${port}/api/no-such-thing`); + expect(api.status).toBe(404); + expect(api.headers.get("content-type")).toContain("application/json"); + expect(((await api.json()) as { error: string }).error).toBe("not found"); + }); + + test("known pages still render, and the degraded attention banner still renders", async () => { + for (const path of ["/", "/board", "/roadmap", "/quota", "/program", "/health"]) { + const res = await fetch(`http://127.0.0.1:${port}${path}`); + expect(res.status).toBe(200); + } + // Fixtures carry no orchestration section: the attention page's + // degraded form (tier-source-missing banner) is the fail-soft + // render this issue's acceptance names. + const full = await (await fetch(`http://127.0.0.1:${port}/attention?full=1`)).text(); + expect(full).toContain("Tier source missing"); + }); +});