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
This commit is contained in:
DongHyeonka
2026-11-04 20:38:12 +09:00
parent 37615072e9
commit 1e8b3d049f
9 changed files with 481 additions and 17 deletions
@@ -308,6 +308,23 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐
- `FileserverErrorCode.java`, `FinalizeUploadApplicationUseCase.java`:
`src/application-fileserver/`
**operation이 선언하는 쓰기 전 거절**(1103/03-01): 업무 code는 엔드포인트마다
단계가 달라 위 표에 "쓰기 뒤 가능"으로 둔다. 쓰기 전에만 그 code를 내는 엔드포인트를
아는 사람은 기능 작성자다. 그 사람이 descriptor의
`commandEffect.refusedBeforeWrite`에 code를 적는다.
- 그 code로 온 400·409·422는 `NOT_APPLIED`다. 적지 않은 code는 그대로 `MAYBE_APPLIED`다.
- 짝 백엔드 생성 기능의 create는 이름 규칙을 `build(command)`에서 트랜잭션 전에
검사하고 400 `<FEATURE>_INVALID`를 준다(`Create__Feature__UseCase.java.tmpl`,
`__Feature__ErrorCode.java.tmpl`). 이 code는 적는다.
- 위 표의 code(`VALIDATION_FAILED` 등)는 적어도 표의 status 규칙을 따른다.
`IDEMPOTENT_*`·`IDEMPOTENCY_*`는 적을 수 없다. 계약 조립이 거절하고, 실행기도
무시한다. 409 `IDEMPOTENT_IN_FLIGHT`의 앞선 요청은 적용될 수 있기 때문이다.
- `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에는 적을 수 없다. 실행기가
백엔드 code를 읽지 않는다.
- 판정은 `src/adapters/http/backend-envelope.ts` `envelopeFailureEffect`, 조립 검사는
`src/contracts/external-contract-runtime.ts` `assertRefusedBeforeWrite`다.
프론트 판정과 표가 다른 곳(고치면 이 줄을 지운다):
- 참조 기능 분류기(`classifyProblem`)는 참조 fixture(problem+json)용이라
+8 -2
View File
@@ -144,7 +144,13 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
- `NOT_APPLIED`(쓰기 전 거절): 400 `VALIDATION_FAILED`(details 모양과 상관없음), 400 `IDEMPOTENCY_KEY_INVALID`, 422 `IDEMPOTENT_REQUEST_MISMATCH`
- `MAYBE_APPLIED`: 그 밖의 400·409·422. 409 `IDEMPOTENT_IN_FLIGHT`, `BAD_PARAMETER`, 도메인 code, fileserver의 422가 여기 든다. 그리고 status와 code가 함께 맞는 5xx 넷: 503 `IDEMPOTENCY_UNAVAILABLE`, 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`(실행 뒤 결과 기록 실패, 새 키 금지), 500 `IDEMPOTENCY_RECOVERY_REQUIRED`(이전 시도 효과를 증명 못 함), 503 `REQUEST_TIMEOUT`(비동기 요청 시간 초과, 처리가 계속될 수 있음)
- 이 넷은 실행기가 자동으로 다시 보내지 않는다. 결과 불명 화면에서 같은 키로 다시 보낸다. 예외는 KEYED 명령의 503 `IDEMPOTENCY_UNAVAILABLE` 하나다(아래)
- 짝 백엔드가 쓰기 전에 거절하는 code를 새로 만들면 계약 문서 6.1절과 이 표를 함께 고친다. 표에 없으면 `MAYBE_APPLIED`다
- 짝 백엔드가 모든 엔드포인트에서 쓰기 전에 거절하는 code를 새로 만들면 계약 문서 6.1절과 이 표를 함께 고친다. 표에 없으면 `MAYBE_APPLIED`다
- **업무 규칙 거절은 operation이 선언한다.** 도메인 code(`<FEATURE>_INVALID`, `*_ALREADY_EXISTS` 등)는 엔드포인트마다 쓰기 전에 나오는지가 다르다. 그래서 표에 없고, 그대로 두면 결과 불명이 된다. 폼은 "변경 결과를 확인할 수 없습니다"를 보이고 저장 버튼을 끈다. 사용자가 값을 고쳐 다시 저장할 수 없다.
- 그 엔드포인트가 쓰기 전에만 내는 code라면 `commandEffect.refusedBeforeWrite`에 적는다. 그 code로 온 400·409·422는 `NOT_APPLIED`가 되고, 다음 저장은 새 키를 쓴다.
- 짝 백엔드 `new-feature.sh`가 만든 create는 이름을 트랜잭션 전에 검사하고 400 `<FEATURE>_INVALID`를 준다(백엔드 `Create__Feature__UseCase.java.tmpl`). 이 code는 적는다. 예: 기능 `worklog`이면 `refusedBeforeWrite: ["WORKLOG_INVALID"]`.
- 고르는 기준: 백엔드 코드에서 그 code를 던지는 곳이 모두 쓰기(트랜잭션, 외부 호출) 전인지 확인했을 때만 적는다. 확인하지 못했으면 적지 않는다. 쓰기 뒤에도 나오는 code를 적으면 결과 불명 요청을 새 키로 다시 보내 중복이 생길 수 있다.
- 적을 수 없는 code: `IDEMPOTENT_*`, `IDEMPOTENCY_*`. 멱등성 응답은 백엔드 표가 정한다. 적으면 계약 조립이 `refusedBeforeWrite cannot declare ...`로 거부한다. `responseEnvelope: "ENVELOPE_V1"`가 아닌 operation에 적어도 거부한다(`refusedBeforeWrite needs responseEnvelope ENVELOPE_V1 ...`).
- 거절 이유를 필드 옆에 보이려면 `mapProblem`이 그 code를 `VALIDATION_REJECTED`와 필드 목록으로 돌려준다. 선언 없이 `mapProblem`만 두면 필드 오류는 보이지만 저장 버튼은 꺼진 채다.
**503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.**
@@ -169,7 +175,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기
**정본**: 어떤 status·code가 "적용 안 됨"인지는 `clean-architecture-backend-template/docs/web/http-contract.md` §2다.
**어디에 적나**: `contracts/<base>-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`). 예제: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`의 `CREATE_EFFECT`.
**어디에 적나**: `contracts/<base>-contract-contribution.ts`의 `commandEffect`(`classifyProblem`, `classifyStatus`, Envelope operation이면 `refusedBeforeWrite`). 예제: `src/features/reference-feature/contracts/reference-feature-contract-contribution.ts`의 `CREATE_EFFECT`.
**틀리면**
+30 -9
View File
@@ -179,10 +179,30 @@ function mayHaveApplied(code: string, status: number): boolean {
}
/**
* The verdict the backend contract gives whatever the operation is, or
* `undefined` when the operation's own classifier decides.
* 1103/03-01. A code the operation declares as refused before its write
* (`commandEffect.refusedBeforeWrite`). Composition already refuses an
* idempotency code in that list; this is the runtime's own fail-close for an
* executor called without composition. The table's own codes keep its status
* rule.
*/
function declaredBeforeWrite(
code: string,
declared: readonly string[] | undefined,
): boolean {
return (
declared !== undefined &&
!Object.hasOwn(REFUSED_BEFORE_WRITE, code) &&
!/^IDEMPOTEN(?:T|CY)_/.test(code) &&
declared.includes(code)
);
}
/**
* The verdict the backend contract gives, or `undefined` when the
* operation's own classifier decides.
*
* - Not applied: a code in the refusal table above.
* - Not applied: a code in the refusal table above, or a 400, 409 or 422
* whose code the operation declared as refused before its write.
* - Maybe applied: every other 400, 409 and 422, including 409
* IDEMPOTENT_IN_FLIGHT (an earlier request with the key still runs); the
* backend can raise them after a write and the code does not say which.
@@ -191,14 +211,15 @@ function mayHaveApplied(code: string, status: number): boolean {
export function envelopeFailureEffect(
status: number,
error: EnvelopeError,
declaredRefusals?: readonly string[],
): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined {
if (refusedBeforeWrite(error.code, status) !== undefined) return "NOT_APPLIED";
return status === 400 ||
status === 409 ||
status === 422 ||
mayHaveApplied(error.code, status)
? "MAYBE_APPLIED"
: undefined;
if (status === 400 || status === 409 || status === 422) {
return declaredBeforeWrite(error.code, declaredRefusals)
? "NOT_APPLIED"
: "MAYBE_APPLIED";
}
return mayHaveApplied(error.code, status) ? "MAYBE_APPLIED" : undefined;
}
/**
+8 -2
View File
@@ -1693,7 +1693,12 @@ async function admitProblem<Input, WireOutput, Problem>(
? invokeValidator(contract.problemValidator, framed.value)
: UNFRAMED_PROBLEM;
if (framed.ok) {
backendEffect = envelopeFailureEffect(status, framed.value);
// 1103/03-01. The operation's own pre-write refusals join the table.
backendEffect = envelopeFailureEffect(
status,
framed.value,
contract.commandEffect?.refusedBeforeWrite,
);
refusalReason = idempotencyRefusalReason(framed.value.code, status);
keyedResend =
isCommand &&
@@ -1720,7 +1725,8 @@ async function admitProblem<Input, WireOutput, Problem>(
}
// The backend's own verdict, when it has one, is the same for every
// operation. The package classifies the rest.
// operation, plus the codes the operation lists as refused before its
// write. The package classifies the rest.
const classification =
isCommand && backendEffect !== undefined
? Object.freeze({ effect: backendEffect, contractRuntimeFailure: false })
@@ -149,6 +149,17 @@ export interface CommandEffectDescriptor<Problem> {
* command was rejected untouched. Without this, they stay `MAYBE_APPLIED`.
*/
classifyStatus?(status: 401 | 403 | 429): "NOT_APPLIED" | "MAYBE_APPLIED";
/**
* 1103/03-01. `responseEnvelope: "ENVELOPE_V1"` only. The backend codes
* this endpoint raises only before it writes, such as the paired backend
* scaffold's `<FEATURE>_INVALID` (its create checks the name before the
* transaction). A 400, 409 or 422 outside the backend's own table that
* carries one of these codes is `NOT_APPLIED`, so the next save takes a new
* key. Every code not listed stays `MAYBE_APPLIED`. Idempotency codes
* (`IDEMPOTENT_*`, `IDEMPOTENCY_*`) are the backend table's to decide, and
* composition refuses them here. Composition installs a copy of the list.
*/
readonly refusedBeforeWrite?: readonly string[];
}
export type HttpMethod =
@@ -524,6 +535,7 @@ function assertHttpContract(
) {
fail(`${label}: command status classifier must be a function`);
}
assertRefusedBeforeWrite(contract, label);
if (contract.retrySemantics === "KEYED" && !contract.commandRecovery) {
fail(`${label}: KEYED commands require a recovery descriptor`);
}
@@ -570,6 +582,46 @@ function assertHttpContract(
}
}
/** The paired backend's `error.code` grammar (its docs/web/http-contract.md §1). */
const BACKEND_ERROR_CODE = /^[A-Z0-9_]{1,64}$/;
/**
* 1103/03-01. Codes no operation may declare as refused before the write:
* the backend's idempotency answers. Its own table decides them, including
* 409 IDEMPOTENT_IN_FLIGHT, whose earlier request may still apply.
*/
const IDEMPOTENCY_CODE = /^IDEMPOTEN(?:T|CY)_/;
function assertRefusedBeforeWrite(
contract: InstalledHttpContract<unknown, unknown, unknown>["contract"],
label: string,
): void {
const declared = contract.commandEffect?.refusedBeforeWrite;
if (declared === undefined) return;
if (!Array.isArray(declared)) {
fail(`${label}: refusedBeforeWrite must be a list of backend codes`);
}
// Without the Envelope the executor never reads a backend code, so the
// list would promise a verdict nothing applies.
if (contract.responseEnvelope !== "ENVELOPE_V1") {
fail(
`${label}: refusedBeforeWrite needs responseEnvelope ENVELOPE_V1; without it classifyProblem decides`,
);
}
const seen = new Set<string>();
for (const code of declared as readonly unknown[]) {
if (typeof code !== "string" || !BACKEND_ERROR_CODE.test(code)) {
fail(`${label}: refusedBeforeWrite code ${String(code)}`);
}
if (IDEMPOTENCY_CODE.test(code)) {
fail(
`${label}: refusedBeforeWrite cannot declare ${code}; the backend's idempotency answers are decided by its own table`,
);
}
if (seen.has(code)) fail(`${label}: refusedBeforeWrite repeats ${code}`);
seen.add(code);
}
}
function assertEventContract(
event: InstalledEventContract<unknown, unknown>,
featureId: string,
@@ -693,6 +745,7 @@ function snapshotHttpContract(
...source,
acceptedStatuses: statusArray(source.acceptedStatuses, reject),
emptyBodyStatuses: statusArray(source.emptyBodyStatuses, reject),
commandEffect: snapshotCommandEffect(source.commandEffect, reject),
commandRecovery:
source.commandRecovery === null
? null
@@ -706,6 +759,44 @@ function snapshotHttpContract(
return Object.freeze({ contract, frontend });
}
/**
* 1103/03-01. The classifiers stay by reference, like validators: behaviour
* the contribution owns. The refusal list is data that lifts the backend's
* table, so the installed effect carries its own frozen copy, read once. The
* copy inherits everything else from the source, so a classifier keeps the
* `this` it was written for, and a list added to the source later is shadowed.
*/
function snapshotCommandEffect(
effect: CommandEffectDescriptor<unknown> | null,
reject: (detail: string) => never,
): CommandEffectDescriptor<unknown> | null {
// Not an object: assertHttpContract names what is wrong.
if (effect === null || typeof effect !== "object") return effect;
let declared: unknown;
try {
const descriptor = Object.getOwnPropertyDescriptor(
effect,
"refusedBeforeWrite",
);
if (descriptor !== undefined && !("value" in descriptor)) {
return reject("refusedBeforeWrite must be a data property");
}
declared = descriptor?.value;
} catch {
return reject("refusedBeforeWrite unreadable");
}
const codes =
declared === undefined
? undefined
: (snapshotExactArray(declared, 64) ??
reject("refusedBeforeWrite must be a list of backend codes"));
return Object.freeze(
Object.create(effect, {
refusedBeforeWrite: { value: codes, enumerable: true },
}) as CommandEffectDescriptor<unknown>,
);
}
/**
* Q-6.7-6. Arrays are copied by index, never through their iterator, so an own
* `Symbol.iterator` cannot hand composition a different list than `length`
+94 -4
View File
@@ -100,7 +100,33 @@ const FORM_OPERATIONS = Object.freeze({
}),
});
function formBinding(fetcher: typeof fetch) {
/**
* 1103/03-01. The same create, declaring the paired backend scaffold's
* `<FEATURE>_INVALID` as refused before the write.
*/
const FORM_DECLARING_OPERATIONS = Object.freeze({
FORM_CREATE_ENTITY: defineFeatureHttpOperation({
contract: Object.freeze({
...FORM_CREATE_CONTRACT,
contract: Object.freeze({
...FORM_CREATE_CONTRACT.contract,
commandEffect: Object.freeze({
...FORM_CREATE_CONTRACT.contract.commandEffect,
refusedBeforeWrite: Object.freeze(["WORKLOG_INVALID"]),
}),
}),
}),
routeId: "FORM_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
});
function formBinding(
fetcher: typeof fetch,
operations:
| typeof FORM_OPERATIONS
| typeof FORM_DECLARING_OPERATIONS = FORM_OPERATIONS,
) {
const executor = createContractHttpExecutor({
baseUrl: "https://api.test",
maxRetryAttempts: 0,
@@ -116,7 +142,7 @@ function formBinding(fetcher: typeof fetch) {
...(context.intent === undefined ? {} : { intent: context.intent }),
}),
}),
FORM_OPERATIONS,
operations,
);
}
@@ -803,8 +829,13 @@ describe("correcting a field after a server validation refusal", () => {
}),
};
function CoordinatedForm(props: Readonly<{ fetcher: typeof fetch }>) {
const [http] = useState(() => formBinding(props.fetcher));
function CoordinatedForm(
props: Readonly<{
fetcher: typeof fetch;
operations?: typeof FORM_DECLARING_OPERATIONS;
}>,
) {
const [http] = useState(() => formBinding(props.fetcher, props.operations));
const mutation = useApplicationMutation<
Readonly<{ name: string; note?: string }>,
unknown
@@ -912,6 +943,65 @@ describe("correcting a field after a server validation refusal", () => {
expect(fetcher).toHaveBeenCalledTimes(2);
});
function sentKeys(fetcher: ReturnType<typeof answerFirst>) {
return fetcher.mock.calls.map(
([, init]) => (init?.headers as Readonly<Record<string, string>>)["Idempotency-Key"],
);
}
// 1103/03-01 (= 08-01). The paired backend scaffold's create refuses a bad
// name with 400 <FEATURE>_INVALID before its transaction. Declared on the
// operation, the refusal is not an unknown result: the user corrects the
// value and saves again, and the second request is a new one.
it("saves the corrected value after a declared pre-write refusal, with a new key", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, { code: "WORKLOG_INVALID" });
render(
<CoordinatedForm fetcher={fetcher} operations={FORM_DECLARING_OPERATIONS} />,
{ wrapper: wrapper(queryClient()) },
);
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("unavailable"),
);
expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled();
await user.clear(name);
await user.type(name, "Fixed");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("success"),
);
expect(fetcher).toHaveBeenCalledTimes(2);
expect(sentKeys(fetcher)).toEqual(["key-1", "key-2"]);
});
// 1103/03-01. A code the operation did not declare may have been raised
// after a write, so the coordinator keeps holding it.
it("keeps the save off after a business refusal the operation did not declare", async () => {
const user = userEvent.setup();
const fetcher = answerFirst(400, { code: "WORKLOG_INVALID" });
render(<CoordinatedForm fetcher={fetcher} />, {
wrapper: wrapper(queryClient()),
});
const name = screen.getByRole("textbox", { name: /Name/ });
await user.type(name, "Rejected");
await user.click(screen.getByRole("button", { name: "Submit" }));
await waitFor(() =>
expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"),
);
await user.clear(name);
await user.type(name, "Fixed");
expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled();
expect(fetcher).toHaveBeenCalledTimes(1);
});
// 1101/14.4. Outside IDEMPOTENT_REQUEST_MISMATCH a 422 may come after a
// write (fileserver INTEGRITY_MISMATCH), so the coordinator holds it as an
// unknown result even though the form shows the field.
@@ -615,6 +615,96 @@ describe("V3 Envelope verdicts follow the backend's refusal table", () => {
});
});
// 1103/03-01. The paired backend scaffold's create checks the name before
// its transaction and answers 400 <FEATURE>_INVALID; the sample answers 409
// POSTER_ALREADY_EXISTS the same way. The operation that knows this declares
// those codes, and only those codes, as refused before the write.
describe("an operation's declared pre-write refusals", () => {
const CREATE_DECLARING_CONTRACT = Object.freeze({
...CREATE_CONTRACT,
contract: Object.freeze({
...CREATE_CONTRACT.contract,
commandEffect: Object.freeze({
...CREATE_CONTRACT.contract.commandEffect,
refusedBeforeWrite: Object.freeze(["WORKLOG_INVALID", "POSTER_ALREADY_EXISTS"]),
}) satisfies CommandEffectDescriptor<EnvelopeProblem>,
}),
});
const declaring = () =>
createFeatureHttpBinding(
v3Executor(),
Object.freeze({
ENVELOPE_CREATE_ITEM: defineFeatureHttpOperation({
contract: CREATE_DECLARING_CONTRACT,
routeId: "ENVELOPE_ROUTE",
mapSuccess: (value) => mappingSuccess(value),
}),
}),
);
it.each([
[400, "WORKLOG_INVALID", "UNKNOWN_CLIENT_FAILURE"],
[409, "POSTER_ALREADY_EXISTS", "CONFLICT"],
] as const)("reads a declared %i %s as not applied", async (status, code, kind) => {
answer("post", "/api/envelope-items", failure(code, "VALIDATION", false), { status });
await expect(v3CreateFailure(declaring()).then(verdict)).resolves.toMatchObject({
kind,
code,
httpStatus: status,
effect: "NOT_APPLIED",
});
});
it("keeps an undeclared business code and the in-flight 409 maybe applied", async () => {
answer("post", "/api/envelope-items", failure("WORKLOG_CONFLICT", "CONFLICT", false), {
status: 409,
});
await expect(v3CreateFailure(declaring())).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
answer(
"post",
"/api/envelope-items",
failure("IDEMPOTENT_IN_FLIGHT", "CONFLICT", true),
{ status: 409, headers: { "Retry-After": "2" } },
);
await expect(v3CreateFailure(declaring())).resolves.toMatchObject({
effect: "MAYBE_APPLIED",
});
});
it("applies the list the composition installed", async () => {
answer("post", "/api/envelope-items", failure("WORKLOG_INVALID", "VALIDATION", false), {
status: 400,
});
const composed = composeContractContributions([
Object.freeze({
contributionId: "envelope-test-http-v1",
featureId: "envelope-test",
source: TEST_CONTRACT_CONTRIBUTION.source,
http: Object.freeze([CREATE_DECLARING_CONTRACT]) as never,
events: Object.freeze([]),
}),
]);
const installed = composed.httpByOperationId.get("ENVELOPE_CREATE_ITEM")!;
const executor = createContractHttpExecutor({
baseUrl: BASE_URL,
maxRetryAttempts: 0,
attachCredentials: () => ({ kind: "READY" as const, headers: {} }),
});
await expect(
executor.execute(installed, Object.freeze({}), {
routeId: "ENVELOPE_ROUTE",
scope: scope(),
intent: intent("ENVELOPE_CREATE_ITEM"),
}),
).resolves.toMatchObject({ kind: "PROBLEM", effect: "NOT_APPLIED" });
});
});
// 1101 README 14.4. An Envelope operation's executor knows the backend code
// and names an idempotency refusal in diagnostics (`reason`, a closed
// taxonomy); any other code stays out of diagnostics.
+50
View File
@@ -59,6 +59,56 @@ describe("backend Envelope failure table", () => {
expect(invitesKeyedResend(status, { code })).toBe(resend);
});
// 1103/03-01. An operation names the codes its endpoint raises only before
// it writes (`commandEffect.refusedBeforeWrite`).
describe("with the operation's declared pre-write refusals", () => {
const declared = ["WORKLOG_INVALID", "POSTER_ALREADY_EXISTS", "VALIDATION_FAILED"];
it.each([
[400, "WORKLOG_INVALID"],
[409, "POSTER_ALREADY_EXISTS"],
[422, "WORKLOG_INVALID"],
] as const)("reads a declared %i %s as not applied", (status, code) => {
expect(envelopeFailureEffect(status, { code }, declared)).toBe("NOT_APPLIED");
});
it("keeps every code the operation did not declare maybe applied", () => {
expect(envelopeFailureEffect(400, { code: "BAD_PARAMETER" }, declared)).toBe(
"MAYBE_APPLIED",
);
expect(envelopeFailureEffect(400, { code: "WORKLOG_INVALID" })).toBe("MAYBE_APPLIED");
});
it("never lets a declaration decide an idempotency answer or a table code", () => {
const reckless = [
"IDEMPOTENT_IN_FLIGHT",
"IDEMPOTENCY_UNAVAILABLE",
"IDEMPOTENCY_COMPLETION_UNKNOWN",
"VALIDATION_FAILED",
];
expect(envelopeFailureEffect(409, { code: "IDEMPOTENT_IN_FLIGHT" }, reckless)).toBe(
"MAYBE_APPLIED",
);
expect(
envelopeFailureEffect(503, { code: "IDEMPOTENCY_UNAVAILABLE" }, reckless),
).toBe("MAYBE_APPLIED");
expect(
envelopeFailureEffect(503, { code: "IDEMPOTENCY_COMPLETION_UNKNOWN" }, reckless),
).toBe("MAYBE_APPLIED");
// The table's status rule still holds for its own code.
expect(envelopeFailureEffect(409, { code: "VALIDATION_FAILED" }, reckless)).toBe(
"MAYBE_APPLIED",
);
});
it("does not reach statuses outside 400, 409 and 422", () => {
expect(envelopeFailureEffect(500, { code: "WORKLOG_INVALID" }, declared)).toBeUndefined();
expect(envelopeFailureEffect(503, { code: "REQUEST_TIMEOUT" }, ["REQUEST_TIMEOUT"])).toBe(
"MAYBE_APPLIED",
);
});
});
it("leaves a status the table does not speak for to the package", () => {
expect(envelopeFailureEffect(404, { code: "NOT_FOUND" })).toBeUndefined();
expect(envelopeFailureEffect(500, { code: "INTERNAL_ERROR" })).toBeUndefined();
@@ -185,6 +185,99 @@ describe("write operation rules", () => {
});
});
// 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)", () => {