diff --git a/docs/architecture/routing-pages-and-patterns.md b/docs/architecture/routing-pages-and-patterns.md index 98d214c4..3358a594 100644 --- a/docs/architecture/routing-pages-and-patterns.md +++ b/docs/architecture/routing-pages-and-patterns.md @@ -280,6 +280,18 @@ chunk recovery 순서: 4. 안전한 support surface와 trace/build ID를 표시한다. 5. recovery 결과를 redacted diagnostics에 기록한다. +지원 참조는 사용자가 문의할 때 말하는 값이고, 진단 이벤트에서 같은 값을 찾을 +수 있다. + +- 라우트 렌더 실패: `buildId:incidentId`. 같은 incident ID가 `ui.render.failed` + 진단의 `correlation_id`에 남는다(`render-error-boundary.tsx`의 + `newIncidentId`, `create-application.ts`의 `reportRenderFailure`). 화면에는 + "한 번 새로고침" 버튼이 있다(`app-router.tsx`의 `RouteFailureSurface`). +- 복구하지 못한 청크 실패: 같은 형식이다. `ChunkRecoveryBoundary`의 + `onUnrecovered`가 같은 ID로 `ui.render.failed`를 기록한다. +- 조회 실패: `AppFailure.requestId`. HTTP 진단의 `correlation_id`와 같은 값이다 + (`async-surface.tsx`의 `TerminalErrorSurface`). + custom fallback을 넘겨 retry/reset 기능을 잃지 않게 한다. boundary는 `location.key` 또는 route ID가 바뀌면 적절히 reset된다. diff --git a/src/application/create-application.ts b/src/application/create-application.ts index fccb38da..5625e5de 100644 --- a/src/application/create-application.ts +++ b/src/application/create-application.ts @@ -62,6 +62,11 @@ export function createApplication( route_id: report.routeId, build_id: report.buildId, component_boundary: report.boundaryName, + // Incident-scoped like a request id: diagnostics only, never + // telemetry. + ...(report.incidentId === undefined + ? {} + : { correlation_id: report.incidentId }), }, }); } catch { diff --git a/src/application/ports/in/application-api.ts b/src/application/ports/in/application-api.ts index f4f7f2bb..fbf7564c 100644 --- a/src/application/ports/in/application-api.ts +++ b/src/application/ports/in/application-api.ts @@ -24,6 +24,8 @@ export type RenderFailureReport = Readonly<{ routeId: string; buildId: string; boundaryName: "route" | "feature"; + /** 08-07. The id the failure page shows as its support reference. */ + incidentId?: string; }>; export type RouteChangedReport = Readonly<{ diff --git a/src/presentation/boundaries/chunk-recovery-boundary.tsx b/src/presentation/boundaries/chunk-recovery-boundary.tsx index 8cc8e375..cca4ca6d 100644 --- a/src/presentation/boundaries/chunk-recovery-boundary.tsx +++ b/src/presentation/boundaries/chunk-recovery-boundary.tsx @@ -5,6 +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"; type RecoveryResult = | Readonly<{ action: "reload-once"; releasePair: string }> @@ -17,12 +18,17 @@ type Props = Readonly<{ chunkId: string; failureKind: "CHUNK_LOAD_FAILURE"; }>): Promise; + /** 08-07. Shown with the incident id as the support reference. */ + buildId?: string; + /** 08-07. Records the incident id the support surface shows. */ + onUnrecovered?: (incidentId: string) => void; }>; type State = Readonly<{ error: unknown | null; recovery: "idle" | "checking" | "reload-requested" | "support"; reason?: string; + incidentId?: string; }>; export function isChunkLoadFailure(error: unknown): boolean { @@ -55,26 +61,29 @@ export class ChunkRecoveryBoundary extends Component { failureKind: "CHUNK_LOAD_FAILURE", }) .then((result) => { - this.setState({ - error, - recovery: - result.action === "reload-once" - ? "reload-requested" - : "support", - ...(result.action === "support" ? { reason: result.reason } : {}), - }); + if (result.action === "support") { + this.showSupport(error, result.reason); + } else { + this.setState({ error, recovery: "reload-requested" }); + } }) .catch(() => { - this.setState({ - error, - recovery: "support", - reason: "recovery-controller-failed", - }); + this.showSupport(error, "recovery-controller-failed"); }); } + private showSupport(error: unknown, reason: string) { + const incidentId = newIncidentId(); + this.setState({ error, recovery: "support", reason, incidentId }); + try { + this.props.onUnrecovered?.(incidentId); + } catch { + // Diagnostics must never hide the recovery surface. + } + } + render() { - const { error, recovery, reason } = this.state; + const { error, recovery, reason, incidentId } = this.state; if (error && !isChunkLoadFailure(error)) throw error; if (error && recovery === "checking") { return ; @@ -83,7 +92,15 @@ export class ChunkRecoveryBoundary extends Component { return ; } if (error && recovery === "support") { - return ; + return ( + + ); } return this.props.children; } @@ -92,9 +109,11 @@ export class ChunkRecoveryBoundary extends Component { function ChunkRecoverySurface({ recovery, reason, + supportReference, }: Readonly<{ recovery: Exclude; reason?: string; + supportReference?: string; }>) { const { message } = useLocale(); if (recovery === "checking") { @@ -119,6 +138,13 @@ function ChunkRecoverySurface({ + {supportReference ? ( +

+ {message("template.supportReference", { + reference: supportReference, + })} +

+ ) : null} ); } diff --git a/src/presentation/boundaries/render-error-boundary.tsx b/src/presentation/boundaries/render-error-boundary.tsx index 36e69ad8..6d4f39b9 100644 --- a/src/presentation/boundaries/render-error-boundary.tsx +++ b/src/presentation/boundaries/render-error-boundary.tsx @@ -10,10 +10,24 @@ export type RenderBoundaryProps = Readonly<{ buildId: string; resetKey?: string; onRenderFailure?: (report: RenderFailureReport) => void; - fallback?: ReactNode; + /** A function receives the incident id the failure was reported with. */ + fallback?: ReactNode | ((incidentId: string) => ReactNode); }>; -type RenderBoundaryState = Readonly<{ hasError: boolean }>; +type RenderBoundaryState = Readonly<{ + hasError: boolean; + 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, @@ -22,7 +36,7 @@ export class RenderErrorBoundary extends Component< state: RenderBoundaryState = { hasError: false }; static getDerivedStateFromError(): RenderBoundaryState { - return { hasError: true }; + return { hasError: true, incidentId: newIncidentId() }; } componentDidCatch(): void { @@ -31,6 +45,9 @@ export class RenderErrorBoundary extends Component< routeId: this.props.routeId, buildId: this.props.buildId, boundaryName: this.props.boundaryName, + ...(this.state.incidentId === undefined + ? {} + : { incidentId: this.state.incidentId }), }); } catch { // Diagnostics must never recurse into another render failure. @@ -49,9 +66,11 @@ export class RenderErrorBoundary extends Component< render(): ReactNode { if (this.state.hasError) { - return ( - this.props.fallback ?? - ); + const { fallback } = this.props; + if (typeof fallback === "function") { + return fallback(this.state.incidentId ?? newIncidentId()); + } + return fallback ?? ; } return this.props.children; } diff --git a/src/presentation/components/async-surface.tsx b/src/presentation/components/async-surface.tsx index e551e43b..74ab5536 100644 --- a/src/presentation/components/async-surface.tsx +++ b/src/presentation/components/async-surface.tsx @@ -57,6 +57,8 @@ export type TerminalErrorSurfaceProps = Readonly<{ onAction?: () => void; /** Read before the action, inside the same alert. */ description?: string; + /** 08-07. The id a user quotes to support, e.g. `AppFailure.requestId`. */ + supportReference?: string; }>; export function TerminalErrorSurface({ @@ -64,6 +66,7 @@ export function TerminalErrorSurface({ action, onAction, description, + supportReference, }: TerminalErrorSurfaceProps) { const { locale, message } = useLocale(); const messageId = useId(); @@ -88,6 +91,13 @@ export function TerminalErrorSurface({ {action !== "none" && onAction && ( )} + {supportReference ? ( +

+ {message("template.supportReference", { + reference: supportReference, + })} +

+ ) : null} ); } @@ -130,6 +140,7 @@ export function AsyncSurface({ ? onRetry ?? onAction : onAction } + supportReference={state.failure.requestId} /> ); } diff --git a/src/presentation/routes/app-router.tsx b/src/presentation/routes/app-router.tsx index f29122e6..5a333654 100644 --- a/src/presentation/routes/app-router.tsx +++ b/src/presentation/routes/app-router.tsx @@ -91,8 +91,11 @@ function RouteLoadingSurface({ function RouteFailureSurface({ definition, + supportReference, }: { definition?: RouteDefinition; + /** 08-07. The build and, when reported, the incident id. */ + supportReference: string; }) { const { message } = useLocale(); return ( @@ -101,6 +104,14 @@ function RouteFailureSurface({ title: message("route.failure.title"), description: message("route.failure.description"), }} + // RENDER_FAILURE's registry action: a render defect stays until the + // URL changes, so the page offers the reload itself. + primaryAction={{ + kind: "button", + label: message("action.reloadOnce"), + onAction: () => window.location.reload(), + }} + supportReference={supportReference} surface={definition?.errorSurface ?? "route-boundary"} variant="unexpected" /> @@ -328,6 +339,8 @@ function RouteSurface({ if (!runtime) return ; const parsed = parseRouteInput(routeId, params, search); if (!parsed.success) return ; + const boundaryName = + definition.errorSurface === "feature-boundary" ? "feature" : "route"; const content = ( @@ -339,6 +352,15 @@ function RouteSurface({ key={definition.routeId} chunkId={definition.chunkId} recover={recovery.recoverChunk} + buildId={buildId} + onUnrecovered={(incidentId) => + diagnostics.reportRenderFailure({ + routeId, + buildId, + boundaryName, + incidentId, + }) + } > @@ -356,10 +378,15 @@ function RouteSurface({ buildId, resetKey: `${location.pathname}${location.search}`, onRenderFailure: diagnostics.reportRenderFailure, - fallback: , + fallback: (incidentId: string) => ( + + ), children: protectedContent, }; - return definition.errorSurface === "feature-boundary" ? ( + return boundaryName === "feature" ? ( ) : ( @@ -404,6 +431,7 @@ function ContextRouteGateway({ }: Readonly<{ routeModule: ContextRouteModule; buildId: string }>) { const location = useLocation(); const recovery = useApplicationRecovery(); + const diagnostics = useApplicationDiagnostics(); const [routes, setRoutes] = useState(null); const [failure, setFailure] = useState | null>( null, @@ -431,7 +459,7 @@ function ContextRouteGateway({ } + fallback={} > {content} @@ -444,11 +472,20 @@ function ContextRouteGateway({ + diagnostics.reportRenderFailure({ + routeId: routeModule.id, + buildId, + boundaryName: "route", + incidentId, + }) + } > ) : ( - + ); } if (routes === null) return ; @@ -475,7 +512,7 @@ function ContextRouteGateway({ } + fallback={} > {route} @@ -522,7 +559,7 @@ function createRegisteredRoutes(buildId: string): RouteObject[] { id: "APP_SHELL", path: "/", element: , - errorElement: , + errorElement: , children: [...platformChildren, ...contextChildren], }, ]; diff --git a/tests/component/async-surface.test.tsx b/tests/component/async-surface.test.tsx index 7cb44269..9bf6b36d 100644 --- a/tests/component/async-surface.test.tsx +++ b/tests/component/async-surface.test.tsx @@ -138,6 +138,17 @@ describe("async UI state matrix", () => { expect(resolveConflict).toHaveBeenCalledOnce(); }); + // 08-07. The id a user quotes when asking for help is the one the request + // diagnostics carry as `correlation_id`. + it("shows the failure's request id as its support reference", () => { + const failure = { + ...createFailure("SERVER_FAILURE", "LIST", 1), + requestId: "req-7f3a", + }; + render(); + expect(screen.getByRole("alert")).toHaveTextContent("지원 참조: req-7f3a"); + }); + it("renders only safe error vocabulary", () => { const failure = createFailure("SERVER_FAILURE", "LIST", 0, { code: "SERVER_FAILURE", diff --git a/tests/component/chunk-recovery-boundary.test.tsx b/tests/component/chunk-recovery-boundary.test.tsx index 8efd76f5..98efa952 100644 --- a/tests/component/chunk-recovery-boundary.test.tsx +++ b/tests/component/chunk-recovery-boundary.test.tsx @@ -141,6 +141,34 @@ describe("chunk recovery boundary classification", () => { ).toBeVisible(); }); + // 08-07. An unrecovered chunk failure shows a reference the render + // diagnostic also records. + it("shows an unrecovered chunk failure's support reference and records it", async () => { + const record = vi.fn(); + window.history.pushState({}, "", "/examples/states"); + render( + + + + + , + ); + + const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/); + const incidentId = reference.textContent?.split(":").at(-1); + expect(record).toHaveBeenCalledWith({ + level: "error", + eventId: "ui.render.failed", + context: expect.objectContaining({ + route_id: "EXAMPLES_STATES", + build_id: "build-a", + correlation_id: incidentId, + }), + }); + }); + it("clears a failed route chunk when the user moves to a sibling route", async () => { // React Router reuses the rendered-route instance between sibling routes, // so a failure latched in one route's boundary would otherwise follow the diff --git a/tests/component/render-boundary.test.tsx b/tests/component/render-boundary.test.tsx index 812d520f..4de85108 100644 --- a/tests/component/render-boundary.test.tsx +++ b/tests/component/render-boundary.test.tsx @@ -11,6 +11,17 @@ import { AsyncSurface } from "../../src/presentation/components/async-surface.ts import { BootErrorShell } from "../../src/presentation/boundaries/boot-error-shell.tsx"; import { FeatureBoundary } from "../../src/presentation/boundaries/render-error-boundary.tsx"; import { LocaleProvider } from "../../src/presentation/i18n/index.ts"; +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"; + +// The states page stands in for any route page with a programmer defect. +vi.mock("../../src/presentation/examples/state-gallery-page.tsx", () => ({ + default: function BrokenPage(): never { + throw new Error("ordinary render defect"); + }, +})); function Defect(): ReactNode { throw new Error("raw render stack"); @@ -36,9 +47,39 @@ describe("render recovery boundaries", () => { routeId: "APP_HOME", buildId: "build-a", boundaryName: "feature", + incidentId: expect.stringMatching(/^[0-9a-f]{8}$/), }); }); + // 08-07. The route failure page shows the reference the user quotes, the + // same id the render diagnostic records, and a way out besides the URL. + it("shows a route render failure's support reference and records it", async () => { + const record = vi.fn(); + window.history.pushState({}, "", "/examples/states"); + render( + + + + + , + ); + + const reference = await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/); + const incidentId = reference.textContent?.split(":").at(-1); + expect(record).toHaveBeenCalledWith({ + level: "error", + eventId: "ui.render.failed", + context: expect.objectContaining({ + route_id: "EXAMPLES_STATES", + build_id: "build-a", + correlation_id: incidentId, + }), + }); + expect(screen.getByRole("button", { name: "한 번 새로고침" })).toBeVisible(); + }); + it("keeps normalized operational failures in normal async state", () => { const state = deriveAsyncState({ failure: createFailure("SERVER_FAILURE", "LIST", 0),