Files
clean-architecture-frontend…/tests/unit/api-operation-rows.test.ts
DongHyeonka 3f7e10c91a fix(contracts): 한 계약 기여 안에서 응답 모양이 다른 operation을 거절한다
문제
responseEnvelope는 operation마다 적는 선택 칸이다. 생성 뼈대에 operation을
손으로 더하면서 이 줄을 빠뜨려도 check:types, check:registries, 라우터를
거치는 페이지 테스트가 모두 통과한다. MSW 시나리오 핸들러가 descriptor의
선언대로 답하기 때문이다. 짝 백엔드에 붙이면 그 화면만 SCHEMA_MISMATCH로
깨진다(리뷰 E-1).

고른 방법
계약 조립이 기여 하나 안의 operation이 같은 응답 모양을 읽는지 본다. 값이
없는 것과 "NONE"은 같은 모양이다. 기여 하나는 백엔드 하나의 패키지라서
그 안의 operation은 한 모양이다. 두 백엔드를 쓰는 기능은 기여를 나눈다.
거절 reason은 두 operation과 고칠 방법을 말한다. 앱을 조립하는 모든 테스트와
check:registries가 실패한다.

버린 대안
- responseEnvelope를 필수 칸으로: tsc가 잡는 가장 강한 통제지만 descriptor
  약 25곳(참조, tests, 다운스트림 손 descriptor, 계약 패키지)을 깨는 공개 타입
  변경이다. 같은 실수(일부만 빠뜨림)를 이 규칙이 잡으므로 작은 쪽을 골랐다.
- 기여 단위 기본값: "기본값이 어디서 오나"라는 규칙이 하나 는다.

위험·한계
- 기여 안의 operation 모두에서 줄을 빼면 잡지 못한다. 생성된 gateway 테스트
  (백엔드 본문을 손으로 적음)만 잡는다. 매뉴얼에 적었다.
- 한 기여에 두 모양을 섞던 다운스트림 기여는 조립이 거부한다. 레포 안에서는
  테스트 fixture 하나(api-operation-rows)가 그랬고 고쳤다.

검증
- RED: 새 테스트 3건 중 섞인 기여 거절 1건 실패. GREEN 뒤 통과.
- tests/unit·integration·contract·component·features·runtime-schema·platform·
  architecture 297파일 3,718건: 섞인 fixture 1건만 실패 → 고친 뒤 통과.
- check:types, lint 통과.

Refs: docs/reviews/2026-11-03-maturity-review/16-structure-patterns.md 16-01
2026-11-04 22:56:52 +09:00

308 lines
9.4 KiB
TypeScript

