Files
clean-architecture-frontend…/tests/unit/schema-metadata-policy.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

167 lines
6.2 KiB
TypeScript

import { describe, expect, it } from "vitest";
import type { RuntimeValidator } from "../../src/contracts/external-contract-runtime.ts";
import type { SchemaDefinition } from "../../src/contracts/schema-registry.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
import {
COMPOSED_CONTRACT_CONTRIBUTIONS,
SCHEMA_REGISTRY,
} from "../../src/features/loaded-feature-runtimes.ts";
/**
* 1103/07-03. FE-REG-SCHEMA rows state each HTTP schema's direction and
* unknown-field policy, and `docs/contracts/compatibility.md` builds the
* "adding a response field is additive" rule on `STRIP_UNKNOWN`. Nothing at
* run time reads those two fields, so they are checked here against the
* validators the installed HTTP descriptors run.
*
* The probe is an object with one key no schema declares, and the same object
* as the only item of an array, so it reaches the first object level of an
* object or list payload. A validator that rejects it with
* `unrecognized_keys` rejects unknown fields; one that reaches the object
* without that issue tolerates them. A nested object below that level is not
* probed.
*/
const PROBE_KEY = "__unknownFieldProbe";
type ProbedPolicy = "REJECT_UNKNOWN" | "STRIP_UNKNOWN" | "UNREACHED";
function probeUnknownFieldPolicy(validator: RuntimeValidator<unknown>): ProbedPolicy {
const probe = { [PROBE_KEY]: true };
for (const [value, objectPath] of [
[probe, []],
[[probe], [0]],
] as const) {
const result = validator.safeParse(value);
if (result.success) return "STRIP_UNKNOWN";
const atObject = (path: readonly (string | number)[]) =>
JSON.stringify(path) === JSON.stringify(objectPath);
if (
result.issues.some(
(issue) => issue.code === "unrecognized_keys" && atObject(issue.path),
)
) {
return "REJECT_UNKNOWN";
}
// Every issue sits at or above the probed object (wrong type, wrong
// shape): the validator never looked inside it, so try the next probe.
const unreached = result.issues.every(
(issue) =>
issue.path.length <= objectPath.length &&
issue.path.every((segment, index) => segment === objectPath[index]),
);
if (!unreached) return "STRIP_UNKNOWN";
}
return "UNREACHED";
}
const slots = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.flatMap(
({ http }) =>
http.flatMap(({ contract }) => [
{
operationId: contract.operationId,
direction: "REQUEST" as const,
validator: contract.inputValidator,
},
{
operationId: contract.operationId,
direction: "RESPONSE" as const,
validator: contract.outputValidator,
},
// 1103/16-04. The failure body is read as a response too.
{
operationId: contract.operationId,
direction: "RESPONSE" as const,
validator: contract.problemValidator,
},
]),
);
type Boundary = SchemaDefinition["boundary"];
/**
* 1103/16-04. Where each installed schema is used: an HTTP input, output or
* failure body, or a route's params or search. The row's `boundary` is
* derived from that set; a schema used in two places that no one boundary
* names (an output that is also an input) has no right answer and is listed.
*/
function usesBySchema(): ReadonlyMap<string, ReadonlySet<string>> {
const uses = new Map<string, Set<string>>();
const add = (schemaId: string | null, use: string) => {
if (schemaId === null) return;
const set = uses.get(schemaId) ?? new Set<string>();
set.add(use);
uses.set(schemaId, set);
};
for (const { http } of COMPOSED_CONTRACT_CONTRIBUTIONS.contributions) {
for (const { contract } of http) {
add(contract.inputValidator.schemaId, "http-input");
add(contract.outputValidator.schemaId, "http-output");
add(contract.problemValidator.schemaId, "http-problem");
}
}
for (const route of Object.values(ROUTE_REGISTRY)) {
add(route.paramsSchema, "route-params");
add(route.searchSchema, "route-search");
}
return uses;
}
function boundaryFor(uses: ReadonlySet<string>): Boundary | undefined {
const key = [...uses].sort().join("+");
const boundaries: Readonly<Record<string, Boundary>> = {
"http-input": "api-request",
"http-output": "api-response",
"http-problem": "api-problem",
"route-params": "route-params",
"http-input+route-params": "route-params",
"route-search": "route-search",
"http-input+route-search": "route-search-api-request",
};
return boundaries[key];
}
// With no installed feature (after the sample is removed) there is nothing to
// probe, and both cases pass empty.
describe("FE-REG-SCHEMA policy of the installed HTTP schemas (1103/07-03)", () => {
it("declares the direction each schema is used in", () => {
const wrong = slots.flatMap(({ operationId, direction, validator }) => {
const declared = SCHEMA_REGISTRY[validator.schemaId]?.direction;
return declared === undefined || declared === direction
? []
: [`${operationId} ${validator.schemaId}: row ${declared}, used as ${direction}`];
});
expect(wrong).toEqual([]);
});
it("gives every schema an operation or route uses a row at the boundary it is used", () => {
const wrong = [...usesBySchema()].flatMap(([schemaId, uses]) => {
const row = SCHEMA_REGISTRY[schemaId];
const expected = boundaryFor(uses);
if (row === undefined) return [`${schemaId}: no FE-REG-SCHEMA row`];
if (expected === undefined) {
return [`${schemaId}: used as ${[...uses].sort().join(" and ")}, which no boundary names`];
}
return row.boundary === expected
? []
: [`${schemaId}: row ${row.boundary}, used as ${expected}`];
});
expect(wrong).toEqual([]);
});
it("declares the unknown-field policy its validator applies", () => {
const wrong = slots.flatMap(({ operationId, validator }) => {
const declared = SCHEMA_REGISTRY[validator.schemaId]?.unknownFieldPolicy;
if (declared === undefined) return [];
const probed = probeUnknownFieldPolicy(validator);
return probed === declared
? []
: [`${operationId} ${validator.schemaId}: row ${declared}, validator ${probed}`];
});
expect(wrong).toEqual([]);
});
});