문제 설계 정본 8.3은 SAFE를 "GET/HEAD; 보낸 뒤 network 실패에도 재시도 허용" 으로 정한다. 실행기는 그 규칙대로 SAFE면 보낸 뒤 응답을 잃어도 다시 보낸다(http-retry-lifecycle.ts canRetryTransport). 그런데 조립 검사는 쓰기가 SAFE인지 보지 않는다. 생성된 뼈대 descriptor가 GET·SAFE· retryBudget 2이고, 매뉴얼은 쓰기를 더할 때 이 파일을 고쳐 쓰라고 한다. retrySemantics를 바꾸지 않으면 POST가 조립을 통과하고, 응답을 잃은 생성 요청이 최대 두 번 더 나간다(리뷰 실험 X-E: fetch 2회, 결과 SUCCESS). V2에도 이 규칙은 없었다. 고른 방법 assertHttpContract의 쓰기 가지(GET·HEAD 밖)에서 retrySemantics가 SAFE면 operation·method와 고를 값(IDEMPOTENT·KEYED·NEVER), 매뉴얼 절을 담아 거절한다. 매뉴얼 02 3절 "틀리면"에 같은 문장을 더했다. 버린 대안 실행기에서 쓰기의 SAFE를 NEVER처럼 다루기: 잘못 적은 계약이 조용히 다른 뜻으로 돈다. 조립 때 알리는 쪽이 고칠 곳을 바로 보여 준다. 위험·한계 쓰기를 SAFE로 적은 다운스트림은 부팅에서 실패한다. 의도한 실패다. 실행기를 조립 없이 직접 부르는 테스트 경로는 이 검사를 거치지 않는다. 검증 - RED: tests/unit/external-contract-runtime.test.ts의 POST·PUT·PATCH·DELETE × SAFE 4건 실패(조립 통과). - GREEN: 같은 파일 23건 통과. GET·SAFE와 PUT·IDEMPOTENT는 그대로 조립된다. - tests/unit·integration·contract·features·runtime-schema 214파일 2,904건 통과. check:types:app·test, eslint, verify:documentation 통과. BREAKING CHANGE: POST·PUT·PATCH·DELETE operation에 retrySemantics "SAFE"를 쓰면 composeContractContributions가 거절한다. 서버 보장에 맞춰 IDEMPOTENT, KEYED(commandRecovery 필요) 또는 NEVER(retryBudget 0)로 바꾼다. Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-03
312 lines
10 KiB
TypeScript
312 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");
|
|
});
|
|
|
|
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");
|
|
});
|
|
|
|
// 1103/03-03. SAFE lets the executor resend after dispatch, which a write
|
|
// copied from the scaffold's GET would then do with a lost answer.
|
|
it.each(["POST", "PUT", "PATCH", "DELETE"])(
|
|
"rejects SAFE retry semantics on a %s",
|
|
(method) => {
|
|
expect(
|
|
reasonFor({
|
|
...createRow,
|
|
contract: {
|
|
...createRow.contract,
|
|
method,
|
|
retrySemantics: "SAFE",
|
|
commandRecovery: null,
|
|
},
|
|
frontend: { ...createRow.frontend, retryBudget: 2 },
|
|
}),
|
|
).toBe(
|
|
`test-feature/TEST_CREATE_ENTITY: SAFE retry semantics is for GET and HEAD only; a ${method} declares IDEMPOTENT, KEYED or NEVER (docs/manual/02-decision-tables.md §3)`,
|
|
);
|
|
},
|
|
);
|
|
|
|
it("keeps SAFE on a read and IDEMPOTENT on a write", () => {
|
|
expect(() =>
|
|
composeContractContributions([
|
|
contribution("write-rule", [
|
|
listRow,
|
|
{
|
|
...createRow,
|
|
contract: {
|
|
...createRow.contract,
|
|
method: "PUT",
|
|
retrySemantics: "IDEMPOTENT",
|
|
commandRecovery: null,
|
|
},
|
|
} as InstalledContractContribution["http"][number],
|
|
]),
|
|
]),
|
|
).not.toThrow();
|
|
});
|
|
});
|
|
|
|
// 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" }] });
|
|
});
|
|
});
|