fix(contexts): 계약에 없는 라우트 핸들을 라우트 적재 때 막는다 (09-06)

문제: context gateway는 적재한 라우트의 handle `routeId`가 가리키는
등록 라우트를 그린다. `context-routes.ts`가 기능 계약에 없는 route id를
handle에 실으면(오타, 계약에서 지운 라우트) 적재는 성공하고, 그 URL을
그릴 때 context 경계 실패 화면이 된다. 7139c7c가 리뷰의 (1)(2)를 했고
(3) "핸들의 route id가 레지스트리에 있는가"는 설계 선택으로 남겼다.

고른 방법: 적재 때 검사한다. `defineBoundedContextModule`이
`route.loadRoutes`를 감싸, 적재한 각 라우트의 handle `routeId`가 그
context 기능들의 계약 라우트 id에 없으면 TypeError로 실패한다. 메시지에
route id, context id, 기능 id를 담는다. handle에 `routeId`가 없어도
실패한다(gateway는 그 라우트를 NOT_FOUND로 그린다).
- 모든 context가 이 함수를 거치므로(생성된 product-context-index) 모든
  context에 걸린다. 모든 context의 라우트를 적재하는 기존 단위 테스트
  (tests/unit/route-runtime.test.ts)가 개발 단계에서 잡는다.
- 적재 실패는 09-09(de48db2)의 "청크 누락이 아닌 적재 실패" 경로로
  context 경계에 가서 `ui.render.failed` 진단을 남긴다. 테스트로 확인했다.
- 라우트는 계속 늦게 읽는다. context를 정의할 때는 loadRoutes를 부르지
  않는다.
- 7139c7c의 `contractRoutePaths`를 bounded-context-module.ts로 옮겨
  앱 모듈과 같이 쓴다. "계약 라우트"의 정의가 한 곳에 남는다.
- starter-experience.md 기능 추가 3단계에 규칙을 적었다.

버린 대안:
- 헬퍼로 제공: 그 헬퍼를 쓰는 context만 지킨다. 안 쓰면 그만이다.
- 생성기에서 검사: 생성기는 정규식으로 리터럴만 읽어 handle을 모른다.

위험·한계:
- 생성된 index는 기능별 라우트를 합쳐서 돌려주므로, 어느 기능의
  `context-routes.ts`가 잘못된 handle을 냈는지는 알 수 없다. 메시지는
  그 context의 기능 id 전부를 적는다. 기능이 하나인 context(지금
  reference)는 정확하다.
- 최상위 라우트만 본다. 지금 context 라우트는 평평하다. children을 쓰는
  context가 생기면 재귀가 필요하다.
- `defineBoundedContextModule`을 거치지 않고 손으로 만든 context 객체는
  검사되지 않는다. 그 경우는 기존처럼 렌더 때 context 경계가 잡는다.
- 등록 라우트가 없는 URL에서 난 적재 실패는 진단 route_id가 NOT_FOUND다.
  레지스트리의 NOT_FOUND splat이 모든 URL에 맞아 gateway의
  `?? routeModule.id` 대체가 쓰이지 않는다. 09-09의 동작이고 고치지 않았다.
- 초기 JS gzip +141 B(203,818 -> 203,959 B, 여유 982 -> 841 B).
  같은 worktree에서 `vite build` 두 번으로 쟀다.

검증:
- RED: tests/architecture/context-route-roots.test.ts 새 3건 중 거절
  2건이 "promise resolved ... instead of rejecting"으로 실패(10건 중 2
  실패). tests/component/context-boundary-diagnostics.test.tsx 새 1건이
  route_id "FIXTURE_ITEMSS"(렌더 때 경계)로 실패.
- GREEN: 두 파일 10건, 4건 통과.
- 회귀: tests/{architecture,unit,features,platform,component,contract,
  runtime-schema,integration,scripts,scale}(pnpm을 띄우는 4개 제외)
  296 files 중 3,383 통과, 1건 실패. 실패는 telemetry-storm.test.ts의
  10초 timeout(부하 34)이고 단독 재실행에서 4건 통과했다.
  check-registries, check-adapter-inventory 통과.
- tsc app·test·node 통과. 바꾼 파일 eslint 통과.
  verify-documentation-readiness PASS_SCOPED.
- check:architecture는 pnpm이 필요해 돌리지 않았다.

