Files
clean-architecture-frontend…/tests/unit/external-contract-runtime.test.ts
T
DongHyeonka 1e8b3d049f feat(http): operation이 쓰기 전 업무 거절 code를 선언한다
문제
Envelope operation의 400·409·422는 백엔드 표의 세 code만 NOT_APPLIED이고
나머지는 모두 MAYBE_APPLIED다. 기능의 classifyProblem은 이를 바꿀 수 없다.
짝 백엔드 생성 기능의 create는 이름 규칙을 트랜잭션 전에 검사하고 400
<FEATURE>_INVALID를 준다. 그런데 폼은 "변경 결과를 확인할 수 없습니다"를
띄우고 저장 버튼을 끈다. 입력을 고쳐도 다시 저장할 수 없다(리뷰 실험
X-A·X-B). 401·403·429는 classifyStatus로 operation이 정할 수 있는데
400·409·422는 정할 자리가 없다.

고른 방법 (결정 D2 ①)
- CommandEffectDescriptor에 선택 칸 refusedBeforeWrite?: readonly string[].
  표 밖 400·409·422가 이 목록의 code면 NOT_APPLIED다. 함수가 아니라 code
  목록이라 리뷰할 수 있고, status 범위를 통째로 NOT_APPLIED로 만들 수 없다.
- 조립 검사(assertRefusedBeforeWrite): 목록은 Envelope operation에만,
  code는 백엔드 문법, 중복 금지. IDEMPOTENT_*·IDEMPOTENCY_*는 거절한다
  (409 IDEMPOTENT_IN_FLIGHT의 앞선 요청은 적용될 수 있다).
- 실행기도 같은 code와 표의 code(VALIDATION_FAILED 등)를 무시한다. 조립
  없이 실행기를 부르는 경로의 fail-close다.
- 조립이 목록을 얼려 복사한다(LIVE-03). classifier는 지금처럼 참조로
  두고, 설치본이 원본을 prototype으로 물려받아 classifier의 this가 그대로다.
- 매뉴얼 02 4절과 계약 문서 6.1절에 언제 적고 언제 적지 않는지,
  <FEATURE>_INVALID 예와 거부 문구를 적었다.

버린 대안
- 표 밖 400 전체를 NOT_APPLIED: BAD_PARAMETER·MAPPING_FAILED는 쓰기 뒤에도
  나온다.
- 분류기 판정 복원: 3261208이 버린 길. 400 전체를 NOT_APPLIED로 보는
  분류기가 키 보호를 푼다.
- 결과 불명 화면에 "적용되지 않음" 버튼: 사용자가 모르고 누르면 새 키로
  중복이 생긴다.
- 백엔드 단계 신호(error.applied): 두 repo 계약 변경이다(D2 ②).

위험·한계
- 쓰기 뒤에도 나오는 code를 잘못 적으면 결과 불명 요청이 새 키로 나가
  중복이 생길 수 있다. 책임은 선언한 기능 작성자에게 간다. 매뉴얼이 백엔드
  코드에서 던지는 곳을 확인한 code만 적으라고 한다.
- 생성기(scripts/create-feature.ts)는 이 칸을 아직 쓰지 않는다. 다른 작업이
  이어 받는다.
- 결과 불명 화면이 거절 code의 문구를 보이는 것(08-01 (가))은 하지 않았다.

검증
- RED: 새 테스트 17건이 이 변경 전 소스에서 실패(조립 규칙 10, 판정 3,
  envelope 통합 3, form-foundation 1).
- GREEN: tests/unit·integration·component·features·contract·runtime-schema
  253파일 3,199건 통과. 폼: WORKLOG_INVALID를 선언하면 결과 unavailable,
  저장 켜짐, 고친 값 저장 fetch 2회, 키 key-1 → key-2. 선언하지 않으면
  effect-unknown, 저장 꺼짐, fetch 1회.
- 변이: 실행기의 멱등성·표 code 무시 제거, 조립의 멱등성 규칙 제거, 목록
  복사 제거, 실행기가 목록을 넘기지 않음 모두 검출. 보존 조건 M5·M10·M24도
  계속 검출.
