Files
clean-architecture-frontend…/tests/unit/api-operation-rows.test.ts
T
DongHyeonka 3fba68bebc refactor(contracts): FE-REG-API 행이 refusedBeforeWrite를 타입으로 읽는다
문제
fix/r1103-contracts는 fix/r1103-http가 아직 없을 때
CommandEffectDescriptor에 없는 refusedBeforeWrite를 구조 캐스트로
읽었다. 두 브랜치를 합치자 그 칸이 타입에 생겼다. 또 행 투영 테스트가
Envelope가 아닌 operation에 refusedBeforeWrite를 적는데, http 쪽 조립
검사(1103/03-01)는 그것을 거절해 테스트가 ContractContributionError로
실패한다.

고른 방법
- api-operations.ts는 effect.refusedBeforeWrite를 타입으로 읽는다.
- 테스트의 create descriptor에 responseEnvelope ENVELOPE_V1을 주고,
  code를 업무 거절 모양(TEST_ENTITY_INVALID 등)으로 바꾼다.

위험·한계
- 행 모양은 그대로다. 기준선 영향 없음.

검증
- tests/unit/api-operation-rows.test.ts 12건, test:unit 2,790건,
  check:types, lint 통과.

Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-01
2026-11-04 22:34:35 +09:00

306 lines
9.3 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,
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,
);
});
});