Refs: docs/reviews/2026-11-01-maturity-review/09-app-core.md 09-06
This commit is contained in:
DongHyeonka
2026-11-03 00:53:27 +09:00
parent 1196b86426
commit d6e4e51688
5 changed files with 164 additions and 23 deletions
+4 -1
View File
@@ -140,7 +140,10 @@ selected app. Every build and check script runs it first; run it yourself with
`FEATURE_CONTEXT_ROUTES`. Page components are imported lazily here, and each
route handle carries the route's params/search `codecs`; the owning context
loads this file only when its route root is visited
(`src/features/reference-feature/context-routes.ts`).
(`src/features/reference-feature/context-routes.ts`). Each handle's
`routeId` must be a route of a feature contract in the same context; the
context refuses the routes when they load, naming the route, context and
features (`src/contexts/bounded-context-module.ts`).
4. Name the owning context in `FEATURE_CONTEXT_ID`. Use an existing context or
add `src/contexts/<context>/context-module.ts` owned by the app.
Every route path in the feature contract must sit at or under that
+4 -18
View File
@@ -1,6 +1,9 @@
import { matchRoutes } from "react-router-dom";
import type { BoundedContextModule } from "../contexts/bounded-context-module.ts";
import {
contractRoutePaths,
type BoundedContextModule,
} from "../contexts/bounded-context-module.ts";
import { assertWithinCardinalityBudget } from "../platform/cardinality/cardinality-budget.ts";
export type DeployableAppModule<Context extends BoundedContextModule = BoundedContextModule> = Readonly<{
@@ -67,20 +70,3 @@ function assertFeatureRoutesReachOwningContext(
}
}
}
/** The route registry reads `contracts.routes`; a feature may have none. */
function contractRoutePaths(
contracts: object,
): readonly (readonly [string, string])[] {
const routes: unknown = "routes" in contracts ? contracts.routes : undefined;
if (typeof routes !== "object" || routes === null) return [];
return Object.entries(routes).flatMap(
([routeId, definition]: [string, unknown]) =>
typeof definition === "object" &&
definition !== null &&
"path" in definition &&
typeof definition.path === "string"
? [[routeId, definition.path] as const]
: [],
);
}
+63 -1
View File
@@ -36,10 +36,72 @@ export function defineBoundedContextModule<const Feature extends AnyFeatureModul
}
seen.add(feature.id);
}
const route = definition.route;
return Object.freeze({
...definition,
features: Object.freeze([...definition.features]),
budget: Object.freeze({ ...definition.budget }),
...(definition.route ? { route: Object.freeze({ ...definition.route }) } : {}),
...(route
? {
route: Object.freeze({
...route,
loadRoutes: async () =>
assertHandlesNameContractRoutes(
definition.id,
definition.features,
await route.loadRoutes(),
),
}),
}
: {}),
});
}
/**
* 09-06 (3). The gateway renders the registered route a loaded route's handle
* names. A handle that no feature of this context declares in its contract
* would only fail when its URL renders, inside the context boundary; checking
* here fails every context whose routes any test or visit loads. Routes stay
* lazy: this runs when they load, not when the context is defined. Only
* top-level routes are checked; context routes are flat today.
*/
function assertHandlesNameContractRoutes(
contextId: string,
features: readonly AnyFeatureModule[],
routes: readonly RouteObject[],
): readonly RouteObject[] {
const routeIds = new Set(
features.flatMap((feature) =>
contractRoutePaths(feature.contracts).map(([routeId]) => routeId),
),
);
for (const route of routes) {
const handle: unknown = route.handle;
const routeId =
typeof handle === "object" && handle !== null && "routeId" in handle
? handle.routeId
: undefined;
if (typeof routeId === "string" && routeIds.has(routeId)) continue;
throw new TypeError(
`Route handle ${String(routeId)} loaded by context ${contextId} is not a contract route of its features (${features.map((feature) => feature.id).join(", ")}).`,
);
}
return routes;
}
/** The route registry reads `contracts.routes`; a feature may have none. */
export function contractRoutePaths(
contracts: object,
): readonly (readonly [string, string])[] {
const routes: unknown = "routes" in contracts ? contracts.routes : undefined;
if (typeof routes !== "object" || routes === null) return [];
return Object.entries(routes).flatMap(
([routeId, definition]: [string, unknown]) =>
typeof definition === "object" &&
definition !== null &&
"path" in definition &&
typeof definition.path === "string"
? [[routeId, definition.path] as const]
: [],
);
}
+61 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
@@ -136,3 +136,63 @@ describe("feature routes and their context route root", () => {
).toThrow(/DETAIL.*list.*items.*status/);
});
});
/**
* 09-06 (3). The gateway renders the registered route a loaded route's handle
* names. A handle no feature of the context declares in its contract fails
* when the context's routes load, not later when that URL renders.
*/
describe("context route handles and their features' contract routes", () => {
function contextLoading(
features: readonly ReturnType<typeof feature>[],
handles: readonly unknown[],
) {
const loadRoutes = vi.fn(async () =>
handles.map((handle, index) => ({
id: `route-${index}`,
path: `/shop/${index}`,
handle,
})),
);
const module = defineBoundedContextModule({
id: "shop-context",
features,
budget: { maxFeatures: 10 },
route: { path: "shop/*", loadRoutes },
});
return { module, loadRoutes };
}
it("loads routes whose handles name the context's contract routes", async () => {
const { module } = contextLoading(
[
feature("shop-feature", { SHOP_ITEMS: "/shop/items" }),
feature("cart-feature", { CART: "/shop/cart" }),
],
[{ routeId: "SHOP_ITEMS" }, { routeId: "CART" }],
);
await expect(module.route?.loadRoutes()).resolves.toHaveLength(2);
});
it("rejects an unregistered handle at load, naming the feature and route ids", async () => {
// E7: a typo in context-routes.ts used to surface only as a context
// boundary failure when that URL rendered.
const { module, loadRoutes } = contextLoading(
[feature("shop-feature", { SHOP_ITEMS: "/shop/items" })],
[{ routeId: "SHOP_ITEMS" }, { routeId: "SHOP_ITEMSS" }],
);
// Defining the context still does not load its routes.
expect(loadRoutes).not.toHaveBeenCalled();
await expect(module.route?.loadRoutes()).rejects.toThrow(
/SHOP_ITEMSS.*shop-context.*shop-feature/,
);
});
it("rejects a handle without a route id", async () => {
const { module } = contextLoading(
[feature("shop-feature", { SHOP_ITEMS: "/shop/items" })],
[{ runtime: {} }],
);
await expect(module.route?.loadRoutes()).rejects.toThrow(/shop-feature/);
});
});
@@ -21,14 +21,36 @@ vi.mock("../../src/.generated/product-feature-index.ts", async () => ({
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 { 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: 3 },
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",
route: {
@@ -131,4 +153,12 @@ describe("context gateway failure diagnostics", () => {
boundary: "route",
});
});
it("reports an unregistered handle refused while the routes load", async () => {
// No feature route owns this URL; the registry's NOT_FOUND splat does.
await expectReportedFailure("/fixture/checked", {
routeId: "NOT_FOUND",
boundary: "route",
});
});
});