Files
clean-architecture-frontend…/tests/component/context-route-gateway.test.tsx
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

186 lines
6.3 KiB
TypeScript

// @vitest-environment jsdom
import { act, render, screen, waitFor } from "@testing-library/react";
import { 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";
/**
* Three bounded contexts cut from the test-only feature's routes, so canonical
* redirects and access rules stay valid: A owns the list, B the status page,
* and the third one's routes module fails to download.
*/
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 only = (id: string) => async () =>
FIXTURE_CONTEXT_ROUTES.filter((route) => route.id === id);
return {
TEMPLATE_APP_MODULE: {
id: "two-context-app",
budget: { maxContexts: 3 },
contexts: [
{
id: "context-a",
features: [],
route: {
path: "fixture/items/*",
loadRoutes: only("FIXTURE_ITEMS"),
},
},
{
id: "context-b",
features: [],
route: {
path: "fixture/items/status/*",
loadRoutes: only("FIXTURE_ITEM_STATUS"),
},
},
{
id: "context-offline",
features: [],
route: {
path: "fixture/items/new/*",
loadRoutes: async () => {
throw new TypeError(
"Failed to fetch dynamically imported module: /assets/context-routes.js",
);
},
},
},
],
},
};
});
function navigateByHistory(url: string) {
act(() => {
window.history.pushState({}, "", url);
window.dispatchEvent(new PopStateEvent("popstate"));
});
}
function reportedRoutes(record: ReturnType<typeof vi.fn>): string[] {
return record.mock.calls
.map(([event]) => event as { eventId: string; context: { route_id: string } })
.filter((event) => event.eventId === "route.changed")
.map((event) => event.context.route_id);
}
describe("context route gateway", () => {
it("never matches a new context's URL against the previous context's routes", async () => {
const record = vi.fn();
window.history.pushState({}, "", "/fixture/items");
render(
<ApplicationProvider
application={createTestApplication({ diagnostics: { record } })}
>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
);
await waitFor(() =>
expect(reportedRoutes(record)).toContain("FIXTURE_ITEMS"),
);
navigateByHistory("/fixture/items/status");
await waitFor(() =>
expect(reportedRoutes(record)).toContain("FIXTURE_ITEM_STATUS"),
);
expect(reportedRoutes(record)).not.toContain("NOT_FOUND");
});
it("sends a failed routes-module download through chunk recovery", async () => {
const reload = vi.fn();
const release = (buildId: string, releaseId: string) => ({
buildId,
releaseId,
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "hash",
routeChunks: { "route-fixture-item-form": "assets/form.js" },
});
// The reload-once guard only trusts a marker it can read back (Q-6.9-9).
const stored = new Map<string, unknown>();
window.history.pushState({}, "", "/fixture/items/new");
render(
<ApplicationProvider
application={createTestApplication({
preferences: {
read: (name) => ({
ok: true as const,
value: stored.has(name) ? stored.get(name) : "system",
}),
write: (name, value) => {
stored.set(name, value);
return { ok: true as const };
},
remove: (name) => {
stored.delete(name);
return { ok: true as const };
},
},
navigation: { reload },
// A deploy happened: the page runs build-a, the server has build-b.
releaseInfo: {
getCurrent: async () => release("build-a", "release-a"),
refresh: async () => release("build-b", "release-b"),
},
})}
>
<PreferenceProviders>
<AppRouter />
</PreferenceProviders>
</ApplicationProvider>,
);
await waitFor(() => expect(reload).toHaveBeenCalledOnce());
expect(
await screen.findByText("새 버전으로 한 번만 전환합니다."),
).toBeVisible();
});
// 1101/14.3. Without a new deploy the download stays failed. The report
// names the route at the URL, or UNREGISTERED_ROUTE when no route does
// (not NOT_FOUND, whose page did not fail), and telemetry takes it: it
// accepts route ids only, so the context id was dropped there.
it.each([
["/fixture/items/new", "FIXTURE_ITEM_FORM"],
["/fixture/items/new/unknown", "UNREGISTERED_ROUTE"],
])("reports an unrecovered routes-module download at %s as %s", async (url, routeId) => {
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>,
);
await screen.findByText(/^지원 참조: build-a:[0-9a-f]{8}$/);
expect(record).toHaveBeenCalledWith(
expect.objectContaining({
eventId: "ui.render.failed",
context: expect.objectContaining({ route_id: routeId }),
}),
);
const [telemetry] = emit.mock.calls.filter(([name]) => name === "ui.render.failed");
expect(projectTelemetryEvent(telemetry?.[0], telemetry?.[1])).toMatchObject({
success: true,
});
});
});