diff --git a/src/platform/errors/context-error-boundary.tsx b/src/platform/errors/context-error-boundary.tsx index d6655b8a..402d6ad2 100644 --- a/src/platform/errors/context-error-boundary.tsx +++ b/src/platform/errors/context-error-boundary.tsx @@ -14,7 +14,7 @@ export function ContextErrorBoundary( props: Readonly<{ contextId?: string; children: ReactNode; - fallback?: ReactNode; + fallback?: ScopedErrorBoundaryProps["fallback"]; resetKey?: string; onError?: ScopedErrorBoundaryProps["onError"]; }>, diff --git a/src/platform/errors/feature-error-boundary.tsx b/src/platform/errors/feature-error-boundary.tsx index e68f9cfb..473537e7 100644 --- a/src/platform/errors/feature-error-boundary.tsx +++ b/src/platform/errors/feature-error-boundary.tsx @@ -13,7 +13,7 @@ export function FeatureErrorBoundary( props: Readonly<{ featureId: string; children: ReactNode; - fallback?: ReactNode; + fallback?: ScopedErrorBoundaryProps["fallback"]; resetKey?: string; onError?: ScopedErrorBoundaryProps["onError"]; }>, diff --git a/src/platform/errors/incident-id.ts b/src/platform/errors/incident-id.ts new file mode 100644 index 00000000..281721ff --- /dev/null +++ b/src/platform/errors/incident-id.ts @@ -0,0 +1,10 @@ +/** + * 08-07. A short id a failure page shows as its support reference and the + * render diagnostic records, so a user's report finds the event. + * `getRandomValues` also works outside secure contexts, unlike `randomUUID`. + * Every error boundary takes its incident ids from here (09-09). + */ +export function newIncidentId(): string { + const [value = 0] = crypto.getRandomValues(new Uint32Array(1)); + return value.toString(16).padStart(8, "0"); +} diff --git a/src/platform/errors/scoped-error-boundary.tsx b/src/platform/errors/scoped-error-boundary.tsx index e1f569b1..2ae3753c 100644 --- a/src/platform/errors/scoped-error-boundary.tsx +++ b/src/platform/errors/scoped-error-boundary.tsx @@ -1,5 +1,7 @@ import { Component, type ReactNode } from "react"; +import { newIncidentId } from "./incident-id.ts"; + /** * Spec §30. Render-failure containment aligned with ownership boundaries. * @@ -10,32 +12,50 @@ import { Component, type ReactNode } from "react"; */ export type ErrorBoundaryScope = "context" | "feature"; +/** + * 09-09. The incident id is the one a function fallback receives, so the + * support reference on screen finds the reported event. + */ +export type ScopedErrorReport = Readonly<{ + scope: ErrorBoundaryScope; + ownerId: string; + incidentId: string; +}>; + export type ScopedErrorBoundaryProps = Readonly<{ scope: ErrorBoundaryScope; ownerId: string; children: ReactNode; - fallback?: ReactNode; + /** A function receives the incident id the failure was reported with. */ + fallback?: ReactNode | ((incidentId: string) => ReactNode); /** Changing the key clears a caught failure (e.g. on navigation). */ resetKey?: string; - onError?: (report: Readonly<{ scope: ErrorBoundaryScope; ownerId: string }>) => void; + onError?: (report: ScopedErrorReport) => void; }>; -type ScopedErrorBoundaryState = Readonly<{ failed: boolean }>; +type ScopedErrorBoundaryState = Readonly<{ + failed: boolean; + incidentId: string; +}>; export class ScopedErrorBoundary extends Component< ScopedErrorBoundaryProps, ScopedErrorBoundaryState > { - state: ScopedErrorBoundaryState = { failed: false }; + state: ScopedErrorBoundaryState = { failed: false, incidentId: "" }; static getDerivedStateFromError(): ScopedErrorBoundaryState { - return { failed: true }; + return { failed: true, incidentId: newIncidentId() }; } componentDidCatch(): void { try { this.props.onError?.( - Object.freeze({ scope: this.props.scope, ownerId: this.props.ownerId }), + Object.freeze({ + scope: this.props.scope, + ownerId: this.props.ownerId, + incidentId: this.state.incidentId, + }), ); } catch { // Observability is outside the render authority. @@ -50,13 +70,16 @@ export class ScopedErrorBoundary extends Component< render(): ReactNode { if (!this.state.failed) return this.props.children; + const { fallback } = this.props; return (
- {this.props.fallback ?? null} + {typeof fallback === "function" + ? fallback(this.state.incidentId) + : (fallback ?? null)}
); } diff --git a/src/presentation/boundaries/chunk-recovery-boundary.tsx b/src/presentation/boundaries/chunk-recovery-boundary.tsx index cca4ca6d..8af8d5a9 100644 --- a/src/presentation/boundaries/chunk-recovery-boundary.tsx +++ b/src/presentation/boundaries/chunk-recovery-boundary.tsx @@ -5,7 +5,7 @@ import { } from "react"; import { Button, LoadingSurface } from "../design-system/index.ts"; import { useLocale } from "../i18n/index.ts"; -import { newIncidentId } from "./render-error-boundary.tsx"; +import { newIncidentId } from "../../platform/errors/incident-id.ts"; type RecoveryResult = | Readonly<{ action: "reload-once"; releasePair: string }> diff --git a/src/presentation/boundaries/render-error-boundary.tsx b/src/presentation/boundaries/render-error-boundary.tsx index 6d4f39b9..aeac874b 100644 --- a/src/presentation/boundaries/render-error-boundary.tsx +++ b/src/presentation/boundaries/render-error-boundary.tsx @@ -1,6 +1,7 @@ import { Component, type ReactNode } from "react"; import type { RenderFailureReport } from "../../application/ports/in/application-api.ts"; +import { newIncidentId } from "../../platform/errors/incident-id.ts"; import { useLocale } from "../i18n/index.ts"; export type RenderBoundaryProps = Readonly<{ @@ -19,16 +20,6 @@ type RenderBoundaryState = Readonly<{ incidentId?: string; }>; -/** - * 08-07. A short id a failure page shows as its support reference and the - * render diagnostic records, so a user's report finds the event. - * `getRandomValues` also works outside secure contexts, unlike `randomUUID`. - */ -export function newIncidentId(): string { - const [value = 0] = crypto.getRandomValues(new Uint32Array(1)); - return value.toString(16).padStart(8, "0"); -} - export class RenderErrorBoundary extends Component< RenderBoundaryProps, RenderBoundaryState diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index 26e51ba5..87691d33 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -41,8 +41,10 @@ import { ChunkRecoveryBoundary, isChunkLoadFailure, } from "../boundaries/chunk-recovery-boundary.tsx"; +import type { RenderFailureReport } from "../../application/ports/in/application-api.ts"; import { ContextErrorBoundary } from "../../platform/errors/context-error-boundary.tsx"; import { FeatureErrorBoundary } from "../../platform/errors/feature-error-boundary.tsx"; +import type { ScopedErrorReport } from "../../platform/errors/scoped-error-boundary.tsx"; import { LoadingSurface, StatusPage } from "../design-system/index.ts"; import { useLocale } from "../i18n/index.ts"; import { AppShell } from "../layouts/app-shell.tsx"; @@ -520,11 +522,25 @@ function ContextRouteGateway({ }, [enteredPathname, features, platformRuntime, routeModule]); const resetKey = `${location.pathname}${location.search}`; - const withinContext = (content: ReactNode) => ( + // 09-09. What the context and feature boundaries catch is reported like a + // route boundary's failure, and the page shows the same incident id. The + // context boundary reports as "route": the diagnostic contract has no + // context value for `component_boundary`. + const reportedFailure = ( + routeId: string, + boundaryName: RenderFailureReport["boundaryName"], + ) => ({ + onError: ({ incidentId }: ScopedErrorReport) => + diagnostics.reportRenderFailure({ routeId, buildId, boundaryName, incidentId }), + fallback: (incidentId: string) => ( + + ), + }); + const withinContext = (routeId: string, content: ReactNode) => ( } + {...reportedFailure(routeId, "route")} > {content} @@ -550,7 +566,13 @@ function ContextRouteGateway({ ) : ( - + // Any other load failure (a routes module that throws while it + // evaluates, a feature runtime that does not load) escalates to the + // context boundary, which reports it. + withinContext( + registeredRouteIdAt(location.pathname) ?? routeModule.id, + , + ) ); } if (routes === null) return ; @@ -572,13 +594,14 @@ function ContextRouteGateway({ /> ); return withinContext( + handle.routeId, featureId === undefined ? ( route ) : ( } + {...reportedFailure(handle.routeId, "feature")} > {route} diff --git a/tests/component/context-boundary-diagnostics.test.tsx b/tests/component/context-boundary-diagnostics.test.tsx new file mode 100644 index 00000000..a1b33e6e --- /dev/null +++ b/tests/component/context-boundary-diagnostics.test.tsx @@ -0,0 +1,134 @@ +// @vitest-environment jsdom + +import { render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { ApplicationProvider } from "../../src/presentation/providers/application-provider.tsx"; +import { PreferenceProviders } from "../../src/presentation/providers/preference-providers.tsx"; +import { AppRouter } from "../../src/presentation/routes/app-router.tsx"; +import { createTestApplication } from "../helpers/create-test-application.ts"; + +/** + * 09-09 (0929/08-05). Failures the context gateway catches outside a route's + * own boundary: the context boundary (a route handle naming an unregistered + * route), the feature boundary (a handle without the codecs its route needs) + * and a routes module that fails for a reason other than a missing chunk. + * Each has to leave a `ui.render.failed` record whose incident id the screen + * shows as `:`. + */ +vi.mock("../../src/.generated/product-feature-index.ts", async () => ({ + DECLARED_PRODUCT_FEATURE_IDS: ["fixture-feature"], + PRODUCT_FEATURE_MODULES: [(await import("../helpers/fixture-feature.tsx")).FIXTURE_FEATURE_MODULE], +})); +vi.mock("../../src/apps/template-app.ts", async () => { + const { FIXTURE_CONTEXT_ROUTES } = await import("../helpers/fixture-feature.tsx"); + const items = FIXTURE_CONTEXT_ROUTES.find((route) => route.id === "FIXTURE_ITEMS"); + const runtime = (items?.handle as { runtime: unknown }).runtime; + return { + TEMPLATE_APP_MODULE: { + id: "boundary-app", + budget: { maxContexts: 3 }, + contexts: [ + { + id: "context-without-codecs", + route: { + path: "fixture/items/*", + loadRoutes: async () => [ + { + id: "FIXTURE_ITEMS", + path: "/fixture/items", + handle: { routeId: "FIXTURE_ITEMS", runtime }, + }, + ], + }, + }, + { + id: "context-with-typo", + route: { + path: "fixture/items/status/*", + loadRoutes: async () => [ + { + id: "FIXTURE_ITEM_STATUSS", + path: "/fixture/items/status", + handle: { routeId: "FIXTURE_ITEM_STATUSS", runtime }, + }, + ], + }, + }, + { + id: "context-broken", + route: { + path: "fixture/items/new/*", + loadRoutes: async () => { + throw new ReferenceError("pageComponent is not defined"); + }, + }, + }, + ], + }, + }; +}); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +async function expectReportedFailure( + url: string, + expected: Readonly<{ routeId: string; boundary: "route" | "feature" }>, +) { + // React logs every caught render error; the assertions below are the point. + vi.spyOn(console, "error").mockImplementation(() => {}); + const record = vi.fn(); + window.history.pushState({}, "", url); + render( + + + + + , + ); + + const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/); + const incidentId = reference.textContent?.split(":").at(-1); + const failures = record.mock.calls + .map(([event]) => event as { eventId: string; context: Record }) + .filter((event) => event.eventId === "ui.render.failed"); + expect(failures).toEqual([ + { + level: "error", + eventId: "ui.render.failed", + context: { + route_id: expected.routeId, + build_id: "build-a", + component_boundary: expected.boundary, + correlation_id: incidentId, + }, + }, + ]); +} + +describe("context gateway failure diagnostics", () => { + it("reports what the context boundary catches", async () => { + await expectReportedFailure("/fixture/items/status", { + routeId: "FIXTURE_ITEM_STATUSS", + boundary: "route", + }); + }); + + it("reports what the feature boundary catches", async () => { + await expectReportedFailure("/fixture/items", { + routeId: "FIXTURE_ITEMS", + boundary: "feature", + }); + }); + + it("reports a routes module that fails without a missing chunk", async () => { + await expectReportedFailure("/fixture/items/new", { + routeId: "FIXTURE_ITEM_FORM", + boundary: "route", + }); + }); +}); diff --git a/tests/platform/errors/failure-boundary.test.tsx b/tests/platform/errors/failure-boundary.test.tsx index 34e40cfe..e270ba58 100644 --- a/tests/platform/errors/failure-boundary.test.tsx +++ b/tests/platform/errors/failure-boundary.test.tsx @@ -55,10 +55,31 @@ describe("ownership-aligned failure boundaries", () => { , ); - expect(onError).toHaveBeenCalledWith({ scope: "feature", ownerId: "broken" }); + expect(onError).toHaveBeenCalledWith({ + scope: "feature", + ownerId: "broken", + incidentId: expect.stringMatching(/^[0-9a-f]{8}$/), + }); expect(screen.getByText("fallback")).toBeInTheDocument(); }); + // 09-09. The support reference on screen has to find the reported event. + it("gives a function fallback the incident id it reported", () => { + vi.spyOn(console, "error").mockImplementation(() => {}); + const onError = vi.fn(); + render( +

incident {incidentId}

} + > + +
, + ); + const [[report]] = onError.mock.calls as [[{ incidentId: string }]]; + expect(screen.getByText(`incident ${report.incidentId}`)).toBeInTheDocument(); + }); + it("clears a contained failure when its reset key changes", () => { vi.spyOn(console, "error").mockImplementation(() => {}); let shouldThrow = true;