Files
clean-architecture-frontend…/tests/unit/external-contract-runtime.test.ts
T
DongHyeonka e4caafda30 fix(contracts)!: 읽기 operation은 SAFE·IDEMPOTENT일 때만 조립한다
문제
GET에 `retrySemantics: "KEYED"`(commandRecovery 없음)나 `"NEVER"`를
적어도 계약 조립이 통과하고 FE-REG-API 행에 그 값이 남는다. KEYED 복구
descriptor 검사가 쓰기 분기 안에만 있기 때문이다. 실행기는 이 GET을
쓰기로 보지 않아 재시도 없는 읽기로 돌린다. 매뉴얼은 "읽기(GET)는 늘
SAFE"라 적는다. V2 `defineRestOperation`은 조회에 SAFE·IDEMPOTENT만
허용했는데 V2 삭제 때 이 규칙이 V3로 옮겨지지 않았다(실험 R1).

고른 방법
assertHttpContract의 읽기 분기에서 GET·HEAD의 retrySemantics가 SAFE나
IDEMPOTENT가 아니면 method와 값을 담아 거절한다. realtime snapshot 바인딩이
요구하는 짝(GET + SAFE·IDEMPOTENT)과 같은 어휘다. 매뉴얼 02 3절 "틀리면"에
거절 문구를 더했다.

버린 대안
- 레지스트리 governance의 allowedValues로 막기: method별 허용값을 표현할
  칸이 없고, 조립(부팅 경로)이 아니라 check:registries에서만 걸린다.

위험·한계
- GET·HEAD를 KEYED나 NEVER로 적은 다운스트림 descriptor는 부팅에서 계약
  조립 실패가 된다. 템플릿 안에는 그런 descriptor가 없다(grep).
- 쓰기의 SAFE 금지(03-03)는 이 커밋 범위가 아니다.

검증
- RED: tests/unit/external-contract-runtime.test.ts의 GET·HEAD × KEYED·NEVER
  4건이 실패(조립 통과)했다.
- GREEN: `run-vitest related src/contracts/external-contract-runtime.ts`
  105파일 950건 통과. check:types, eslint, check:registries,
  verify:documentation 통과.

BREAKING CHANGE: GET·HEAD operation의 retrySemantics가 KEYED나 NEVER이면
계약 조립이 CONTRACT_CONTRIBUTION_INVALID로 실패한다. SAFE(재시도 허용)나
IDEMPOTENT로 바꾼다. 재시도를 막으려면 frontend.retryBudget을 0으로 둔다.

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

304 lines
10 KiB
TypeScript

