fix(router): context·feature 경계와 라우트 모듈 실패를 진단에 남긴다 (09-09)

문제: context gateway의 `ContextErrorBoundary`·`FeatureErrorBoundary`는
`onError`를 받지 않아 잡은 실패를 진단에 남기지 않고, 화면 지원 참조는
buildId뿐이다. 라우트 모듈이 청크 누락이 아닌 이유로 실패할 때(평가 중
throw, 15-01 뒤로는 기능 실행부 적재 실패)도 같은 화면만 그리고 기록이
없다. 안쪽 경계(`RenderErrorBoundary`) 밖에서 난 실패, 예를 들어 핸들의
route id가 레지스트리에 없거나 핸들에 라우트 codec이 없을 때는 사용자
신고로도 사건을 찾을 수 없다. 0929/08-05와 같은 결함이다.

고른 방법:
- `ScopedErrorBoundary`가 잡을 때 incident id를 만들어 `onError` 보고에
  넣고, 함수형 fallback에 같은 id를 넘긴다. 둘 다 추가 변경이다(기존
  ReactNode fallback과 `{scope, ownerId}`를 읽는 쪽은 그대로 동작).
- incident id 생성기를 `src/platform/errors/incident-id.ts`로 옮겨 두
  경계 계열이 같은 함수를 쓴다(platform은 presentation을 import할 수 없다).
- gateway가 두 경계에 `reportRenderFailure` 호출과
  `<buildId>:<incidentId>` 지원 참조를 넘긴다. context 경계는
  `component_boundary`를 "route"로 보고한다. 진단·텔레메트리 계약에
  context 값이 없고, 같은 gateway의 청크 복구 보고도 "route"를 쓴다.
- 비청크 적재 실패는 context 경계 안에서 다시 throw해 같은 보고 경로를
  탄다. route id는 URL의 등록 라우트, 없으면 context id다.

버린 대안:
- 세 곳을 presentation `RouteBoundary`로 바꾸기(0929/08-05 제안): 경계
  두 계열 통합(리팩토링 R4) 성격이고 context/feature 소유 범위 표시
  (`data-boundary`, testid)가 바뀐다.
- gateway가 URL마다 incident id를 하나 만들어 두 경계에 나눠 주기:
  두 경계가 같은 id를 공유해 사건 구분이 흐려진다.
- `component_boundary`에 "context" 추가: 진단·텔레메트리 계약과
  레지스트리 기준선을 바꾸는 일이라 이번 범위 밖이다.

위험·한계:
- `APP_SHELL`의 `errorElement`(0929/08-05가 함께 적은 곳)는 그대로
  buildId만 보이고 보고하지 않는다. React Router 오류 요소라 다른 방식
  (useRouteError + 마운트 시 보고)이 필요해 남겼다.
- 실패한 context 안에서 URL을 바꾸면 경계가 리셋되고 다시 throw해 방문마다
  한 번 보고한다.
- 화면 변화: context·feature 경계 실패 화면과 비청크 적재 실패 화면의
  지원 참조가 `build:incident` 형식이 된다. 시각 골든에는 없는 화면이다.
- 초기 JS +58 B gzip(202,748 → 202,806 B, 여유 1,994 B).

검증:
- RED: tests/component/context-boundary-diagnostics.test.tsx 3건(context
  경계: 미등록 핸들 id, feature 경계: codec 없는 핸들, 비청크 적재 실패)이
  모두 `Unable to find an element with the text: /^지원 참조:
  build-a:[0-9a-f]{8}$/`로 실패. 화면은 "지원 참조: build-a"였다.
- GREEN: 3건 통과. failure-boundary.test.tsx에 함수형 fallback이 보고한
  incident id를 받는지 1건 추가, `onError` 보고 기대값에 incidentId 추가.
- 회귀: tests/{architecture,platform,component,features,scripts,contract}
  95 files / 592 tests, tests/unit(pnpm을 띄우는 5개 제외) 164 files /
  1,929 tests 통과. tsc app·test 통과. 바꾼 파일 eslint 통과.
  check-architecture(shim), check-adapter-inventory, check-diagnostics,
  check-registries 통과.
This commit is contained in:
DongHyeonka
2026-11-01 22:56:29 +09:00
parent 7139c7c61e
commit de48db25d9
9 changed files with 227 additions and 25 deletions
@@ -14,7 +14,7 @@ export function ContextErrorBoundary(
props: Readonly<{
contextId?: string;
children: ReactNode;
fallback?: ReactNode;
fallback?: ScopedErrorBoundaryProps["fallback"];
resetKey?: string;
onError?: ScopedErrorBoundaryProps["onError"];
}>,
@@ -13,7 +13,7 @@ export function FeatureErrorBoundary(
props: Readonly<{
featureId: string;
children: ReactNode;
fallback?: ReactNode;
fallback?: ScopedErrorBoundaryProps["fallback"];
resetKey?: string;
onError?: ScopedErrorBoundaryProps["onError"];
}>,
+10
View File
@@ -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");
}
+30 -7
View File
@@ -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 (
<div
role="alert"
data-boundary={this.props.scope}
data-testid={`${this.props.scope}-fallback-${this.props.ownerId}`}
>
{this.props.fallback ?? null}
{typeof fallback === "function"
? fallback(this.state.incidentId)
: (fallback ?? null)}
</div>
);
}
@@ -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 }>
@@ -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
+27 -4
View File
@@ -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) => (
<RouteFailureSurface supportReference={`${buildId}:${incidentId}`} />
),
});
const withinContext = (routeId: string, content: ReactNode) => (
<ContextErrorBoundary
contextId={routeModule.id}
resetKey={resetKey}
fallback={<RouteFailureSurface supportReference={buildId} />}
{...reportedFailure(routeId, "route")}
>
{content}
</ContextErrorBoundary>
@@ -550,7 +566,13 @@ function ContextRouteGateway({
<Rethrow error={failure.error} />
</ChunkRecoveryBoundary>
) : (
<RouteFailureSurface supportReference={buildId} />
// 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,
<Rethrow error={failure.error} />,
)
);
}
if (routes === null) return <RouteLoadingSurface />;
@@ -572,13 +594,14 @@ function ContextRouteGateway({
/>
);
return withinContext(
handle.routeId,
featureId === undefined ? (
route
) : (
<FeatureErrorBoundary
featureId={featureId}
resetKey={resetKey}
fallback={<RouteFailureSurface supportReference={buildId} />}
{...reportedFailure(handle.routeId, "feature")}
>
{route}
</FeatureErrorBoundary>
@@ -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 `<buildId>:<incidentId>`.
*/
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(
<ApplicationProvider
application={createTestApplication({ diagnostics: { record } })}
>
<PreferenceProviders>
<AppRouter buildId="build-a" />
</PreferenceProviders>
</ApplicationProvider>,
);
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<string, unknown> })
.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",
});
});
});
@@ -55,10 +55,31 @@ describe("ownership-aligned failure boundaries", () => {
<ThrowsOnRender />
</FeatureErrorBoundary>,
);
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(
<ContextErrorBoundary
contextId="commerce"
onError={onError}
fallback={(incidentId) => <p>incident {incidentId}</p>}
>
<ThrowsOnRender />
</ContextErrorBoundary>,
);
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;