From 93782b0fce86309cea10b2727ded71709f2aa2f0 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Tue, 3 Nov 2026 01:51:03 +0900 Subject: [PATCH] =?UTF-8?q?fix(http):=20=EB=A9=B1=EB=93=B1=EC=84=B1=20?= =?UTF-8?q?=EA=B1=B0=EC=A0=88=20422=C2=B7400=EC=9D=84=20=EC=A0=81=EC=9A=A9?= =?UTF-8?q?=20=EC=95=88=20=EB=90=A8=EC=9C=BC=EB=A1=9C=20=EB=B3=B4=EA=B3=A0?= =?UTF-8?q?=20=EC=9B=90=EC=9D=B8=EC=9D=84=20=EB=82=A8=EA=B8=B4=EB=8B=A4=20?= =?UTF-8?q?(=EB=B0=B1=EC=97=94=EB=93=9C=201101/02-01)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제 짝 백엔드는 KEYED 요청을 실행하기 전에 두 가지를 거절한다(백엔드 docs/web/http-contract.md §2). - 422 IDEMPOTENT_REQUEST_MISMATCH: 같은 키에 다른 본문. 클라이언트 버그. - 400 IDEMPOTENCY_KEY_INVALID(details.reason MISSING·MALFORMED): 키 누락· 형식 오류. 둘 다 이 요청은 적용되지 않았고, 그대로 다시 보내면 같은 답이 온다. - V2(client.ts)는 이 실패에 effect를 붙이지 않는다. mutation 코디네이터는 effect가 없으면 MAYBE_APPLIED로 보고(application-query.ts mutationFailureWithEffect) 키를 붙든다. 400은 결과 불명 화면으로 가고, 같은 입력을 다시 저장하면 같은 키로 같은 400·422를 계속 받는다. 진단 이벤트(http.request.completed)에는 원인이 없다. - V3 참조 기능은 분류기가 400·422를 이미 NOT_APPLIED로 본다. 다만 mapProblem이 400을 다루지 않아 code가 CONTRACT_PROBLEM으로 바뀌고 서버의 IDEMPOTENCY_KEY_INVALID가 사라진다. 고른 방법 - V2: 문서에 적힌 status와 code가 둘 다 맞을 때만 effect NOT_APPLIED를 붙인다(IDEMPOTENCY_REFUSALS 표). 같은 표가 진단 reason을 준다. - 422 → reason IDEMPOTENT_REQUEST_MISMATCH - 400 → reason IDEMPOTENCY_KEY_RULE_MISMATCH. 프론트는 보내기 전에 isValidIdempotencyKey로 키를 검사한다. 서버의 400은 두 키 규칙이 어긋났다는 뜻이라 그 이름으로 남긴다. 보내기 전 거절(VALIDATION_ REJECTED, httpStatus 없음)은 표에 걸리지 않는다. reason은 diagnostics에만 넣는다. telemetry 속성은 그대로다(VD-07). - V3 참조 mapProblem: 400 + IDEMPOTENCY_KEY_INVALID만 UNKNOWN_CLIENT_ FAILURE와 서버 code로 둔다. 다른 400은 기존 fallback 그대로다. - kind는 바꾸지 않았다(422 VALIDATION_REJECTED, 400 UNKNOWN_CLIENT_ FAILURE). 둘 다 retryable:false이고 V2 재시도 대상이 아니다. - 키 문법은 백엔드 IdempotencyKeyHeader([\x21-\x7E]{1,256}, trim 없음)와 같다. 1자 키를 받는 행을 더해 경계를 고정했다. 버린 대안 - code만 보고 판정: 다른 status에 같은 code가 오면 NOT_APPLIED를 잘못 붙인다. NOT_APPLIED는 다음 저장이 새 키를 쓰게 하는 판정이라 문서의 짝(status+code)만 믿는다. - 422 mismatch를 UNKNOWN_CLIENT_FAILURE로 바꾸기: 화면 문구가 바뀐다. 요구는 재전송 금지·결과 불명 화면 금지·원인 code 보존이라 kind는 두었다. - 서버 code를 진단 reason에 그대로 넣기: 서버 code는 무제한이라 진단 cardinality 규칙(taxonomy)을 깬다. 표에 있는 두 값만 넣는다. 위험·한계 - 422 mismatch를 NOT_APPLIED로 보면 다음 저장이 새 키를 쓴다. 같은 키의 앞선 요청이 적용됐을 수 있지만, 프론트는 canonical 입력이 같을 때만 키를 재사용하므로 mismatch는 지문 규칙이 어긋난 버그다. 결정(15절)대로 이번 요청은 적용되지 않았다고 본다. - 422 화면 문구는 "입력값을 다시 확인해 주세요."다. 사용자가 고칠 입력이 아니지만 다시 저장하면 새 키로 나간다. - V3 실행기의 진단은 problem code를 모른다(Problem 타입은 계약 패키지 소유). V3에서 원인은 AppFailure.code·httpStatus로만 보인다. 검증 - RED: tests/integration/http-diagnostics.test.ts 새 2행 실패(effect undefined, reason 없음). tests/features/reference-feature/reference-http- problem-mapping.test.ts 400 IDEMPOTENCY_KEY_INVALID 행 실패(code CONTRACT_PROBLEM). 422 mismatch 매핑, 분류기 2행, 1자 키 행은 처음부터 통과(이미 맞는 동작을 고정). - GREEN: 위 파일과 tests/features/reference-feature, tests/integration/ http-client·http-execution-contract·auth-recovery·legacy-http-credential- authority, tests/contract/reusable-capability/feature-http-binding 24 files 207 tests 통과. tests/unit/legacy-and-optional-network-remediation 6/6. tsc app·test 통과, 바꾼 파일 eslint 통과. Refs: clean-architecture-backend-template docs/reviews/2026-11-01-maturity-review/README.md 14.3, 15 --- src/adapters/http/client.ts | 46 +++++++++- .../adapters/reference-http-gateway.ts | 9 ++ .../reference-http-problem-mapping.test.ts | 52 +++++++++++ tests/integration/http-diagnostics.test.ts | 87 +++++++++++++++++++ ...y-and-optional-network-remediation.test.ts | 4 + 5 files changed, 196 insertions(+), 2 deletions(-) diff --git a/src/adapters/http/client.ts b/src/adapters/http/client.ts index 2db6b5ad..45eebf80 100644 --- a/src/adapters/http/client.ts +++ b/src/adapters/http/client.ts @@ -222,6 +222,8 @@ export function createHttpClient( outcomeKind: "success" | "recovered" | "failed" | "aborted", ): HttpResult { const error = outcome.ok ? undefined : outcome.error; + const reason = + error && idempotencyRefusalReason(error.code, error.httpStatus); const context = { route_id: input.routeId, operation_id: input.operationId, @@ -241,7 +243,8 @@ export function createHttpClient( diagnostics?.record({ level: error ? "warn" : "info", eventId: "http.request.completed", - context, + // Diagnostics only: telemetry below keeps its fixed attribute set. + context: reason ? { ...context, reason } : context, }); } catch { // Diagnostics cannot change the HTTP result. @@ -1005,10 +1008,14 @@ async function parseResponse( envelopeRecord.error && typeof envelopeRecord.error === "object" ? (envelopeRecord.error as Record) : {}; + const code = safeBackendCode(envelope); return { ok: false, error: failure(kind, operation.operationId, attempt, { - code: safeBackendCode(envelope), + code, + ...(idempotencyRefusalReason(code, response.status) === undefined + ? {} + : { effect: "NOT_APPLIED" as const }), httpStatus: response.status, requestId: safeMeta(envelopeRecord.meta).requestId, traceId: safeMeta(envelopeRecord.meta).traceId, @@ -1073,6 +1080,41 @@ async function recoverSession( }; } +/** + * 백엔드 1101/02-01. Refusals the paired backend answers before it runs the + * command (clean-architecture-backend-template docs/web/http-contract.md §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. + */ +const IDEMPOTENCY_REFUSALS: Readonly< + Record> +> = Object.freeze({ + // The same key went out with another body. + IDEMPOTENT_REQUEST_MISMATCH: Object.freeze({ + status: 422, + reason: "IDEMPOTENT_REQUEST_MISMATCH", + }), + // `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", + }), +}); + +function idempotencyRefusalReason( + code: string, + status: number | undefined, +): string | undefined { + const refusal = Object.hasOwn(IDEMPOTENCY_REFUSALS, code) + ? IDEMPOTENCY_REFUSALS[code] + : undefined; + return refusal !== undefined && refusal.status === status + ? refusal.reason + : undefined; +} + function safeBackendCode(envelope: unknown): string { if (!envelope || typeof envelope !== "object") return "HTTP_FAILURE"; const error = (envelope as Record).error; diff --git a/src/features/reference-feature/adapters/reference-http-gateway.ts b/src/features/reference-feature/adapters/reference-http-gateway.ts index 12ebc8f4..152be19c 100644 --- a/src/features/reference-feature/adapters/reference-http-gateway.ts +++ b/src/features/reference-feature/adapters/reference-http-gateway.ts @@ -41,6 +41,15 @@ export const REFERENCE_HTTP_OPERATIONS = Object.freeze({ code: problem.code ?? "REFERENCE_RESOURCE_CONFLICT", }); } + // 백엔드 1101/02-01. The paired backend's answer to a key outside its + // rule. The executor checked the key before sending, so this names a + // rule mismatch between the two sides: keep the code for diagnostics. + if (metadata.status === 400 && problem.code === "IDEMPOTENCY_KEY_INVALID") { + return Object.freeze({ + kind: "UNKNOWN_CLIENT_FAILURE" as const, + code: problem.code, + }); + } if (metadata.status === 422) { return Object.freeze({ kind: "VALIDATION_REJECTED" as const, diff --git a/tests/features/reference-feature/reference-http-problem-mapping.test.ts b/tests/features/reference-feature/reference-http-problem-mapping.test.ts index 972e68a2..2330d1e8 100644 --- a/tests/features/reference-feature/reference-http-problem-mapping.test.ts +++ b/tests/features/reference-feature/reference-http-problem-mapping.test.ts @@ -107,6 +107,54 @@ describe("reference HTTP business problem mapping", () => { }, ); + // 백엔드 1101/02-01. The paired backend refuses both before it runs the + // command (its docs/web/http-contract.md §2). The failure keeps the cause + // code and does not invite a resend. + it.each([ + { + status: 422, + code: "IDEMPOTENT_REQUEST_MISMATCH", + expectedKind: "VALIDATION_REJECTED", + }, + { + // The executor checked the key before sending: the two rules disagree. + status: 400, + code: "IDEMPOTENCY_KEY_INVALID", + expectedKind: "UNKNOWN_CLIENT_FAILURE", + }, + ] as const)( + "keeps the paired backend's $status $code as a not-applied failure", + async ({ status, code, expectedKind }) => { + const executor = executorReturning( + Object.freeze({ + kind: "PROBLEM", + problem: Object.freeze({ + type: "https://api.test/problems/" + code.toLowerCase(), + title: code, + status, + code, + }), + metadata: Object.freeze({ status }), + effect: "NOT_APPLIED", + }), + ); + const gateway = createReferenceHttpGateway( + createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), + ); + + await expect(gateway.create({ name: "n" })).resolves.toMatchObject({ + ok: false, + error: { + kind: expectedKind, + code, + httpStatus: status, + effect: "NOT_APPLIED", + retryable: false, + }, + }); + }, + ); + it("keeps the platform status fallback when the operation has no problem mapper", async () => { const executor = executorReturning( Object.freeze({ @@ -157,6 +205,10 @@ describe("reference create problem effect classification (0929/03-01)", () => { { status: 409, code: "CONFLICT", effect: "NOT_APPLIED" }, { status: 400, code: undefined, effect: "NOT_APPLIED" }, { status: 422, code: "VALIDATION_REJECTED", effect: "NOT_APPLIED" }, + // 백엔드 1101/02-01. Refused before the command ran: this request was + // not applied, so the next save may mint a new key. + { status: 422, code: "IDEMPOTENT_REQUEST_MISMATCH", effect: "NOT_APPLIED" }, + { status: 400, code: "IDEMPOTENCY_KEY_INVALID", effect: "NOT_APPLIED" }, { status: 404, code: "NOT_FOUND", effect: "MAYBE_APPLIED" }, { status: 503, code: "SERVER_FAILURE", effect: "MAYBE_APPLIED" }, ] as const)( diff --git a/tests/integration/http-diagnostics.test.ts b/tests/integration/http-diagnostics.test.ts index 7c361a3d..96a33996 100644 --- a/tests/integration/http-diagnostics.test.ts +++ b/tests/integration/http-diagnostics.test.ts @@ -190,4 +190,91 @@ describe("HTTP diagnostics and terminal telemetry", () => { }); expect(emitted).toEqual([]); }); + + // 백엔드 1101/02-01. The paired backend refuses these before it runs the + // command (its docs/web/http-contract.md §2): not applied, not resent, and + // diagnostics name the cause. + it.each([ + { + status: 422, + code: "IDEMPOTENT_REQUEST_MISMATCH", + kind: "VALIDATION_REJECTED", + details: undefined, + reason: "IDEMPOTENT_REQUEST_MISMATCH", + }, + { + status: 400, + code: "IDEMPOTENCY_KEY_INVALID", + kind: "UNKNOWN_CLIENT_FAILURE", + details: { reason: "MALFORMED" }, + // This client checked the key before sending, so the two rules disagree. + reason: "IDEMPOTENCY_KEY_RULE_MISMATCH", + }, + ])( + "reports a $status $code as not applied, sent once, with reason $reason", + async ({ status, code, kind, details, reason }) => { + const fetcher = vi.fn(async () => + Response.json( + { + success: false, + error: { + code, + category: "VALIDATION", + message: "요청을 처리할 수 없습니다.", + retryable: false, + ...(details === undefined ? {} : { details }), + }, + meta: { requestId: "request-1", traceId: "trace-1" }, + }, + { status }, + ), + ); + const { client, records } = harness(fetcher); + + await expect( + client.execute({ + operationId: "CREATE_ENTITY", + routeId: "TEST_ROUTE", + body: { name: "n" }, + idempotencyKey: "key-1", + }), + ).resolves.toMatchObject({ + ok: false, + error: { + kind, + code, + httpStatus: status, + retryable: false, + effect: "NOT_APPLIED", + }, + }); + expect(fetcher).toHaveBeenCalledTimes(1); + expect(records).toMatchObject([ + { context: { outcome: "failed", error_kind: kind, reason } }, + ]); + }, + ); + + it("keeps an unrelated 422 effect-free and reason-free", async () => { + const fetcher = vi.fn(async () => + Response.json( + { + success: false, + error: { code: "INVALID_INPUT" }, + meta: { requestId: "request-1", traceId: "trace-1" }, + }, + { status: 422 }, + ), + ); + const { client, records } = harness(fetcher); + + const result = await client.execute({ + operationId: "CREATE_ENTITY", + routeId: "TEST_ROUTE", + body: { name: "n" }, + }); + + expect(result.ok ? undefined : result.error.effect).toBeUndefined(); + expect(records[0]?.context).not.toHaveProperty("reason"); + }); }); diff --git a/tests/unit/legacy-and-optional-network-remediation.test.ts b/tests/unit/legacy-and-optional-network-remediation.test.ts index 723da17a..886c8abb 100644 --- a/tests/unit/legacy-and-optional-network-remediation.test.ts +++ b/tests/unit/legacy-and-optional-network-remediation.test.ts @@ -142,8 +142,12 @@ describe("OPT-NET-02 shared idempotency key validation", () => { } }); + // 백엔드 1101/02-01. The paired backend's IdempotencyKeyHeader grammar is + // the same: [\x21-\x7E]{1,256}, never trimmed. A key it refuses with + // 400 IDEMPOTENCY_KEY_INVALID never left this client. it("accepts the bounded visible-ASCII values both sides allow", () => { for (const value of [ + "k", "key-1", "a".repeat(256), "0f8fad5b-d9cb-469f-a165-70867728950e",