Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions pm-stack/aggregator/src/error-boundary.ts
Original file line number Diff line number Diff line change
@@ -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
// <h1> + 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(`<h1>Not found</h1><p class="muted">no page at <code>${path}</code></p>`, {
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(
`<h1>Something went wrong</h1><p class="muted">this page failed to render — the failure is recorded, and other pages are unaffected. <a href="/health">health</a></p>`,
{ status: 500, headers: { "content-type": "text/html; charset=utf-8" } },
);
}
64 changes: 47 additions & 17 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 }),
Expand Down Expand Up @@ -401,7 +413,11 @@ async function deriveWatchdogItems(diagnosis?: ReturnType<NonNullable<Source["di
}

async function attentionContext() {
const [feed, summary, coverage] = await Promise.all([source.attention(), source.orchestration(), source.coverage()]);
const [feed, summary, coverage] = await Promise.all([
source.attention().catch(() => []),
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;
Expand Down Expand Up @@ -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 };
Expand All @@ -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()),
Expand Down Expand Up @@ -685,17 +701,21 @@ async function handler(req: Request): Promise<Response> {
}

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(
`<h1>Not found</h1><p class="muted">no SaaS service with id <code>${serviceMatch[1]}</code> — <a href="/quota">back to Usage &amp; billing</a></p>`,
404,
);
}

Expand Down Expand Up @@ -1127,16 +1147,16 @@ async function handler(req: Request): Promise<Response> {
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;
const links = subject.links;
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(() => []),
Expand Down Expand Up @@ -1171,10 +1191,10 @@ async function handler(req: Request): Promise<Response> {
};
return html(renderItem(title, id, links, notes, items, comments, prov(), extras));
}
return html(`<h1>Not found</h1><p class="muted">no board item or roadmap row with subject <code>${id}</code></p>`);
return html(`<h1>Not found</h1><p class="muted">no board item or roadmap row with subject <code>${id}</code></p>`, 404);
}

return json({ error: "not found", path }, 404);
return notFoundResponse(path);
}

/**
Expand All @@ -1187,7 +1207,17 @@ async function handler(req: Request): Promise<Response> {
*/

async function fetchHandler(req: Request): Promise<Response> {
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")) {
Expand Down
106 changes: 106 additions & 0 deletions pm-stack/aggregator/test/error-boundary-1211.test.ts
Original file line number Diff line number Diff line change
@@ -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");
});
});