diff --git a/docs/architecture/backend-api-and-server-state-contract.md b/docs/architecture/backend-api-and-server-state-contract.md index f58e526a..08424390 100644 --- a/docs/architecture/backend-api-and-server-state-contract.md +++ b/docs/architecture/backend-api-and-server-state-contract.md @@ -287,6 +287,13 @@ mutation이 400·409·422로 실패하면 프론트는 그 요청이 적용됐 - application-notification의 `VALIDATION_FAILED`(`NotificationFailureCode`)는 `ApiErrorCarrier`가 아니다. HTTP로는 500 `INTERNAL_ERROR`로 나가므로 표에 없다. - 표에 없는 400·409·422 code는 `MAYBE_APPLIED`로 본다. +- 400·409·422 밖에서 백엔드 계약이 직접 정한 답 넷도 status와 code가 함께 + 맞으면 기능 분류기와 상관없이 `MAYBE_APPLIED`다(`backend-envelope.ts` + `MAYBE_APPLIED_ANSWERS`). `http-contract.md` §2의 503 `IDEMPOTENCY_UNAVAILABLE`, + 503 `IDEMPOTENCY_COMPLETION_UNKNOWN`(백엔드 `bbe944bd`부터), 500 + `IDEMPOTENCY_RECOVERY_REQUIRED`, §4의 503 `REQUEST_TIMEOUT`이다. 실행기가 + 자동으로 다시 보내는 것은 KEYED 명령의 503 `IDEMPOTENCY_UNAVAILABLE`뿐이다. + 나머지는 결과 불명 화면에서 사용자가 같은 키로 다시 보낸다. - 파일 위치(백엔드 repo 기준): - `GlobalExceptionHandler.java`: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/` - `PageParams.java`, `SortParam.java`: 같은 모듈 `.../web/pagination/` diff --git a/docs/manual/02-decision-tables.md b/docs/manual/02-decision-tables.md index b0bea47a..2b6d242a 100644 --- a/docs/manual/02-decision-tables.md +++ b/docs/manual/02-decision-tables.md @@ -140,9 +140,10 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 - 같은 status라도 code로 나뉠 수 있다. 예: 409 중 "처리 중"은 `MAYBE_APPLIED`여야 한다. `NOT_APPLIED`로 보면 다음 저장이 새 키를 만들어 같은 작업이 두 번 적용된다. - 401·403·429는 문제 응답 본문을 읽기 전에 status로 나뉜다. 서버가 상태를 안 바꾼다고 보장하면 `classifyStatus`로 `NOT_APPLIED`를 돌려준다. 없으면 `MAYBE_APPLIED`다. - 문제 응답 본문이 기능의 problem 스키마를 통과하지 못하면 `classifyProblem`을 부르지 않는다. 쓰기는 `MAYBE_APPLIED`가 된다(`src/adapters/http/http-execution-v3.ts`). -- `responseEnvelope: "ENVELOPE_V1"`인 operation은 400·409·422와 503 `IDEMPOTENCY_UNAVAILABLE`의 판정을 실행기가 백엔드 기준 표로 정한다(`src/adapters/http/backend-envelope.ts`의 `REFUSED_BEFORE_WRITE`). 표의 근거는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절이다(백엔드 코드에서 code마다 쓰기 전·후를 읽은 결과). `classifyProblem`은 그 밖의 status만 받고, 다르게 답해도 표의 판정은 바뀌지 않는다. +- `responseEnvelope: "ENVELOPE_V1"`인 operation은 400·409·422와 백엔드가 직접 정한 5xx 네 가지의 판정을 실행기가 백엔드 기준 표로 정한다(`src/adapters/http/backend-envelope.ts`의 `REFUSED_BEFORE_WRITE`, `MAYBE_APPLIED_ANSWERS`). 표의 근거는 [계약 문서](../architecture/backend-api-and-server-state-contract.md) 6.1절이다(백엔드 코드에서 code마다 쓰기 전·후를 읽은 결과). `classifyProblem`은 그 밖의 status만 받고, 다르게 답해도 표의 판정은 바뀌지 않는다. - `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가 여기 든다. 그리고 503 `IDEMPOTENCY_UNAVAILABLE` + - `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`다 **503 `IDEMPOTENCY_UNAVAILABLE`는 `NOT_APPLIED`로 분류하지 않는다.** @@ -155,6 +156,7 @@ context는 URL 앞부분 하나(라우트 루트)를 가진다. 그 아래 기 503 IDEMPOTENCY_UNAVAILABLE → V3 실행기 ├─ responseEnvelope: "ENVELOPE_V1" (생성한 기능) → 실행기가 MAYBE_APPLIED로 정한다 + │ KEYED이고 retryBudget > 0이면 먼저 같은 키로 다시 보낸다(3절). 예산을 다 쓰면 결과 불명 └─ Envelope 없음 (참조 기능) → 기능의 classifyProblem이 정한다 참조 기능: 400·422와 정해 둔 409 code만 NOT_APPLIED → 503은 MAYBE_APPLIED → 결과 불명 화면 → "같은 요청으로 다시 보내기"가 같은 키로 보낸다 diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index f6ac34a0..fe3b74f7 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -153,16 +153,40 @@ export function isFieldValidationFailure( Array.isArray(error.details); } +/** + * 1103/03-04. The backend's answers outside 400, 409 and 422 that it defines + * itself (§2, §4), each with its status. None of them lets a client say the + * command did not run, and none takes a new key. + */ +const MAYBE_APPLIED_ANSWERS: Readonly> = Object.freeze({ + // §2. Refused before the action, but to be resent with the same key, which + // only an unknown result keeps. + IDEMPOTENCY_UNAVAILABLE: 503, + // §2. The action ran and recording its result failed: same key later, + // never a new one. + IDEMPOTENCY_COMPLETION_UNKNOWN: 503, + // §2. An earlier attempt's effect cannot be proven. Not resent on its own; + // the user checks the data. + IDEMPOTENCY_RECOVERY_REQUIRED: 500, + // §4. An async request ran past its time; the work may still go on. + REQUEST_TIMEOUT: 503, +}); + +function mayHaveApplied(code: string, status: number): boolean { + return Object.hasOwn(MAYBE_APPLIED_ANSWERS, code) + ? MAYBE_APPLIED_ANSWERS[code] === status + : false; +} + /** * The verdict the backend contract gives whatever the operation is, or * `undefined` when the operation's own classifier decides. * - * - Not applied: a code in the table above. + * - Not applied: a code in the refusal table above. * - 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. - * And 503 IDEMPOTENCY_UNAVAILABLE: §2 says to resend it with the same key, - * which only an unknown result keeps. + * And the answers in `MAYBE_APPLIED_ANSWERS`, status and code together. */ export function envelopeFailureEffect( status: number, @@ -172,7 +196,7 @@ export function envelopeFailureEffect( return status === 400 || status === 409 || status === 422 || - (status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE") + mayHaveApplied(error.code, status) ? "MAYBE_APPLIED" : undefined; } diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index d6c66572..79228616 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -199,8 +199,8 @@ export interface InstalledHttpContract { * the paired backend's `{ success, data | error, meta }` * (clean-architecture-backend-template docs/web/http-contract.md §1). * `outputValidator` then sees `data` (`null` when the key is absent) and - * `problemValidator` sees `error`. Whether a 400, 409, 422 or 503 - * `IDEMPOTENCY_UNAVAILABLE` applied comes from the backend's own table + * `problemValidator` sees `error`. Whether a 400, 409, 422 or one of the + * backend's own 5xx answers (§2, §4) applied comes from the backend's table * (`src/adapters/http/backend-envelope.ts`, the frontend contract's 6.1), * not from `commandEffect.classifyProblem`, which decides every other * status. A body that is empty by `emptyBodyStatuses` has no Envelope. diff --git a/tests/integration/http-execution-v3-envelope.test.ts b/tests/integration/http-execution-v3-envelope.test.ts index 2626feea..6c47b148 100644 --- a/tests/integration/http-execution-v3-envelope.test.ts +++ b/tests/integration/http-execution-v3-envelope.test.ts @@ -588,6 +588,23 @@ describe("V3 Envelope verdicts follow the backend's refusal table", () => { effect: "MAYBE_APPLIED", }); + // 1103/03-04. The backend's other idempotency failures and its async + // request timeout say the command may have run (http-contract.md §2, §4). + for (const [status, code] of [ + [503, "IDEMPOTENCY_COMPLETION_UNKNOWN"], + [500, "IDEMPOTENCY_RECOVERY_REQUIRED"], + [503, "REQUEST_TIMEOUT"], + ] as const) { + answer("post", "/api/envelope-items", failure(code, "TRANSIENT_DEPENDENCY", true), { + status, + }); + await expect(v3CreateFailure(conflict)).resolves.toMatchObject({ + httpStatus: status, + code, + effect: "MAYBE_APPLIED", + }); + } + // A 404 is the package's to classify. answer("post", "/api/envelope-items", failure("NOT_FOUND", "NOT_FOUND", false), { status: 404, @@ -634,7 +651,14 @@ describe("KEYED resend on the backend's pre-execution refusal", () => { frontend: Object.freeze({ ...CREATE_CONTRACT.frontend, retryBudget: 1 as const }), }); - async function run(answers: readonly (() => Response)[]) { + async function run( + answers: readonly (() => Response)[], + contract: InstalledHttpContract< + Readonly>, + z.output, + EnvelopeProblem + >["contract"] = CREATE_CONTRACT.contract, + ) { const keys: (string | null)[] = []; server.use( http.post(`${BASE_URL}/api/envelope-items`, ({ request }) => { @@ -650,7 +674,7 @@ describe("KEYED resend on the backend's pre-execution refusal", () => { sleep: async () => {}, random: () => 0, }); - const outcome = await executor.execute(RETRYING_CREATE, Object.freeze({}), { + const outcome = await executor.execute({ ...RETRYING_CREATE, contract }, Object.freeze({}), { routeId: "ENVELOPE_ROUTE", scope: scope(), intent: intent("ENVELOPE_CREATE_ITEM"), @@ -695,6 +719,29 @@ describe("KEYED resend on the backend's pre-execution refusal", () => { expect(keys).toEqual([KEY]); }); + // 1103/03-04. "May be applied, resend later with the same key": the key + // is kept for the user's resend, and nothing is sent again on its own, even + // by a package that reads every problem as refused. + it.each([ + [503, "IDEMPOTENCY_COMPLETION_UNKNOWN"], + [500, "IDEMPOTENCY_RECOVERY_REQUIRED"], + [503, "REQUEST_TIMEOUT"], + ] as const)("keeps the key and does not resend %i %s", async (status, code) => { + const { outcome, keys } = await run( + [ + () => + HttpResponse.json(failure(code, "TRANSIENT_DEPENDENCY", true), { + status, + }), + created, + ], + CREATE_LENIENT_CONTRACT.contract, + ); + + expect(outcome).toMatchObject({ kind: "PROBLEM", effect: "MAYBE_APPLIED" }); + expect(keys).toEqual([KEY]); + }); + it("does not resend a 503 the backend did not mark as a pre-execution refusal", async () => { const { outcome, keys } = await run([ () => diff --git a/tests/unit/backend-envelope.test.ts b/tests/unit/backend-envelope.test.ts index baf3d8a9..4b59dbc9 100644 --- a/tests/unit/backend-envelope.test.ts +++ b/tests/unit/backend-envelope.test.ts @@ -4,6 +4,7 @@ import { envelopeFailureEffect, envelopeFailureReading, idempotencyRefusalReason, + invitesKeyedResend, } from "../../src/adapters/http/backend-envelope.ts"; /** @@ -47,8 +48,26 @@ describe("backend Envelope failure table", () => { expect(envelopeFailureEffect(status, { code })).toBe("MAYBE_APPLIED"); }); + // 1103/03-04. http-contract.md §2 and §4: the command may have run. + it.each([ + [503, "IDEMPOTENCY_UNAVAILABLE", true], + [503, "IDEMPOTENCY_COMPLETION_UNKNOWN", false], + [500, "IDEMPOTENCY_RECOVERY_REQUIRED", false], + [503, "REQUEST_TIMEOUT", false], + ] as const)("reads %i %s as maybe applied", (status, code, resend) => { + expect(envelopeFailureEffect(status, { code })).toBe("MAYBE_APPLIED"); + expect(invitesKeyedResend(status, { code })).toBe(resend); + }); + 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(); + // Status and code together: these codes under another 5xx are not the + // backend's documented answers. + expect( + envelopeFailureEffect(500, { code: "IDEMPOTENCY_COMPLETION_UNKNOWN" }), + ).toBeUndefined(); + expect(envelopeFailureEffect(502, { code: "REQUEST_TIMEOUT" })).toBeUndefined(); }); // 1103/08-05. Only a field list makes a 422 an input error.