Files
clean-architecture-frontend…/tests/unit/second-api-feature-registries.test.ts
T
DongHyeonka 12f3bb7862 refactor(contracts)!: V2 API 행을 지우고 FE-REG-API를 HTTP descriptor에서 뽑는다
문제
기능 하나가 같은 HTTP API를 두 번 적는다. *-api-contract.ts의 V2 행
(defineRestOperation)은 check:registries(FE-REG-API)가 검사하는 선언이고,
contract contribution의 V3 descriptor가 실제로 실행된다. 둘이 어긋나지 않게
http-operation-v2-v3-parity 테스트를 따로 둔다. 048f490으로 V2 클라이언트가
없어져 V2 행을 읽는 실행 코드는 없고, 검사만 남은 두 번째 사본이다. V2 행을
위한 기능별 runtimeSchemas·mappers 레지스트리와 V2 보안 프로필 해석
(resolveRestSecurityProfiles)도 같이 남아 있다. 사용자 지시: 최신 경로 하나만
남기고, 레지스트리 기준선 재승인을 승인했다.

고른 방법
- src/contracts/api-operations.ts를 projectApiOperationRows 하나로 바꿨다.
  조립된 contribution의 descriptor마다 operationId, featureId, method, path,
  authProfileId, retrySemantics, requestBody, responseBody, responseEnvelope,
  request/response/problemSchema(검증기 schemaId) 행을 만든다. FE-REG-API는
  같은 export(API_OPERATIONS)를 읽고, governance 정의를 이 필드로 바꿨다.
  requestSchema·responseSchema는 그대로 FE-REG-SCHEMA를 참조한다.
- FeatureRuntime은 apiContract 대신 schemas(FE-REG-SCHEMA 행)만 받는다.
  installed-feature-runtime-registries는 schemas로 스키마 레지스트리를 만들고
  FE-REG-API 행을 descriptor에서 뽑는다. RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
  REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID를 지웠다.
- realtime snapshot 바인딩은 ApiOperationRow를 받고 method GET과
  retrySemantics SAFE·IDEMPOTENT를 본다(V2의 contractVersion·semantics·
  replayPolicy 대신).
- rest-profiles.ts에서 V2 행용 provider·CSRF 프로필 해석을 지웠다. V3는 조립
  때 auth profile을 검사하고 자격증명 헤더를 프로필로 거른다.
- 참조 기능: reference-api-contract.ts를 reference-schema-metadata.ts로
  바꾸고(스키마 행만), V2 runtime codec·operation mapper·레지스트리 mapper를
  지웠다. V3 descriptor가 쓰지 않는 NoRequest 스키마 행도 지웠다.
- create:feature: <base>-api-contract.ts 대신 <base>-schema-metadata.ts를
  만든다. codec·mapper 레지스트리 행과 그 테스트를 만들지 않는다.
- 레지스트리 기준선을 update:registry-baseline으로 다시 만들고 승인했다
  (digest 16f72742…, 승인자 DongHyeonka, 이유에 사용자 승인을 적음).
- 매뉴얼 01·02·reference, starter-experience, 계약 문서의 V2 설명을 지웠다.

버린 대안
- V2 행을 남기고 V3에서 생성하기: 생성 단계와 생성물이 하나 더 생긴다. 행은
  실행되지 않으므로 메모리에서 뽑아 검사하면 충분하다.
- 스키마 메타데이터(FE-REG-SCHEMA 행)도 검증기에서 뽑기: boundary·
  unknownFieldPolicy·owner는 검증기에 없고, 라우트 스키마도 같은 레지스트리를
  쓴다. 이 행은 V2가 아니라 스키마 레지스트리라 남겼다.

위험·한계
- BREAKING: FeatureRuntime 모양, contracts·rest-profiles·loaded-feature-runtimes
  의 이름이 바뀌거나 없어졌다. memento-frontend의 memento-web이 V2 행을 쓴다.
  옮기는 법은 CHANGELOG에 적는다.
- V2 보안 프로필 일관성 검사(auth "none"과 ANONYMOUS, 쿠키 프로필의 CSRF
  모드)가 사라졌다. V3 descriptor에는 그 칸이 없다.
- BoundedPollOperationContract(realtime polling recipe)는 contractVersion: 2
  필드를 갖지만 자체 계약이라 바꾸지 않았다.

