Files
clean-architecture-frontend…/tests/component/context-boundary-diagnostics.test.tsx
T
DongHyeonka 7c8cb19e94 fix(routes): 등록 라우트 없는 URL의 적재 실패를 UNREGISTERED_ROUTE로 적는다 (1101/14.3)
문제: context gateway가 라우트 적재 실패를 `ui.render.failed`로 남길 때
`route_id`를 URL에서 고른다. 고르는 곳이 세 군데이고 결과가 서로 다르다.
- 청크 누락이 아닌 실패: `registeredRouteIdAt(...) ?? routeModule.id`.
  레지스트리의 NOT_FOUND splat이 모든 URL에 맞아서 등록 라우트가 없는 URL은
  `NOT_FOUND`가 되고 대체값은 한 번도 쓰이지 않는다. 운영에서는 not-found
  화면이 깨진 것처럼 읽혀 플랫폼 담당에게 간다. 실제로 실패한 것은 context의
  라우트 모듈이다.
- 복구하지 못한 청크 실패: 늘 `routeModule.id`(context id). telemetry는
  `route_id`를 `^[A-Z][A-Z0-9_]{0,63}$`로만 받는다. 그래서 이 이벤트는
  `invalid-attribute-value`로 버려진다(`projectTelemetryEvent`로 확인).
- 레이아웃 청크 실패: `?? "NOT_FOUND"`. 레이아웃 아래 context는 등록 경로에만
  붙어서 지금은 닿지 않는 값이다.

이 진단이 구분해야 하는 것은 둘이다. 어느 화면(그래서 어느 기능)이 실패했나,
그리고 not-found 화면 자체가 실패했나. 그 값은 telemetry까지 가야 한다.

고른 방법: 세 곳이 `failedRouteIdAt(pathname)` 하나를 쓴다. URL의 등록
라우트 id를 쓰고, 등록 라우트가 없으면(NOT_FOUND만 맞으면) 명시값
`UNREGISTERED_ROUTE`(`UNREGISTERED_ROUTE_ID`, src/contracts/routes.ts)를
쓴다. 등록 URL의 청크 실패는 context id 대신 그 라우트 id가 된다. 라우트
id로 소유 기능과 context를 찾을 수 있다. 청크 복구의 chunkId 선택은 바꾸지
않았다.

버린 대안:
- context id(`routeModule.id`, 원래 의도한 대체값): 실패한 모듈을 정확히
  가리키지만 telemetry가 버린다. 받게 하려면 `route_id` 문법을 소문자
  kebab까지 넓혀야 한다. 그러면 `api.request.failed` 등 모든 이벤트의
  `route_id` 검사가 약해진다.
- context id를 대문자 snake로 바꿔 쓰기: 숨은 이름 규칙이 생기고 실제 라우트
  id와 섞인다.
- `context_id` 속성 추가: 진단·telemetry 허용 목록과 레지스트리 기준선을
  바꿔야 한다. 기준선 재승인은 이 작업 범위가 아니다.

위험·한계:
- 등록 라우트가 없는 URL의 실패는 어느 context인지 진단에 남지 않는다. 같은
  결함은 그 context의 등록 URL에서도 나므로 그 보고로 찾는다.
- [계약] `ui.render.failed`의 `route_id`에 `UNREGISTERED_ROUTE` 값이 생긴다.
  복구하지 못한 context 라우트 청크 실패는 context id 대신 라우트 id를 적는다.
  `route_id` 이름과 허용 문법은 그대로다.
- 기능이 `UNREGISTERED_ROUTE`라는 route id를 선언하면 구분되지 않는다. 막지
  않았다.

검증:
- RED: context-boundary-diagnostics "unregistered handle" 1건이
  `"route_id": "NOT_FOUND"`로 실패. context-route-gateway 새 2건이
  `"route_id": "context-offline"`로 실패(8건 중 3 실패).
- GREEN: 두 파일과 context-layouts 14건 통과. 각 보고는 telemetry 투영
  (`projectTelemetryEvent`)도 통과한다.
- 회귀: tests/{architecture,unit,features,platform,component,contract,
  runtime-schema,integration,scripts,scale}(pnpm을 띄우는 3개 제외) 306
  files, 3,572건 통과.
- tsc app·test 통과. 바꾼 파일 eslint 통과. check-registries,
  check-diagnostics 통과. verify-documentation-readiness PASS_SCOPED.
2026-11-03 20:30:35 +09:00

174 lines
5.9 KiB
TypeScript

// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { projectTelemetryEvent } from "../../src/contracts/telemetry.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";
/**
* 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, FIXTURE_FEATURE_MODULE } = await import(
"../helpers/fixture-feature.tsx"
);
const { defineBoundedContextModule } = await import(
"../../src/contexts/bounded-context-module.ts"
);
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: 4 },
contexts: [
// 09-06 (3). A context defined the regular way refuses the same typo
// when its routes load, before anything renders.
defineBoundedContextModule({
id: "context-checked-typo",
features: [FIXTURE_FEATURE_MODULE],
budget: { maxFeatures: 1 },
route: {
path: "fixture/checked/*",
loadRoutes: async () => [
{
id: "FIXTURE_ITEMSS",
path: "/fixture/checked",
handle: { routeId: "FIXTURE_ITEMSS", runtime },
},
],
},
}),
{
id: "context-without-codecs",
features: [],
route: {
path: "fixture/items/*",
loadRoutes: async () => [
{
id: "FIXTURE_ITEMS",
path: "/fixture/items",
handle: { routeId: "FIXTURE_ITEMS", runtime },
},
],
},
},
{
id: "context-with-typo",
features: [],
route: {
path: "fixture/items/status/*",
loadRoutes: async () => [
{
id: "FIXTURE_ITEM_STATUSS",
path: "/fixture/items/status",
handle: { routeId: "FIXTURE_ITEM_STATUSS", runtime },
},
],
},
},
{
id: "context-broken",
features: [],
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();
const emit = vi.fn();
window.history.pushState({}, "", url);
render(
<ApplicationProvider
application={createTestApplication({ diagnostics: { record }, telemetry: { emit } })}
>
<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,
},
},
]);
// The same failure reaches telemetry, which takes route ids only.
const [telemetry] = emit.mock.calls.filter(([name]) => name === "ui.render.failed");
expect(projectTelemetryEvent(telemetry?.[0], telemetry?.[1])).toMatchObject({ success: true });
}
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",
});
});
it("reports an unregistered handle refused while the routes load", async () => {
// 1101/14.3. No registered route names this URL. The context failed, not
// the not-found page, so the report must not say NOT_FOUND.
await expectReportedFailure("/fixture/checked", {
routeId: "UNREGISTERED_ROUTE",
boundary: "route",
});
});
});