diff --git a/src/adapters/http/client.ts b/src/adapters/http/client.ts index 45eebf80..209f9c7b 100644 --- a/src/adapters/http/client.ts +++ b/src/adapters/http/client.ts @@ -873,8 +873,9 @@ async function parseResponse( now: number, ): Promise { // R3-1. Retry-After is read only where the retry policy honors it; 502/504 - // keep the local backoff. - const retryAfterMs = [408, 425, 429, 503].includes(response.status) + // keep the local backoff. 백엔드 1101/02-01: a 409 is never retried here, + // but a same-key resend after it waits on its Retry-After. + const retryAfterMs = [408, 409, 425, 429, 503].includes(response.status) ? (parseRetryAfterDelay(response.headers.get("retry-after"), now) ?? undefined) : undefined; diff --git a/src/adapters/http/feature-http-binding.ts b/src/adapters/http/feature-http-binding.ts index f91b10e7..7f967c9e 100644 --- a/src/adapters/http/feature-http-binding.ts +++ b/src/adapters/http/feature-http-binding.ts @@ -375,6 +375,10 @@ function projectOutcome( mapped?.code ?? "CONTRACT_PROBLEM", { httpStatus: outcome.metadata.status, + // 백엔드 1101/02-01. A resend of an unknown answer waits on it. + ...(outcome.metadata.retryAfterMs === undefined + ? {} + : { retryAfterMs: outcome.metadata.retryAfterMs }), effect: outcome.effect, ...(mapped?.validationIssues === undefined ? {} diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 49ca0c1a..081f240b 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -271,6 +271,8 @@ type MutationAdmission = { intent: MutationIntent | null; /** Held while UNKNOWN so the same input keeps the same identity token. */ identityLease: Readonly<{ release(): void }> | null; + /** `performance.now()` before which a resend waits (see RESEND_WAIT_CEILING_MS). */ + resendNotBefore: number; scope: CacheScopeSnapshot | null; optimisticLayer: OptimisticLayerLease | null; optimisticQueryKey: readonly unknown[] | null; @@ -296,6 +298,17 @@ type UnknownEffectRegistry = { activeAdmissions: number; }; +/** + * 백엔드 1101/02-01. An unknown answer may say when to ask again: the paired + * backend answers a same-key request while the first still runs with + * `409 IDEMPOTENT_IN_FLIGHT` and `Retry-After: 2`. A resend (the resend + * button, or saving the same input) before then only meets the same 409, so + * it waits, shown as pending. The wait is capped: an early resend carries the + * same key, so the server answers it again and never applies it twice. + * Same ceiling as the V3 executor's own Retry-After retries. + */ +const RESEND_WAIT_CEILING_MS = 5_000; + const LEGACY_OPTIMISTIC_SCOPE = Object.freeze({ isCurrent: () => true, }); @@ -544,6 +557,7 @@ export function useApplicationMutation( input, intent: null, identityLease: null, + resendNotBefore: 0, scope: scope ?? null, optimisticLayer: null, optimisticQueryKey: optimistic?.queryKey ?? null, @@ -601,6 +615,13 @@ export function useApplicationMutation( admission.optimisticLayer = optimisticLayer; } + const resendWaitMs = + (replayed?.resendNotBefore ?? 0) - performance.now(); + if (resendWaitMs > 0) { + await new Promise((resolve) => { + setTimeout(resolve, resendWaitMs); + }); + } let value: Value; try { value = await mutation.mutateAsync(execution); @@ -634,6 +655,9 @@ export function useApplicationMutation( optimisticLayer?.markUncertain(); if (!scope || scope.isCurrent()) { admission.state = "UNKNOWN"; + admission.resendNotBefore = + performance.now() + + Math.min(failure.retryAfterMs ?? 0, RESEND_WAIT_CEILING_MS); if (identityLease) { identityLease.acquire(); admission.identityLease = identityLease; diff --git a/tests/component/application-mutation-admission.test.tsx b/tests/component/application-mutation-admission.test.tsx index 2ddfabfa..5f386dc6 100644 --- a/tests/component/application-mutation-admission.test.tsx +++ b/tests/component/application-mutation-admission.test.tsx @@ -408,12 +408,14 @@ describe("application mutation intent admission", () => { ) { const client = queryClient(); const intents: MutationIntent[] = []; + const sentAt: number[] = []; const execute = vi.fn( async ( input: string, context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>, ): Promise> => { intents.push(context.intent); + sentAt.push(performance.now()); return outcomes.shift() ?? { ok: true, value: input }; }, ); @@ -433,7 +435,7 @@ describe("application mutation intent admission", () => { }), { wrapper: wrapper(client) }, ); - return { hook, intents, execute }; + return { hook, intents, execute, sentAt }; } const unknown: ApplicationResult = { @@ -511,5 +513,51 @@ describe("application mutation intent admission", () => { expect(resent).toBeNull(); expect(execute).toHaveBeenCalledTimes(3); }); + + // 백엔드 1101/02-01. The paired backend answers a same-key request while + // the first still runs with 409 IDEMPOTENT_IN_FLIGHT and Retry-After. + it("holds a resend until the Retry-After of the unknown answer", async () => { + const inFlight: ApplicationResult = { + ok: false, + error: createFailure("CONFLICT", "CREATE_REPLAYED", 0, { + code: "IDEMPOTENT_IN_FLIGHT", + effect: "MAYBE_APPLIED", + retryAfterMs: 300, + }), + }; + const { hook, intents, sentAt } = renderKeyedCreate([inFlight]); + await act(() => hook.result.current.submit("same-input")); + + await act(async () => { + await hook.result.current.resendUnknownEffect(); + }); + + expect(intents[1]).toBe(intents[0]); + expect((sentAt[1] ?? 0) - (sentAt[0] ?? 0)).toBeGreaterThanOrEqual(290); + }); + + it("waits at most the resend ceiling for a long Retry-After", async () => { + const inFlight: ApplicationResult = { + ok: false, + error: createFailure("CONFLICT", "CREATE_REPLAYED", 0, { + code: "IDEMPOTENT_IN_FLIGHT", + effect: "MAYBE_APPLIED", + retryAfterMs: 3_600_000, + }), + }; + const { hook, sentAt } = renderKeyedCreate([inFlight]); + await act(() => hook.result.current.submit("same-input")); + vi.useFakeTimers({ toFake: ["setTimeout"] }); + try { + await act(async () => { + const resent = hook.result.current.resendUnknownEffect(); + await vi.advanceTimersByTimeAsync(5_000); + await resent; + }); + expect(sentAt).toHaveLength(2); + } finally { + vi.useRealTimers(); + } + }); }); }); 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 2330d1e8..6ead51b4 100644 --- a/tests/features/reference-feature/reference-http-problem-mapping.test.ts +++ b/tests/features/reference-feature/reference-http-problem-mapping.test.ts @@ -19,6 +19,35 @@ function executorReturning( } describe("reference HTTP business problem mapping", () => { + // 백엔드 1101/02-01. The resend waits on this value. + it("carries the Retry-After of an in-flight 409 onto the unknown failure", async () => { + const executor = executorReturning( + Object.freeze({ + kind: "PROBLEM", + problem: Object.freeze({ + type: "https://api.test/problems/idempotent_in_flight", + title: "IDEMPOTENT_IN_FLIGHT", + status: 409, + code: "IDEMPOTENT_IN_FLIGHT", + }), + metadata: Object.freeze({ status: 409, retryAfterMs: 2_000 }), + effect: "MAYBE_APPLIED", + }), + ); + const gateway = createReferenceHttpGateway( + createFeatureHttpBinding(executor, REFERENCE_HTTP_OPERATIONS), + ); + + await expect(gateway.create({ name: "n" })).resolves.toMatchObject({ + ok: false, + error: { + code: "IDEMPOTENT_IN_FLIGHT", + effect: "MAYBE_APPLIED", + retryAfterMs: 2_000, + }, + }); + }); + it("maps a typed 409 reference problem to the feature-owned business code", async () => { const executor = executorReturning( Object.freeze({ diff --git a/tests/features/reference-feature/reference-production-vertical.test.tsx b/tests/features/reference-feature/reference-production-vertical.test.tsx index 65534958..685119e4 100644 --- a/tests/features/reference-feature/reference-production-vertical.test.tsx +++ b/tests/features/reference-feature/reference-production-vertical.test.tsx @@ -211,6 +211,7 @@ describe("reference feature production vertical path", () => { it("keeps the key when the resend meets the first attempt still in flight (0929/03-01)", async () => { const user = userEvent.setup(); const idempotencyKeys: (string | null)[] = []; + const sentAt: number[] = []; // A server that deduplicates by key: one receipt per created resource. const receipts = new Map>(); let firstAttemptRunning = true; @@ -218,11 +219,13 @@ describe("reference feature production vertical path", () => { http.post("https://api.test/api/reference-resources", async ({ request }) => { const key = request.headers.get("idempotency-key") ?? ""; idempotencyKeys.push(key); + sentAt.push(performance.now()); const receipt = receipts.get(key); if (receipt) { if (firstAttemptRunning) { // The paired backend answers a same-key request while the first - // attempt still runs with 409 IDEMPOTENT_IN_FLIGHT. + // attempt still runs with 409 IDEMPOTENT_IN_FLIGHT and + // Retry-After (2 there; 1 here to keep the test short). firstAttemptRunning = false; return HttpResponse.json( { @@ -233,7 +236,10 @@ describe("reference feature production vertical path", () => { }, { status: 409, - headers: { "content-type": "application/problem+json" }, + headers: { + "content-type": "application/problem+json", + "retry-after": "1", + }, }, ); } @@ -286,12 +292,17 @@ describe("reference feature production vertical path", () => { conflict: screen.queryAllByText(/충돌/).length > 0, }; await user.click(next); - await waitFor(() => expect(idempotencyKeys).toHaveLength(3)); + await waitFor(() => expect(idempotencyKeys).toHaveLength(3), { + timeout: 3_000, + }); const [first] = idempotencyKeys; expect(idempotencyKeys).toEqual([first, first, first]); expect(receipts.size).toBe(1); expect(shownAfterInFlight).toEqual({ unknown: true, conflict: false }); + // 백엔드 1101/02-01. The click came right after the 409; the resend + // waited out its Retry-After instead of meeting the same 409 again. + expect((sentAt[2] ?? 0) - (sentAt[1] ?? 0)).toBeGreaterThanOrEqual(990); expect(await screen.findByText("저장했습니다.")).toBeVisible(); }); diff --git a/tests/integration/http-client.test.ts b/tests/integration/http-client.test.ts index 44243efe..d1a993f6 100644 --- a/tests/integration/http-client.test.ts +++ b/tests/integration/http-client.test.ts @@ -511,6 +511,48 @@ describe("shared HTTP client", () => { }); }); +// 백엔드 1101/02-01. The paired backend answers a same-key request while the +// first still runs with 409 IDEMPOTENT_IN_FLIGHT, retryable and Retry-After 2. +// The client does not resend it itself (the result is unknown); it hands the +// Retry-After to whoever resends with the same key. +it("keeps the Retry-After of an in-flight 409 without resending", async () => { + let fetched = 0; + server.use( + http.post("https://api.test/api/entities", () => { + fetched += 1; + return HttpResponse.json( + { + success: false, + error: { + code: "IDEMPOTENT_IN_FLIGHT", + category: "CONFLICT", + message: "같은 요청을 처리하고 있습니다.", + retryable: true, + }, + meta: { requestId: "request-1", traceId: "trace-1" }, + }, + { status: 409, headers: { "Retry-After": "2" } }, + ); + }), + ); + const client = testClient({ baseUrl: "https://api.test", clock }); + + await expect( + client.execute("CREATE_ENTITY", { + body: { name: "n" }, + idempotencyKey: "key-1", + }), + ).resolves.toMatchObject({ + ok: false, + error: { + kind: "CONFLICT", + code: "IDEMPOTENT_IN_FLIGHT", + retryAfterMs: 2_000, + }, + }); + expect(fetched).toBe(1); +}); + // 백엔드 1101/02-02. The paired backend drops a null field together with its // key (its docs/web/http-contract.md §1). A missing key must read as the null // it stands for.