검증
- check:types, lint, check:architecture, check:registries(11 registries PASS,
  compatibility=none), check:ci, check:diagnostics, check:adapter-inventory,
  verify:documentation 통과.
- test:unit 2,566(새 tests/unit/api-operation-rows.test.ts 3건 포함),
  test:integration 114, test:component 245, test:contract 23,
  test:runtime-schema 56, tests/features 99 통과.
- tests/unit/second-api-feature-registries.test.ts: V3 descriptor만 가진 두
  번째 기능을 복사본에 넣으면 기준선을 고치지 않고 check:registries가 통과한다.
- check:bundle 통과. 초기 JS 201,598 → 200,911 B.
- test:feature-scaffold 16개, test:sample-removal 23개 검사 통과.

BREAKING CHANGE: FeatureRuntime이 apiContract 대신 schemas를 받는다.
defineRestOperation, ApiOperation, RestOperationV2, composeApiOperations,
validateApiRuntimeBindings, getApiOperation, contracts의 API_OPERATIONS,
createRestProviderProfile, RestProviderProfile, resolveRestSecurityProfiles,
validateRestProfileBindings, REST_CSRF_PROFILES, RestCsrfProfile,
loaded-feature-runtimes의 RUNTIME_SCHEMA_CODECS, MAPPER_REGISTRY,
REST_PROFILE_BINDINGS_VALID, API_RUNTIME_BINDINGS_VALID가 없어졌다. 기능은
operation을 contract contribution에만 적고, schemas 행을 feature-runtime에
넘긴다.
2026-11-03 21:37:48 +09:00

