Files
clean-architecture-frontend…/tests/unit/second-api-feature-registries.test.ts
T
DongHyeonka 3b40f73638 fix(contracts)!: 스키마 메타의 boundary를 쓰임과 대조하고 실패 본문 행을 둔다
문제
<base>-schema-metadata.ts의 boundary는 손으로 적고, check:registries는 값이
목록 안인지만 본다. 응답 스키마에 boundary "api-request"를 적어도 타입·
레지스트리·기능 테스트가 모두 통과한다(리뷰 E-4 세 번째 변이). direction과
unknownFieldPolicy는 07-03 수정(5bee9ab)이 검증기와 대조한다. 또 FE-REG-API의
problemSchema는 breaking 칸이지만 FE-REG-SCHEMA를 참조하지 않고, 참조 기능과
생성 뼈대에 실패 본문 스키마 행이 없다(07-01 (d)).

고른 방법
- schema-metadata-policy.test.ts에 boundary 대조를 더한다. 설치된 descriptor의
  입력·응답·실패 검증기와 라우트 paramsSchema·searchSchema에서 스키마마다
  쓰인 자리를 모으고, 그 조합에서 boundary를 정해 행과 비교한다. 쓰이는데
  행이 없는 스키마도 실패한다. direction·unknownFieldPolicy 검사는 실패
  검증기까지 넓힌다.
- boundary에 "api-problem"을 더한다(SchemaDefinition, governance
  allowedValues). FE-REG-API problemSchema → FE-REG-SCHEMA.schemaId 참조를
  governance에 더한다.
- 참조 기능 ReferenceProblem, 생성 뼈대 <Base>Problem, second-api fixture에
  실패 본문 행을 더한다.

버린 대안
- 메타 행을 descriptor·라우트에서 투영(16-04 권고 (b)): 메타 파일이 거의
  사라지지만 생성 뼈대·참조 기능·레지스트리 원본을 함께 바꾼다. 리뷰가
  "빠르게 막으려면 (c) 먼저"라고 적은 대조 테스트를 골랐다.
- owner를 기능 ID에서 검사: 정한 규칙이 없다(참조 기능 owner는
  "...-vertical-slice"). 그대로 둔다.

위험·한계
- governance 참조 추가는 FE-REG-API 계약 변경이라 기준선을 다시 찍었다
  (REGISTRY_BASELINE_REASON에 1103/16-04). 다른 브랜치 변경(FE-REG-TELEMETRY
  optionalAttributes)도 같은 스냅샷에 들어갔다. 오케스트레이터가 통합 뒤 다시
  찍는다.
- 다운스트림 기능은 실패 본문 행이 없으면 check:registries가 실패한다.
  CHANGELOG에 이행 안내가 필요하다.
- 대조 테스트는 설치된 기능만 본다. 기능을 더한 상태에서 test:unit을 돌릴 때
  잡힌다.

검증
- RED: 새 boundary 테스트가 "ReferenceProblem: no FE-REG-SCHEMA row"로 실패.
  행을 더한 뒤 통과.
- 변이: ReferenceResourcePayload boundary를 api-request로 바꾸면 "row
  api-request, used as api-response"로 실패. 되돌림.
- check:registries 실패(FE-REG-API references 변경) → 기준선 갱신 뒤 PASS
  compatibility=none.
- second-api-feature-registries, registry-governance, release-artifacts,
  create-feature 테스트 통과. check:types, lint, verify:documentation 통과.

BREAKING CHANGE: FE-REG-API problemSchema가 FE-REG-SCHEMA.schemaId를 참조한다.
설치된 기능의 problemValidator 스키마마다 <base>-schema-metadata.ts에
boundary "api-problem", direction "RESPONSE" 행이 없으면 check:registries가
"FE-REG-API.<operationId>.problemSchema references unknown FE-REG-SCHEMA"로
실패한다. 행을 더하고 레지스트리 기준선을 다시 찍는다.
Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-04
Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-01
2026-11-04 23:35:33 +09:00

296 lines
11 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"),
// 1103/16-04. FE-REG-API's problemSchema references a row too.
SecondItemProblem: schema("SecondItemProblem", "api-problem", "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 })));
});
/** A copy of the repository with the second feature written into it. */
async function repositoryWithSecondFeature(featureContract = FEATURE_CONTRACT) {
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`]: featureContract,
[`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);
return root;
}
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 repositoryWithSecondFeature();
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);
it("names the operation and the profile when the auth profile id is wrong (1103/09-07)", async () => {
const root = await repositoryWithSecondFeature(
FEATURE_CONTRACT.replace('authProfileId: "ANONYMOUS"', 'authProfileId: "SECOND_UNKNOWN"'),
);
const checked = spawnSync(
process.execPath,
[path.resolve("scripts/check-registries.ts")],
{ cwd: root, encoding: "utf8" },
);
expect(checked.status).toBe(1);
expect(checked.stderr).toContain(
`${FEATURE_ID}/GET_SECOND_ITEM: unknown authProfileId SECOND_UNKNOWN`,
);
}, 60_000);
});