import { readFile } from "node:fs/promises";
import { describe, expect, it } from "vitest";
import {
canonicalizeRegistryValue,
diffRegistrySnapshots,
} from "../../scripts/lib/registry-compatibility.ts";
import { projectApiOperationRows } from "../../src/contracts/api-operations.ts";
import { composeContractContributions } from "../../src/contracts/external-contract-runtime.ts";
import { unvalidatedPayload } from "../../src/contracts/unvalidated-payload.ts";
import {
API_OPERATIONS,
COMPOSED_CONTRACT_CONTRIBUTIONS,
} from "../../src/features/loaded-feature-runtimes.ts";
import {
TEST_CLASSIFIED_CREATE_HTTP_CONTRACT,
TEST_CONTRACT_CONTRIBUTION,
TEST_CREATE_HTTP_CONTRACT,
TEST_LIST_HTTP_CONTRACT,
} from "../helpers/external-contract-fixture.ts";
/**
* FE-REG-API rows are projected from the installed HTTP descriptors, so an
* operation is written once and the governed row cannot disagree with what
* executes.
*/
describe("FE-REG-API rows projected from HTTP descriptors", () => {
it("projects each descriptor with its feature, wire and schema identities", () => {
const rows = projectApiOperationRows(
composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).contributions,
);
expect(Object.keys(rows)).toEqual([
"TEST_LIST_ENTITIES",
"TEST_GET_ENTITY",
"TEST_CREATE_ENTITY",
]);
expect(rows.TEST_LIST_ENTITIES).toEqual({
operationId: "TEST_LIST_ENTITIES",
featureId: "test-feature",
method: "GET",
path: "/api/test-entities",
authProfileId: "ANONYMOUS",
retrySemantics: "SAFE",
requestBody: "NONE",
responseBody: "REQUIRED_JSON",
responseEnvelope: "NONE",
requestSchema: "TestEntityListQuery",
responseSchema: "TestEntityListPayload",
problemSchema: "TestProblem",
acceptedStatuses: [200],
emptyBodyStatuses: [],
unvalidated: [],
requestByteLimit: 0,
responseByteLimit: 32_768,
totalDeadlineMs: 10_000,
retryBudget: 2,
traffic: null,
commandEffect: null,
commandRecovery: null,
});
expect(rows.TEST_CREATE_ENTITY).toMatchObject({
method: "POST",
retrySemantics: "KEYED",
requestBody: "JSON",
acceptedStatuses: [201],
retryBudget: 0,
commandEffect: { classifiesStatus: false },
commandRecovery: {
mode: "IDEMPOTENCY_REPLAY",
operationIdentityField: "idempotencyKey",
},
});
expect(rows.TEST_CREATE_ENTITY?.commandEffect).not.toHaveProperty(
"refusedBeforeWrite",
);
});
it("carries the command effect data and the validator slots that skip validation", () => {
const traffic = Object.freeze({
maxPhysicalRequests: 2,
maxRetries: 1,
maxConcurrentRequests: 1,
maxQueuedRequests: 0,
});
const rows = projectApiOperationRows(
composeContractContributions([
{
...TEST_CONTRACT_CONTRIBUTION,
http: [
{
...TEST_LIST_HTTP_CONTRACT,
contract: {
...TEST_LIST_HTTP_CONTRACT.contract,
// 1103/16-01. One contribution reads one frame.
responseEnvelope: "ENVELOPE_V1" as const,
outputValidator: unvalidatedPayload(
"TestEntityListPayload",
"typed by the package",
),
},
frontend: { ...TEST_LIST_HTTP_CONTRACT.frontend, traffic },
},
{
...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT,
contract: {
...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract,
// A descriptor that names the codes refused before any write.
// Only an Envelope operation may name them.
responseEnvelope: "ENVELOPE_V1" as const,
commandEffect: {
...TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract.commandEffect,
refusedBeforeWrite: ["TEST_ENTITY_INVALID", "TEST_ENTITY_ALREADY_EXISTS"],
},
},
},
] as never,
},
]).contributions,
);
expect(rows.TEST_LIST_ENTITIES).toMatchObject({
unvalidated: ["output"],
traffic,
});
expect(rows.TEST_CREATE_ENTITY?.commandEffect).toEqual({
classifiesStatus: true,
refusedBeforeWrite: ["TEST_ENTITY_INVALID", "TEST_ENTITY_ALREADY_EXISTS"],
});
});
it("carries an Envelope declaration", () => {
const rows = projectApiOperationRows(
composeContractContributions([
{
...TEST_CONTRACT_CONTRIBUTION,
http: [
{
...TEST_LIST_HTTP_CONTRACT,
contract: {
...TEST_LIST_HTTP_CONTRACT.contract,
responseEnvelope: "ENVELOPE_V1" as const,
},
},
] as never,
},
]).contributions,
);
expect(rows.TEST_LIST_ENTITIES?.responseEnvelope).toBe("ENVELOPE_V1");
});
it("is what the registry governance reads for the installed features", () => {
expect(API_OPERATIONS).toEqual(
projectApiOperationRows(COMPOSED_CONTRACT_CONTRIBUTIONS.contributions),
);
expect(Object.keys(API_OPERATIONS).sort()).toEqual(
[...COMPOSED_CONTRACT_CONTRIBUTIONS.httpByOperationId.keys()].sort(),
);
});
});
/**
* 1103/07-01. The wire values of a descriptor are graded by the governance
* the repository ships, not only recorded: narrowing what the frontend
* accepts, or changing how it validates, needs baseline evidence.
*/
describe("FE-REG-API compatibility of descriptor wire values", () => {
async function snapshotOf(
rows: Readonly<Record<string, unknown>>,
): Promise<Readonly<Record<string, unknown>>> {
const governance = JSON.parse(
await readFile("config/contracts/registry-governance.json", "utf8"),
) as {
registries: Array<{
registryId: string;
breakingFields: string[];
fieldTypes: Record<string, string>;
}>;
};
const api = governance.registries.find(
(registry) => registry.registryId === "FE-REG-API",
)!;
return {
registries: [
{
registryId: "FE-REG-API",
contract: {
breakingFields: api.breakingFields,
fieldTypes: api.fieldTypes,
},
rows: canonicalizeRegistryValue(rows),
},
],
};
}
const rowsWith = (
contract: Partial<typeof TEST_CREATE_HTTP_CONTRACT.contract> = {},
frontend: Partial<typeof TEST_CREATE_HTTP_CONTRACT.frontend> = {},
) =>
projectApiOperationRows(
composeContractContributions([
{
...TEST_CONTRACT_CONTRIBUTION,
http: [
{
contract: {
...TEST_CREATE_HTTP_CONTRACT.contract,
acceptedStatuses: [200, 201],
emptyBodyStatuses: [201],
...contract,
},
frontend: { ...TEST_CREATE_HTTP_CONTRACT.frontend, ...frontend },
},
] as never,
},
]).contributions,
);
async function changesFor(after: Readonly<Record<string, unknown>>) {
const diff = diffRegistrySnapshots(
await snapshotOf(rowsWith()),
await snapshotOf(after),
);
return diff.changes.map(({ changeId, impact }) => `${changeId} ${impact}`);
}
it.each([
[
"a narrowed status list",
{ acceptedStatuses: [201] },
{},
[
"FE-REG-API:TEST_CREATE_ENTITY:acceptedStatuses:allowed-value-removed breaking",
],
],
[
"a narrowed empty-body list",
{ emptyBodyStatuses: [] },
{},
[
"FE-REG-API:TEST_CREATE_ENTITY:emptyBodyStatuses:allowed-value-removed breaking",
],
],
[
"another problem schema",
{
problemValidator: {
...TEST_CREATE_HTTP_CONTRACT.contract.problemValidator,
schemaId: "OtherProblem",
},
},
{},
["FE-REG-API:TEST_CREATE_ENTITY:problemSchema:field-changed breaking"],
],
[
"an output whose validation is skipped",
{ outputValidator: unvalidatedPayload("TestEntityPayload", "trusted") },
{},
["FE-REG-API:TEST_CREATE_ENTITY:unvalidated:field-changed breaking"],
],
[
"a widened status list",
{ acceptedStatuses: [200, 201, 202] },
{},
[
"FE-REG-API:TEST_CREATE_ENTITY:acceptedStatuses:field-changed behavior-change",
],
],
[
"a larger response limit and a longer deadline",
{},
{ responseByteLimit: 8_388_608, totalDeadlineMs: 60_000 },
[
"FE-REG-API:TEST_CREATE_ENTITY:responseByteLimit:field-changed behavior-change",
"FE-REG-API:TEST_CREATE_ENTITY:totalDeadlineMs:field-changed behavior-change",
],
],
[
"a traffic policy",
{},
{
traffic: {
maxPhysicalRequests: 1,
maxRetries: 0,
maxConcurrentRequests: 1,
maxQueuedRequests: 0,
},
},
["FE-REG-API:TEST_CREATE_ENTITY:traffic:field-changed behavior-change"],
],
[
"a status classifier",
{
commandEffect: TEST_CLASSIFIED_CREATE_HTTP_CONTRACT.contract.commandEffect,
},
{},
[
"FE-REG-API:TEST_CREATE_ENTITY:commandEffect:field-changed behavior-change",
],
],
] as const)("grades %s", async (_name, contract, frontend, expected) => {
expect(await changesFor(rowsWith(contract as never, frontend as never))).toEqual(
expected,
);
});
});