- check:types, lint, check:registries, check:architecture,
  verify:documentation 통과.

Refs: docs/reviews/2026-11-03-maturity-review/03-adapters-http-state.md 03-01
Refs: docs/reviews/2026-11-03-maturity-review/08-presentation.md 08-01
2026-11-04 20:38:12 +09:00

405 lines
14 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();
});
});
// 1103/03-01. A command names the backend codes its endpoint raises only
// before it writes. Composition decides what such a list may hold.
describe("declared pre-write refusals", () => {
const [, , createRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
InstalledContractContribution["http"][number],
InstalledContractContribution["http"][number],
InstalledContractContribution["http"][number],
];
function withRefusals(
refusedBeforeWrite: unknown,
responseEnvelope: unknown = "ENVELOPE_V1",
) {
return contribution("refusal-rule", [
{
...createRow,
contract: {
...createRow.contract,
responseEnvelope,
commandEffect: {
...createRow.contract.commandEffect!,
refusedBeforeWrite,
},
},
} as InstalledContractContribution["http"][number],
]);
}
function reasonFor(refusedBeforeWrite: unknown, responseEnvelope?: unknown) {
return captureContributionError(() =>
composeContractContributions([
withRefusals(refusedBeforeWrite, responseEnvelope),
]),
).reason;
}
it("installs a frozen copy of the declared codes", () => {
const declared = ["TEST_ENTITY_INVALID", "TEST_ENTITY_ALREADY_EXISTS"];
const composed = composeContractContributions([withRefusals(declared)]);
declared.push("ADDED_AFTER_BOOT");
const installed = composed.httpByOperationId.get("TEST_CREATE_ENTITY")?.contract
.commandEffect;
expect(installed?.refusedBeforeWrite).toEqual([
"TEST_ENTITY_INVALID",
"TEST_ENTITY_ALREADY_EXISTS",
]);
expect(Object.isFrozen(installed?.refusedBeforeWrite)).toBe(true);
// The classifiers are still the contribution's own.
expect(installed?.classifyProblem).toBe(createRow.contract.commandEffect!.classifyProblem);
expect(installed?.successEffect).toBe("APPLIED_CONFIRMED");
});
it.each([
"IDEMPOTENT_IN_FLIGHT",
"IDEMPOTENT_REQUEST_MISMATCH",
"IDEMPOTENCY_UNAVAILABLE",
"IDEMPOTENCY_COMPLETION_UNKNOWN",
"IDEMPOTENCY_KEY_INVALID",
])("refuses to declare the idempotency answer %s", (code) => {
expect(reasonFor(["TEST_ENTITY_INVALID", code])).toBe(
`test-feature/TEST_CREATE_ENTITY: refusedBeforeWrite cannot declare ${code}; the backend's idempotency answers are decided by its own table`,
);
});
it("refuses a list on an operation that does not read the Envelope", () => {
expect(reasonFor(["TEST_ENTITY_INVALID"], "NONE")).toBe(
"test-feature/TEST_CREATE_ENTITY: refusedBeforeWrite needs responseEnvelope ENVELOPE_V1; without it classifyProblem decides",
);
});
it.each([
[
"a lowercase code",
["test_entity_invalid"],
"test-feature/TEST_CREATE_ENTITY: refusedBeforeWrite code test_entity_invalid",
],
[
"a repeated code",
["TEST_ENTITY_INVALID", "TEST_ENTITY_INVALID"],
"test-feature/TEST_CREATE_ENTITY: refusedBeforeWrite repeats TEST_ENTITY_INVALID",
],
// Refused while the row is copied, before its operation id is read.
[
"a string instead of a list",
"TEST_ENTITY_INVALID",
"test-feature: refusedBeforeWrite must be a list of backend codes",
],
])("refuses %s", (_label, declared, reason) => {
expect(reasonFor(declared)).toBe(reason);
});
});
// 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" }] });
});
});