271 lines
10 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { linkFixtureNodeModules } from "../../scripts/lib/fixture-node-modules.ts";
/**
* F-3 (09-07). Adding a feature that owns an API operation must not require
* edits outside its own directory: governance, composers and the registry
* baseline stay as they are. This writes one such feature (plus the bounded
* context it declares, so the check survives the sample's removal) into a copy
* of the repository and runs the production generator and `check-registries`.
* 0929/07-03. The feature also owns a route with its own search schema and its
* own loading surface name, the values FE-REG-ROUTE once kept in a central
* allowlist.
* 1101/16-01. And an invalidation topic, namespace and edge: every feature
* with server state has them, and adding them is additive.
*/
const FEATURE_ID = "second-api-feature";
const CONTEXT_ID = "second-api-context";
const TOPIC_ID = "qinv.01kb3m8q2v6t4r9s1n5p7c0w";
const FEATURE_CONTRACT = `import {
PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,
PLACEHOLDER_CONTRACT_PACKAGE_REVISION,
PLACEHOLDER_CONTRACT_PACKAGE_VERSION,
} from "../../../contracts/deployment-admission.ts";
import type {
InstalledContractContribution,
InstalledHttpContract,
} from "../../../contracts/external-contract-runtime.ts";
import { unvalidatedPayload } from "../../../contracts/unvalidated-payload.ts";
import { defineQueryInvalidationTopic } from "../../../contracts/query-invalidation.ts";
import { defineQueryNamespaceIdentity } from "../../../contracts/query-keys.ts";
const OWNER = "feature-frontend-second-api-feature";
const SECOND_ITEM_TOPIC = defineQueryInvalidationTopic("${TOPIC_ID}");
const SECOND_ITEM_NAMESPACE = defineQueryNamespaceIdentity("second-item", 1);
const schema = (schemaId: string, boundary: string, direction: string) =>
Object.freeze({ schemaId, boundary, owner: OWNER, runtime: "zod", schemaVersion: 1, direction });
const unchecked = (schemaId: string) =>
unvalidatedPayload(schemaId, "registry fixture: only check-registries reads it");
const SECOND_CONTRACT_PACKAGE = Object.freeze({
packageId: "@org-contracts/second-api",
version: PLACEHOLDER_CONTRACT_PACKAGE_VERSION,
digest: PLACEHOLDER_CONTRACT_PACKAGE_DIGEST,
runtimeProtocolVersion: 1 as const,
sourceRevision: PLACEHOLDER_CONTRACT_PACKAGE_REVISION,
});
const ROUTES = Object.freeze({
SECOND_ITEM_LIST: Object.freeze({
routeId: "SECOND_ITEM_LIST",
path: "/second-api/items",
paramsSchema: null,
searchSchema: "SecondItemListQuery",
access: "public",
loadingSurface: "second-item-list",
errorSurface: "feature-boundary",
chunkId: "route-second-item-list",
title: "Second items",
navigationLabel: null,
navigationOrder: null,
}),
});
// 15-01. Declaration half: what the shell reads at boot.
export const SECOND_API_CONTRACT = Object.freeze({
featureId: "${FEATURE_ID}",
routes: ROUTES,
routeRuntimeContracts: Object.freeze({
SECOND_ITEM_LIST: Object.freeze({
routeId: "SECOND_ITEM_LIST",
moduleId: "second-item-list-page",
paramsCodec: "none",
searchCodec: "SecondItemListQuery",
}),
}),
invalidation: Object.freeze({
topics: Object.freeze([SECOND_ITEM_TOPIC]),
namespaces: Object.freeze([SECOND_ITEM_NAMESPACE]),
edges: Object.freeze([
Object.freeze({ topicId: SECOND_ITEM_TOPIC, namespace: SECOND_ITEM_NAMESPACE }),
]),
}),
topicVersions: Object.freeze([
Object.freeze({ topicId: SECOND_ITEM_TOPIC, topicVersion: 1 }),
]),
contractPackages: Object.freeze([SECOND_CONTRACT_PACKAGE]),
} as const);
// Runtime half, loaded with feature-runtime.ts.
export const SECOND_API_SCHEMAS = Object.freeze({
SecondItemListQuery: schema("SecondItemListQuery", "route-search", "REQUEST"),
SecondItemParams: schema("SecondItemParams", "api-request", "REQUEST"),
SecondItemPayload: schema("SecondItemPayload", "api-response", "RESPONSE"),
} as const);
export const SECOND_API_CONTRIBUTION: InstalledContractContribution = Object.freeze({
contributionId: "second-api-feature-http-v1",
featureId: "${FEATURE_ID}",
source: Object.freeze({ kind: "EXTERNAL_PACKAGE" as const, package: SECOND_CONTRACT_PACKAGE }),
http: Object.freeze([
Object.freeze({
contract: Object.freeze({
operationId: "GET_SECOND_ITEM",
method: "GET" as const,
pathTemplate: "/api/second-items/{itemId}",
inputValidator: unchecked("SecondItemParams"),
outputValidator: unchecked("SecondItemPayload"),
problemValidator: unchecked("SecondItemProblem"),
acceptedStatuses: Object.freeze([200]),
emptyBodyStatuses: Object.freeze([]),
retrySemantics: "SAFE" as const,
requestBody: "NONE" as const,
responseBody: "REQUIRED_JSON" as const,
responseEnvelope: "ENVELOPE_V1" as const,
commandRecovery: null,
commandEffect: null,
projectRequest: (input: unknown) =>
Object.freeze({
pathValues: Object.freeze({ itemId: String((input as { itemId: string }).itemId) }),
queryEntries: Object.freeze([]),
body: null,
}),
}),
frontend: Object.freeze({
policyId: "SECOND_ITEM_V1",
requestByteLimit: 0,
responseByteLimit: 16_384,
totalDeadlineMs: 10_000,
retryBudget: 0 as const,
authProfileId: "ANONYMOUS",
diagnosticsOperation: "second.item",
}),
}),
]) as readonly InstalledHttpContract<unknown, unknown, unknown>[],
events: Object.freeze([]),
});
`;
const FEATURE_MODULE = `import { defineFeatureModule } from "../feature-module.ts";
import { SECOND_API_CONTRACT } from "./contracts/second-api-contract.ts";
export const FEATURE_MODULE_ID = "${FEATURE_ID}";
export const FEATURE_CONTEXT_ID = "${CONTEXT_ID}";
export const FEATURE_MODULE = defineFeatureModule({
id: FEATURE_MODULE_ID,
contracts: SECOND_API_CONTRACT,
routes: SECOND_API_CONTRACT.routes,
messages: {},
loadRuntime: async () => (await import("./feature-runtime.ts")).FEATURE_RUNTIME,
} as const);
`;
const FEATURE_RUNTIME = `import { defineFeatureRuntime } from "../feature-module.ts";
import {
SECOND_API_CONTRIBUTION,
SECOND_API_SCHEMAS,
} from "./contracts/second-api-contract.ts";
export const FEATURE_RUNTIME = defineFeatureRuntime({
featureId: "${FEATURE_ID}",
schemas: SECOND_API_SCHEMAS,
adapters: [],
contractContributions: [SECOND_API_CONTRIBUTION],
} as const);
`;
const FEATURE_GATEWAY = `// The executable consumer of GET_SECOND_ITEM.
export const SECOND_ITEM_OPERATION = "GET_SECOND_ITEM";
`;
const CONTEXT_ROUTES = `import type { RouteObject } from "react-router-dom";
export const FEATURE_CONTEXT_ROUTES: readonly RouteObject[] = Object.freeze([]);
`;
const CONTEXT_MODULE = `export const CONTEXT_MODULE_ID = "${CONTEXT_ID}";
export const CONTEXT_APP_ID = "template-app";
export const CONTEXT_ROUTE_PATH = "second-api/*";
export const CONTEXT_MAX_FEATURES = 1;
`;
const roots: string[] = [];
afterAll(async () => {
await Promise.all(roots.map((root) => rm(root, { recursive: true, force: true })));
});
describe("adding a feature with an API operation, a route and an invalidation topic (F-3, 09-07, 0929/07-03, 1101/16-01)", () => {
it("passes check-registries without edits outside the feature and its context", async () => {
const root = await mkdtemp(path.join(tmpdir(), "second-api-feature-"));
roots.push(root);
// scripts/check-diagnostics.ts is a FE-REG-TELEMETRY consumer path.
for (const entry of [
"src",
"config/contracts",
"schemas/artifacts",
"scripts/check-diagnostics.ts",
]) {
await cp(path.resolve(entry), path.join(root, entry), { recursive: true });
}
await linkFixtureNodeModules(root);
const files: Readonly<Record<string, string>> = {
[`src/contexts/${CONTEXT_ID}/context-module.ts`]: CONTEXT_MODULE,
[`src/features/${FEATURE_ID}/feature-module.ts`]: FEATURE_MODULE,
[`src/features/${FEATURE_ID}/feature-runtime.ts`]: FEATURE_RUNTIME,
[`src/features/${FEATURE_ID}/context-routes.ts`]: CONTEXT_ROUTES,
[`src/features/${FEATURE_ID}/contracts/second-api-contract.ts`]: FEATURE_CONTRACT,
[`src/features/${FEATURE_ID}/adapters/second-api-gateway.ts`]: FEATURE_GATEWAY,
};
for (const [file, content] of Object.entries(files)) {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), content);
}
const generated = spawnSync(
process.execPath,
[path.resolve("scripts/generate-product-feature-index.ts"), `--root=${root}`],
{ encoding: "utf8" },
);
expect(generated.stderr).toBe("");
expect(generated.status).toBe(0);
const checked = spawnSync(
process.execPath,
[path.resolve("scripts/check-registries.ts")],
{ cwd: root, encoding: "utf8" },
);
expect(checked.stderr).toBe("");
expect(checked.stdout).toMatch(/11 registries PASS/u);
expect(checked.status).toBe(0);
const report = JSON.parse(
await readFile(path.join(root, "artifacts/quality/registries.json"), "utf8"),
) as {
registries: { registryId: string; rows: Record<string, unknown> }[];
compatibility: { changes: { registryId: string; field: string; impact: string }[] };
};
const api = report.registries.find(({ registryId }) => registryId === "FE-REG-API");
expect(Object.keys(api?.rows ?? {})).toContain("GET_SECOND_ITEM");
const routes = report.registries.find(({ registryId }) => registryId === "FE-REG-ROUTE");
expect(routes?.rows.SECOND_ITEM_LIST).toMatchObject({
searchSchema: "SecondItemListQuery",
loadingSurface: "second-item-list",
});
const graph = report.registries.find(
({ registryId }) => registryId === "FE-REG-QUERY-INVALIDATION",
);
expect(graph?.rows["invalidation-graph"]).toMatchObject({
topics: expect.arrayContaining([TOPIC_ID]),
});
expect(
report.compatibility.changes
.filter(({ registryId }) => registryId === "FE-REG-QUERY-INVALIDATION")
.map(({ field, impact }) => [field, impact]),
).toEqual([
["edges", "additive"],
["namespaces", "additive"],
["topics", "additive"],
]);
}, 60_000);
});