diff --git a/src/adapters/http/backend-envelope.ts b/src/adapters/http/backend-envelope.ts index 5499f253..bd9da4fd 100644 --- a/src/adapters/http/backend-envelope.ts +++ b/src/adapters/http/backend-envelope.ts @@ -50,48 +50,59 @@ export function readFailureEnvelope( } /** - * 백엔드 1101/02-01. Refusals the paired backend answers before it runs the - * command (§2): the request was not applied and sending it again unchanged - * gets the same answer. Only the documented status and code together count. - * The value is the diagnostics `reason`, named for what is wrong on this side. + * 1101/14.4. The 400, 409 and 422 codes the paired backend raises only before + * it writes. Backend 5786126c, read code by code into the frontend contract + * (docs/architecture/backend-api-and-server-state-contract.md 6.1); recheck + * this table with that section when the backend SHA there moves. Only the + * status and code together count. `reason` is the diagnostics name of an + * idempotency refusal, named for what is wrong on this side. */ export type IdempotencyRefusalReason = | "IDEMPOTENT_REQUEST_MISMATCH" | "IDEMPOTENCY_KEY_RULE_MISMATCH"; -const IDEMPOTENCY_REFUSALS: Readonly< - Record> +const REFUSED_BEFORE_WRITE: Readonly< + Record< + string, + Readonly<{ status: number; reason?: IdempotencyRefusalReason }> + > > = Object.freeze({ - // The same key went out with another body. - IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({ - status: 422, - reason: "IDEMPOTENT_REQUEST_MISMATCH", - }), + // Request binding and validation, whatever the details: the field list, a + // body that did not parse (`{cause}` or none), a page or sort parameter. + VALIDATION_FAILED: Object.freeze({ status: 400 }), // `isValidIdempotencyKey` passed the key before sending, so the client and // server key rules disagree. IDEMPOTENCY_KEY_INVALID: Object.freeze({ status: 400, reason: "IDEMPOTENCY_KEY_RULE_MISMATCH", }), + // The same key went out with another body. + IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({ + status: 422, + reason: "IDEMPOTENT_REQUEST_MISMATCH", + }), }); +function refusedBeforeWrite(code: string, status: number | undefined) { + const refusal = Object.hasOwn(REFUSED_BEFORE_WRITE, code) + ? REFUSED_BEFORE_WRITE[code] + : undefined; + return refusal !== undefined && refusal.status === status + ? refusal + : undefined; +} + export function idempotencyRefusalReason( code: string, status: number | undefined, ): IdempotencyRefusalReason | undefined { - const refusal = Object.hasOwn(IDEMPOTENCY_REFUSALS, code) - ? IDEMPOTENCY_REFUSALS[code] - : undefined; - return refusal !== undefined && refusal.status === status - ? refusal.reason - : undefined; + return refusedBeforeWrite(code, status)?.reason; } /** - * 백엔드 1101/02-01 후속. A field validation failure: a 422, or the paired - * backend's 400 VALIDATION_FAILED whose details is the field list (§4). A 400 - * VALIDATION_FAILED whose body did not parse carries `{cause}`, not a list, - * and is not one. + * 백엔드 1101/02-01 후속. A failure the form shows on its fields: a 422, or + * the paired backend's 400 VALIDATION_FAILED whose details is the field list + * (§4). This decides the kind and the issues only, not whether it applied. */ export function isFieldValidationFailure( status: number, @@ -109,25 +120,23 @@ export function isFieldValidationFailure( * The verdict the backend contract gives whatever the operation is, or * `undefined` when the operation's own classifier decides. * - * - Not applied: a field validation failure, checked when the request is - * bound, before the command runs (64e98ee), and an idempotency refusal. - * - Maybe applied: 409 IDEMPOTENT_IN_FLIGHT (the first request still runs) - * and 503 IDEMPOTENCY_UNAVAILABLE. §2 says to resend both with the same - * key, which only an unknown result keeps. + * - Not applied: a code in the 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. */ export function envelopeFailureEffect( status: number, error: EnvelopeError, ): "NOT_APPLIED" | "MAYBE_APPLIED" | undefined { - if ( - (status === 409 && error.code === "IDEMPOTENT_IN_FLIGHT") || + if (refusedBeforeWrite(error.code, status) !== undefined) return "NOT_APPLIED"; + return status === 400 || + status === 409 || + status === 422 || (status === 503 && error.code === "IDEMPOTENCY_UNAVAILABLE") - ) { - return "MAYBE_APPLIED"; - } - return isFieldValidationFailure(status, error) || - idempotencyRefusalReason(error.code, status) !== undefined - ? "NOT_APPLIED" + ? "MAYBE_APPLIED" : undefined; } diff --git a/src/contracts/external-contract-runtime.ts b/src/contracts/external-contract-runtime.ts index e3d555ff..5976fbbe 100644 --- a/src/contracts/external-contract-runtime.ts +++ b/src/contracts/external-contract-runtime.ts @@ -198,10 +198,12 @@ export interface InstalledHttpContract { * the body is the DTO, and a failure body is the problem. `"ENVELOPE_V1"`: * 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), - * `problemValidator` sees `error`, and the backend's operation-independent - * verdicts (§2, §4) come before `commandEffect.classifyProblem`. A body - * that is empty by `emptyBodyStatuses` has no Envelope. + * `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 + * (`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. */ responseEnvelope?: ResponseEnvelope; commandRecovery: CommandRecoveryDescriptor | null; diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index 26c0bca2..24294523 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -645,20 +645,8 @@ describe("correcting a field after a V2 validation refusal", () => { const meta = { requestId: "request-1", traceId: "trace-1" }; - // 백엔드 1101/02-01 후속. A 422 in the frontend contract's shape, and the - // paired backend's 400 VALIDATION_FAILED (its docs/web/http-contract.md §4). - it.each([ - { status: 422, error: { code: "INVALID_INPUT", details: { issues: [{ path: "name", code: "REQUIRED" }] } } }, - { - status: 400, - error: { - code: "VALIDATION_FAILED", - details: [{ field: "name", code: "NOT_BLANK", message: "필수 값이 없습니다." }], - }, - }, - ])("saves the corrected value after a $status field error", async ({ status, error }) => { - const user = userEvent.setup(); - const fetcher = vi + function answerFirst(status: number, error: unknown) { + return vi .fn() .mockResolvedValueOnce( Response.json({ success: false, error, meta }, { status }), @@ -670,6 +658,16 @@ describe("correcting a field after a V2 validation refusal", () => { meta, }), ); + } + + // 백엔드 1101/02-01 후속. The paired backend's 400 VALIDATION_FAILED with + // the field list (its docs/web/http-contract.md §4). + it("saves the corrected value after a 400 field error", async () => { + const user = userEvent.setup(); + const fetcher = answerFirst(400, { + code: "VALIDATION_FAILED", + details: [{ field: "name", code: "NOT_BLANK", message: "필수 값이 없습니다." }], + }); render(, { wrapper: wrapper(queryClient()), }); @@ -689,4 +687,52 @@ describe("correcting a field after a V2 validation refusal", () => { ); expect(fetcher).toHaveBeenCalledTimes(2); }); + + // 1101/14.4. A body the backend could not read is refused while binding, + // before any write (frontend contract 6.1), so the save is not held. + it("saves again after a 400 VALIDATION_FAILED whose body did not parse", async () => { + const user = userEvent.setup(); + const fetcher = answerFirst(400, { + code: "VALIDATION_FAILED", + details: { cause: "JsonParseException" }, + }); + render(, { + wrapper: wrapper(queryClient()), + }); + + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Fixed"); + await user.click(screen.getByRole("button", { name: "Submit" })); + await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1)); + await waitFor(() => + expect(screen.getByRole("button", { name: "Submit" })).toBeEnabled(), + ); + await user.click(screen.getByRole("button", { name: "Submit" })); + + await waitFor(() => + expect(screen.getByTestId("result")).toHaveTextContent("success"), + ); + expect(fetcher).toHaveBeenCalledTimes(2); + }); + + // 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. + it("keeps the save off after a 422 the backend may have applied", async () => { + const user = userEvent.setup(); + const fetcher = answerFirst(422, { + code: "INVALID_INPUT", + details: { issues: [{ path: "name", code: "REQUIRED" }] }, + }); + render(, { + 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(name).toHaveAttribute("aria-invalid", "true")); + + expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled(); + expect(fetcher).toHaveBeenCalledTimes(1); + }); }); diff --git a/tests/integration/http-client.test.ts b/tests/integration/http-client.test.ts index d20c8622..bea16586 100644 --- a/tests/integration/http-client.test.ts +++ b/tests/integration/http-client.test.ts @@ -674,19 +674,28 @@ describe("paired backend 400 VALIDATION_FAILED", () => { expect(JSON.stringify(result)).not.toContain("raw backend copy"); }); + // 1101/14.4. The backend raises every VALIDATION_FAILED while it binds the + // request, before it writes (frontend contract 6.1, backend 5786126c), so + // it is not applied whatever its details are. BAD_PARAMETER can come from + // any layer, after a write too. it.each([ // A body that did not parse: details names the cause, not a field. - { code: "VALIDATION_FAILED", details: { cause: "JsonParseException" } }, - { code: "VALIDATION_FAILED", details: undefined }, - { code: "BAD_PARAMETER", details: { parameter: "limit" } }, - ])("keeps a 400 $code with details $details as before", async ({ code, details }) => { - const result = await answer400(code, details); + { code: "VALIDATION_FAILED", details: { cause: "JsonParseException" }, effect: "NOT_APPLIED" }, + { code: "VALIDATION_FAILED", details: undefined, effect: "NOT_APPLIED" }, + // A page or sort parameter: one {field, code}, not a list. + { code: "VALIDATION_FAILED", details: { field: "size", code: "MAX" }, effect: "NOT_APPLIED" }, + { code: "BAD_PARAMETER", details: { parameter: "limit" }, effect: undefined }, + ])( + "reads a 400 $code with details $details as a client failure, effect $effect", + async ({ code, details, effect }) => { + const result = await answer400(code, details); - expect(result).toMatchObject({ - ok: false, - error: { kind: "UNKNOWN_CLIENT_FAILURE", code, httpStatus: 400 }, - }); - expect(result.ok ? null : result.error.validationIssues).toBeUndefined(); - expect(result.ok ? null : result.error.effect).toBeUndefined(); - }); + expect(result).toMatchObject({ + ok: false, + error: { kind: "UNKNOWN_CLIENT_FAILURE", code, httpStatus: 400 }, + }); + expect(result.ok ? null : result.error.validationIssues).toBeUndefined(); + expect(result.ok ? null : result.error.effect).toBe(effect); + }, + ); }); diff --git a/tests/integration/http-diagnostics.test.ts b/tests/integration/http-diagnostics.test.ts index cc175c76..5c60fd91 100644 --- a/tests/integration/http-diagnostics.test.ts +++ b/tests/integration/http-diagnostics.test.ts @@ -256,8 +256,9 @@ describe("HTTP diagnostics and terminal telemetry", () => { ); it.each([ - // A field validation refusal is not applied, but names no idempotency cause. - { status: 422, code: "INVALID_INPUT", effect: "NOT_APPLIED" }, + // 1101/14.4. Only IDEMPOTENT_REQUEST_MISMATCH is a 422 refused before a + // write (frontend contract 6.1); fileserver's 422s come after one. + { status: 422, code: "INVALID_INPUT", effect: undefined }, // Any other refusal keeps no effect: the coordinator holds it as unknown. { status: 409, code: "SOMETHING_NEW", effect: undefined }, ])("gives an unrelated $status $code no reason", async ({ status, code, effect }) => { diff --git a/tests/integration/http-execution-v3-envelope.test.ts b/tests/integration/http-execution-v3-envelope.test.ts index 99c9b5c0..b945c43b 100644 --- a/tests/integration/http-execution-v3-envelope.test.ts +++ b/tests/integration/http-execution-v3-envelope.test.ts @@ -157,15 +157,14 @@ const CREATE_CONTRACT = Object.freeze({ EnvelopeProblem >; -/** A package that reads every 409 as a domain conflict refused untouched. */ -const CREATE_CONFLICT_NOT_APPLIED_CONTRACT = Object.freeze({ +/** A package that reads every problem as refused untouched. */ +const CREATE_LENIENT_CONTRACT = Object.freeze({ ...CREATE_CONTRACT, contract: Object.freeze({ ...CREATE_CONTRACT.contract, commandEffect: Object.freeze({ successEffect: "APPLIED_CONFIRMED" as const, - classifyProblem: ({ status }: Readonly<{ status: number }>) => - status === 409 || status === 503 ? "NOT_APPLIED" : "MAYBE_APPLIED", + classifyProblem: () => "NOT_APPLIED" as const, }) satisfies CommandEffectDescriptor, }), }); @@ -188,9 +187,9 @@ const OPERATIONS = Object.freeze({ }), }); -const CONFLICT_OPERATIONS = Object.freeze({ +const LENIENT_OPERATIONS = Object.freeze({ ENVELOPE_CREATE_ITEM: defineFeatureHttpOperation({ - contract: CREATE_CONFLICT_NOT_APPLIED_CONTRACT, + contract: CREATE_LENIENT_CONTRACT, routeId: "ENVELOPE_ROUTE", mapSuccess: (value) => mappingSuccess(value), }), @@ -538,7 +537,7 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () => }, ], [ - "400 VALIDATION_FAILED without a field list", + "400 VALIDATION_FAILED for an unreadable body", { status: 400, body: failure("VALIDATION_FAILED", "VALIDATION", false, { @@ -546,10 +545,32 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () => }), }, ], + [ + "400 VALIDATION_FAILED without details", + { status: 400, body: failure("VALIDATION_FAILED", "VALIDATION", false) }, + ], + [ + "400 VALIDATION_FAILED for a page parameter", + { + status: 400, + body: failure("VALIDATION_FAILED", "VALIDATION", false, { + field: "size", + code: "MAX", + }), + }, + ], + [ + "400 BAD_PARAMETER", + { status: 400, body: failure("BAD_PARAMETER", "VALIDATION", false) }, + ], [ "409 domain conflict", { status: 409, body: failure("RESOURCE_CONFLICT", "CONFLICT", false) }, ], + [ + "422 INTEGRITY_MISMATCH", + { status: 422, body: failure("INTEGRITY_MISMATCH", "VALIDATION", false) }, + ], ]; it.each(cases)("%s", async (_label, response) => { @@ -591,10 +612,35 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () => effect: "NOT_APPLIED", validationIssues: [{ path: "name", code: "NOT_BLANK" }], }); + // 1101/14.4. Every VALIDATION_FAILED is raised before a write. + for (const label of [ + "400 VALIDATION_FAILED for an unreadable body", + "400 VALIDATION_FAILED without details", + "400 VALIDATION_FAILED for a page parameter", + ]) { + await expect(read(byLabel.get(label)!)).resolves.toMatchObject({ + kind: "UNKNOWN_CLIENT_FAILURE", + code: "VALIDATION_FAILED", + effect: "NOT_APPLIED", + }); + } + // Codes the backend can raise after a write. + for (const label of [ + "400 BAD_PARAMETER", + "409 domain conflict", + "422 INTEGRITY_MISMATCH", + ]) { + await expect(read(byLabel.get(label)!)).resolves.toMatchObject({ + effect: "MAYBE_APPLIED", + }); + } }); - it("keeps an in-flight 409 and an idempotency 503 uncertain even when the package calls them not applied", async () => { - const conflict = createFeatureHttpBinding(v3Executor(), CONFLICT_OPERATIONS); + // 1101/14.4. For an Envelope operation the table decides 400, 409 and 422 + // (frontend contract 6.1) and 503 IDEMPOTENCY_UNAVAILABLE; the package + // classifies every other status. + it("keeps 400, 409, 422 outside the table and an idempotency 503 uncertain even when the package calls them not applied", async () => { + const conflict = createFeatureHttpBinding(v3Executor(), LENIENT_OPERATIONS); answer( "post", "/api/envelope-items", @@ -615,10 +661,24 @@ describe("V3 Envelope verdicts equal the V2 client's for the same answer", () => effect: "MAYBE_APPLIED", }); - // A domain 409 is the package's to classify. answer("post", "/api/envelope-items", failure("RESOURCE_CONFLICT", "CONFLICT", false), { status: 409, }); + await expect(v3CreateFailure(conflict)).resolves.toMatchObject({ + effect: "MAYBE_APPLIED", + }); + + answer("post", "/api/envelope-items", failure("BAD_PARAMETER", "VALIDATION", false), { + status: 400, + }); + await expect(v3CreateFailure(conflict)).resolves.toMatchObject({ + effect: "MAYBE_APPLIED", + }); + + // A 404 is the package's to classify. + answer("post", "/api/envelope-items", failure("NOT_FOUND", "NOT_FOUND", false), { + status: 404, + }); await expect(v3CreateFailure(conflict)).resolves.toMatchObject({ effect: "NOT_APPLIED", });