import { describe, expect, it } from "vitest";
import {
ContractContributionError,
composeContractContributions,
invokeValidator,
type InstalledContractContribution,
type RuntimeValidator,
} from "../../src/contracts/external-contract-runtime.ts";
import {
listUnvalidatedPayloads,
unvalidatedPayload,
} from "../../src/contracts/unvalidated-payload.ts";
import {
TEST_CONTRACT_CONTRIBUTION,
TEST_EVENT_CONTRACT,
} from "../helpers/external-contract-fixture.ts";
function contribution(
contributionId: string,
http: InstalledContractContribution["http"],
): InstalledContractContribution & Readonly<{ contributionId: string }> {
return Object.freeze({
...TEST_CONTRACT_CONTRIBUTION,
contributionId,
http: Object.freeze([...http]),
});
}
function captureContributionError(operation: () => unknown): ContractContributionError {
try {
operation();
} catch (error) {
expect(error).toBeInstanceOf(ContractContributionError);
return error as ContractContributionError;
}
throw new Error("Expected contract composition to fail.");
}
describe("external contract contribution composition", () => {
it("allows one feature to install multiple uniquely identified contributions", () => {
const operations = TEST_CONTRACT_CONTRIBUTION.http;
const composed = composeContractContributions([
contribution("test-read-contracts", operations.slice(0, 2)),
contribution("test-command-contracts", operations.slice(2)),
]);
expect(composed.contributions).toHaveLength(2);
expect(composed.httpByOperationId.size).toBe(3);
});
it("rejects duplicate contribution identities even across different feature entries", () => {
const first = contribution(
"test-contracts",
TEST_CONTRACT_CONTRIBUTION.http.slice(0, 1),
);
const second = contribution(
"test-contracts",
TEST_CONTRACT_CONTRIBUTION.http.slice(1),
);
const error = captureContributionError(() =>
composeContractContributions([first, second]),
);
expect(error.reason).toContain("duplicate contributionId");
});
it("maps malformed source values to the closed composition error", () => {
const malformed = {
...contribution("malformed-source", []),
source: null,
} as unknown as InstalledContractContribution;
const error = captureContributionError(() =>
composeContractContributions([malformed]),
);
expect(error.reason).toContain("source");
});
it("rejects method and body vocabulary outside the runtime protocol", () => {
const installed = TEST_CONTRACT_CONTRIBUTION.http[0]!;
const malformedOperation = {
...installed,
contract: { ...installed.contract, method: "TRACE" },
} as unknown as InstalledContractContribution["http"][number];
const error = captureContributionError(() =>
composeContractContributions([
contribution("invalid-http-vocabulary", [malformedOperation]),
]),
);
expect(error.reason).toContain("method");
});
});
// 07-06 (MX1, MX9, MX6). The write-API rules the composer teaches through its
// error messages. TEST_CONTRACT_CONTRIBUTION composing in the first block is
// the valid control.
describe("write operation rules", () => {
const [listRow, , createRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
InstalledContractContribution["http"][number],
InstalledContractContribution["http"][number],
InstalledContractContribution["http"][number],
];
function reasonFor(row: object): string {
return captureContributionError(() =>
composeContractContributions([
contribution("write-rule", [
row as InstalledContractContribution["http"][number],
]),
]),
).reason;
}
// The executor decides "write" by `commandEffect !== null`, not by method,
// so this rule is the only thing keeping a GET from running as a command.
it("rejects command descriptors on a read operation", () => {
expect(
reasonFor({
...listRow,
contract: { ...listRow.contract, commandEffect: createRow.contract.commandEffect },
}),
).toBe("test-feature/TEST_LIST_ENTITIES: read operations carry no command descriptors");
});
// 1103/07-01 (c). The KEYED recovery check sits in the write branch, so a
// GET written as KEYED or NEVER used to compose and run as a read with no
// retry. A read is SAFE or IDEMPOTENT (docs/manual/02-decision-tables.md 3절).
it.each([
["GET", "KEYED"],
["GET", "NEVER"],
["HEAD", "KEYED"],
["HEAD", "NEVER"],
] as const)("rejects a %s declared %s", (method, retrySemantics) => {
expect(
reasonFor({
...listRow,
contract: { ...listRow.contract, method, retrySemantics },
frontend: { ...listRow.frontend, retryBudget: 0 },
}),
).toBe(
`test-feature/TEST_LIST_ENTITIES: ${method} is a read; its retrySemantics is SAFE or IDEMPOTENT, not ${retrySemantics}`,
);
});
it.each(["SAFE", "IDEMPOTENT"] as const)("composes a GET declared %s", (retrySemantics) => {
expect(
composeContractContributions([
contribution("read-rule", [
{
...listRow,
contract: { ...listRow.contract, retrySemantics },
} as InstalledContractContribution["http"][number],
]),
]).httpByOperationId.size,
).toBe(1);
});
it("requires a recovery descriptor on a KEYED command", () => {
expect(
reasonFor({
...createRow,
contract: { ...createRow.contract, commandRecovery: null },
}),
).toBe("test-feature/TEST_CREATE_ENTITY: KEYED commands require a recovery descriptor");
});
it("rejects a retry budget on a NEVER-retry operation", () => {
expect(
reasonFor({
...createRow,
contract: { ...createRow.contract, retrySemantics: "NEVER" },
frontend: { ...createRow.frontend, retryBudget: 1 },
}),
).toBe("test-feature/TEST_CREATE_ENTITY: retry budget contradicts NEVER retry semantics");
});
});
// The sample feature's own cases (its fixture composes, a second one does not)
// live in tests/features so they leave with the sample.
describe("template fixture provenance (07-04, §4.8)", () => {
it("rejects a fixture copied into a product feature, which would leave the contract set silently", () => {
const copied = Object.freeze({
...contribution("order-http-v1", TEST_CONTRACT_CONTRIBUTION.http),
featureId: "order",
source: Object.freeze({
kind: "TEMPLATE_FIXTURE" as const,
fixtureId: "REFERENCE_FEATURE_V1" as const,
revision: 1 as const,
}),
});
const error = captureContributionError(() =>
composeContractContributions([copied]),
);
expect(error.reason).toMatch(
/^order: TEMPLATE_FIXTURE REFERENCE_FEATURE_V1 belongs to .+ only; pin an EXTERNAL_PACKAGE$/u,
);
});
});
// 1101/07-03. Skipping runtime validation stays possible, but only a skip
// made through `unvalidatedPayload` is named, so the composed result lists it.
describe("validation skipped by name (1101/07-03)", () => {
const [listRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
InstalledContractContribution["http"][number],
];
const skipped = unvalidatedPayload("TestEntityListPayload", "typed by the package");
function withOutput(validator: RuntimeValidator<unknown>) {
return contribution("skip-test", [
{ ...listRow, contract: { ...listRow.contract, outputValidator: validator } },
]);
}
it("lists nothing when every validator checks its input", () => {
expect(
listUnvalidatedPayloads(composeContractContributions([TEST_CONTRACT_CONTRIBUTION])),
).toEqual([]);
});
it("lists an operation whose output skips validation, with its reason", () => {
expect(
listUnvalidatedPayloads(composeContractContributions([withOutput(skipped)])),
).toEqual([
{
featureId: "test-feature",
contractId: "TEST_LIST_ENTITIES",
validator: "output",
schemaId: "TestEntityListPayload",
reason: "typed by the package",
},
]);
});
it("lists an event whose payload skips validation", () => {
const composed = composeContractContributions([
Object.freeze({
...contribution("skip-event", []),
events: Object.freeze([
{ ...TEST_EVENT_CONTRACT, payloadValidator: unvalidatedPayload("TestEntity", "trusted feed") },
]),
}),
]);
expect(listUnvalidatedPayloads(composed)).toEqual([
expect.objectContaining({
contractId: "test.entity.changed",
validator: "payload",
reason: "trusted feed",
}),
]);
});
it("refuses to name a skip without a reason", () => {
expect(() => unvalidatedPayload("TestEntity", " ")).toThrow(
"TestEntity: an unvalidated payload needs a reason",
);
});
// Composition (boot path) does not read the marker, so a hand-built one is
// not refused there; the list still shows it instead of passing it as checked.
it("lists a hand-built marker that is not NONE or has no reason", () => {
const handBuilt = { ...skipped, validation: "PARTIAL", unvalidatedReason: undefined };
expect(
listUnvalidatedPayloads(
composeContractContributions([withOutput(handBuilt as unknown as RuntimeValidator<unknown>)]),
),
).toEqual([expect.objectContaining({ validator: "output", reason: "" })]);
});
});
describe("validator invocation (07-06)", () => {
const returning = (result: unknown): RuntimeValidator<unknown> => ({
schemaId: "Malformed",
safeParse: () => result as never,
});
it.each([
["non-array issues", { success: false, issues: 5 }],
["object issues", { success: false, issues: {} }],
["non-boolean success", { success: "no", data: "unchecked" }],
["throwing issues getter", {
success: false,
get issues(): never {
throw new Error("hostile");
},
}],
])("reports THROWN for a result with %s", (_label, result) => {
expect(invokeValidator(returning(result), {})).toEqual({ outcome: "THROWN" });
});
it("keeps well-formed results", () => {
expect(invokeValidator(returning({ success: true, data: 1 }), {})).toEqual({
outcome: "VALID",
value: 1,
});
expect(
invokeValidator(returning({ success: false, issues: [{ path: [], code: "X" }] }), {}),
).toEqual({ outcome: "INVALID", issues: [{ path: [], code: "X" }] });
});
});