문제: FE-REG-SCHEMA 행의 direction·unknownFieldPolicy는 타입에서 선택 칸이다. tests/unit/schema-metadata-policy.test.ts는 행이 값을 적지 않으면 그 자리를 건너뛰었다(direction의 `declared === undefined`, 정책의 `if (declared === undefined) return []`). 1105/07-02는 RESPONSE 행의 정책이 REJECT_UNKNOWN으로 바뀔 때만 breaking으로 본다. 그래서 손으로 쓴 응답 행이 두 칸을 빼고 들어오면, 뒤에 응답 DTO를 .strict()로 바꿔도 행이 바뀌지 않아 check:registries는 아무것도 보지 않고 정책 테스트도 건너뛴다. 백엔드가 응답에 필드 하나를 더하면 그 API가 SCHEMA_MISMATCH로 실패한다. 고른 방법: 리뷰의 (A). descriptor의 입력·응답·실패 검증기(`slots`)로 쓰인 스키마의 행이 두 칸을 적지 않으면 두 테스트가 실패로 센다. 메시지는 `row states no direction, used as <방향>`과 `row states no unknownFieldPolicy, validator <탐침 결과>`다. 행이 아예 없으면 같은 메시지가 나오고, boundary 테스트도 `no FE-REG-SCHEMA row`로 실패한다. 템플릿 HTTP 행과 생성기가 쓰는 행(create-feature.ts, create-feature- write-slice.ts)은 이미 두 칸을 적어 통과한다. 라우트에만 쓰이는 행 (NotFoundSplat)은 slots에 없어 그대로 두 칸이 없어도 된다. 매뉴얼 01 4단계와 errors.md에 규칙과 메시지를 적었다. 버린 대안: (B) governance가 api-* 경계 행에 두 칸을 필수로 둔다. 경계별 필수 칸 규칙이 governance에 없어 분류기 변경과 기준선 재승인이 필요하다. 타입에서 두 칸을 필수로 만들면 route 전용 행까지 바뀌고, src/contracts export의 모양이 바뀐다. 위험·한계: 다운스트림이 두 칸 없는 HTTP 행을 가졌다면 동기화 뒤 test:unit이 실패한다. 메시지대로 두 칸을 적으면 된다. 고친 곳이 검사(테스트 파일) 자신이라 RED는 테스트 파일만으로 만들 수 없다. 참조 응답 행에서 두 칸을 지운 변이로 확인한다. 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/unit/schema-metadata-policy.test.ts (변이 없이 통과, ReferenceResourcePayload 행의 두 칸을 지운 변이에서 두 테스트 실패) Refs: 1106/07-02
177 lines
6.6 KiB
TypeScript
177 lines
6.6 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.
|
|
*
|
|
* 1106/07-02. Both fields are optional in the row type, and a row that left
|
|
* them out used to be skipped here. 1105/07-02 grades a response row whose
|
|
* policy turns `REJECT_UNKNOWN` as breaking, but a row with no policy does not
|
|
* change when its DTO turns `.strict()`, so nothing saw it. A schema an HTTP
|
|
* operation uses now fails here without them. Route-only rows (`NotFoundSplat`)
|
|
* are not in `slots` and still need neither.
|
|
*/
|
|
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 === direction
|
|
? []
|
|
: [
|
|
`${operationId} ${validator.schemaId}: row ${declared ?? "states no direction"}, 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;
|
|
const probed = probeUnknownFieldPolicy(validator);
|
|
return probed === declared
|
|
? []
|
|
: [
|
|
`${operationId} ${validator.schemaId}: row ${declared ?? "states no unknownFieldPolicy"}, validator ${probed}`,
|
|
];
|
|
});
|
|
|
|
expect(wrong).toEqual([]);
|
|
});
|
|
});
|