diff --git a/docs/operations/api-contract-and-server-state-recovery.md b/docs/operations/api-contract-and-server-state-recovery.md index ba60984a..a1d36e24 100644 --- a/docs/operations/api-contract-and-server-state-recovery.md +++ b/docs/operations/api-contract-and-server-state-recovery.md @@ -256,6 +256,10 @@ diagnostics에만 남고 `api.request.failed`에는 세지 않는다(03-07). 그 다시 보내기"는 그 intent와 같은 `Idempotency-Key`로 보낸다. 입력이 바뀌면 새 key다. 자동 재전송은 없다(`src/presentation/adapters/query/application-query.ts` `submit`·`resendUnknownEffect`, 화면 `src/presentation/components/async-surface.tsx`). + 다시 보낸 요청이 쓰기 전에 거절되거나(429, 503 `RATE_LIMIT_*`, 401) 보내지 못하면 + (`NOT_STARTED`) 그 시도만 적용되지 않은 것이다. 결과 불명과 key는 그대로다. 폼은 + "잠시 뒤 같은 요청으로 다시 보내 주세요"를 보이고 저장을 받지 않는다. 401은 다시 + 로그인 안내가 먼저다(1106/03-01, `use-app-form.ts` `resendUnknown`). 키가 없는 command(`NEVER`)는 서버가 두 번째 요청을 가려내지 못하므로 재전송 버튼을 그리지 않는다(`canResendUnknownEffect`, 0929/03-03). 같은 canonical input의 재저장도 보내지 않는다. 훅의 `submit`이 `NOT_STARTED` `DUPLICATE_IN_FLIGHT`(code diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 49750c6c..28b9b749 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -264,7 +264,10 @@ type ApplicationMutationController = Readonly<{ * intent, so a keyed command carries the same `Idempotency-Key`. Resolves * to `null` when nothing is waiting to be resent, and (0929/03-03) when * that request has no key: the server could not tell a second one from a - * new request, so it could apply twice. + * new request, so it could apply twice. 1106/03-01. A resend that ends + * `NOT_APPLIED` or `NOT_STARTED` resolves to that failure and leaves the + * request unknown with its key; only success or `APPLIED_CONFIRMED` + * settles it. */ resendUnknownEffect(): Promise | null>; /** @@ -605,6 +608,24 @@ export function useApplicationMutation( notifyUnknownEffectChannel(unknownEffectChannel); setConflict(null); mutation.reset(); + const holdUnknown = (retryAfterMs: number | undefined): void => { + admission.state = "UNKNOWN"; + admission.resendNotBefore = + performance.now() + + Math.min(retryAfterMs ?? 0, RESEND_WAIT_CEILING_MS); + if (identityLease) { + identityLease.acquire(); + admission.identityLease = identityLease; + } + notifyUnknownEffectChannel(unknownEffectChannel); + }; + // 1106/03-01. A resend of an unknown request that is refused before + // the write (429, the edge's 503 RATE_LIMIT_*) or never sent shows only + // that this attempt did not apply; the first may have. The request + // stays unknown with its intent, so the next save or resend carries + // the same key, never a new one (backend http-contract.md §2). + const resendLeavesUnknown = (): boolean => + replayed !== undefined && (!scope || scope.isCurrent()); let runtimeExecution: RuntimeMutationExecution | undefined; const pending = (async (): Promise> => { @@ -666,6 +687,11 @@ export function useApplicationMutation( switch (failure.effect) { case "NOT_STARTED": case "NOT_APPLIED": + if (resendLeavesUnknown()) { + optimisticLayer?.markUncertain(); + holdUnknown(failure.retryAfterMs); + break; + } optimisticLayer?.rollback(); if (failure.kind === "CONFLICT") setConflict(failure); settleMutationAdmission(unknownEffectChannel, admission); @@ -684,15 +710,7 @@ export function useApplicationMutation( case "MAYBE_APPLIED": 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; - } - notifyUnknownEffectChannel(unknownEffectChannel); + holdUnknown(failure.retryAfterMs); } else { settleMutationAdmission(unknownEffectChannel, admission); } @@ -724,6 +742,11 @@ export function useApplicationMutation( }), "NOT_STARTED", ); + if (resendLeavesUnknown()) { + admission.optimisticLayer?.markUncertain(); + holdUnknown(undefined); + return { ok: false as const, error: failure }; + } settleMutationAdmission(unknownEffectChannel, admission); if (failure.kind === "CONFLICT") setConflict(failure); return { ok: false as const, error: failure }; diff --git a/src/presentation/forms/use-app-form.ts b/src/presentation/forms/use-app-form.ts index ef67fb2d..6b3b74b9 100644 --- a/src/presentation/forms/use-app-form.ts +++ b/src/presentation/forms/use-app-form.ts @@ -397,7 +397,10 @@ export function useAppForm< * D-1. Runs a resend of the unknown submission (for example * `mutation.resendUnknownEffect`) through the same outcome handling as a * submit. The form never builds a new command here: the caller resends the - * original request with its original key. + * original request with its original key. 1106/03-01. A resend refused + * before the write (429, 503 `RATE_LIMIT_*`) or never sent leaves the + * result unknown: the form keeps the submission, so a save does not go + * out as a new request, and asks for the same request again later. */ const resendUnknown = useCallback( ( @@ -410,7 +413,15 @@ export function useAppForm< setPending(true); try { const outcome = await send(); - if (outcome) applyOutcome(outcome, submittedValues); + if (outcome && resendLeftUnknown(outcome)) { + focusFeedbackRef.current = true; + unknownSubmissionRef.current = submittedValues; + setFieldErrors({} as FieldErrors); + setFormErrors(["form.resendLater"]); + setResult("effect-unknown"); + } else if (outcome) { + applyOutcome(outcome, submittedValues); + } return outcome; } finally { setPending(false); @@ -486,6 +497,20 @@ function refusalFor( : undefined; } +/** + * 1106/03-01. The resend did not reach the write: the request it repeats is + * still unknown, and the mutation coordinator keeps its key. Signing in again + * still comes first (D-2). + */ +function resendLeftUnknown(outcome: FormResult): boolean { + return ( + !outcome.ok && + (outcome.error.effect === "NOT_APPLIED" || + outcome.error.effect === "NOT_STARTED") && + outcome.error.action !== "reauth" + ); +} + /** 1105/08-01. Nothing has focus: the focused element left the document. */ function focusIsLost(): boolean { const active = document.activeElement; diff --git a/src/presentation/i18n/catalog.ts b/src/presentation/i18n/catalog.ts index ccbf460e..edf02ba0 100644 --- a/src/presentation/i18n/catalog.ts +++ b/src/presentation/i18n/catalog.ts @@ -152,6 +152,8 @@ const PLATFORM_KO_MESSAGES = { "form.validation.configuration": "입력 구성을 다시 확인해 주세요.", "form.conflict": "다른 변경과 충돌했습니다. 입력은 유지되었으니 최신 상태를 확인해 주세요.", + "form.resendLater": + "다시 보낸 요청이 처리되지 않았습니다. 잠시 뒤 같은 요청으로 다시 보내 주세요.", "form.reauthLosesInput": "다시 로그인하면 이 화면에 입력한 내용은 사라집니다. 필요하면 먼저 복사해 두세요.", "form.remaining": "{count}자 남음", @@ -356,6 +358,8 @@ const PLATFORM_EN_MESSAGES = { "form.validation.configuration": "Review the input configuration.", "form.conflict": "Another update conflicts with this change. Your input has been preserved.", + "form.resendLater": + "The request sent again was not processed. Send the same request again shortly.", "form.reauthLosesInput": "Signing in again clears what you entered on this page. Copy it first if you need it.", "form.remaining": "{count} characters remaining", diff --git a/tests/component/application-mutation-admission.test.tsx b/tests/component/application-mutation-admission.test.tsx index 23d0fe73..359d57f0 100644 --- a/tests/component/application-mutation-admission.test.tsx +++ b/tests/component/application-mutation-admission.test.tsx @@ -407,7 +407,14 @@ describe("application mutation intent admission", () => { function renderKeyedCreate( outcomes: ApplicationResult[], - options: Readonly<{ maxIdentities?: number; keyed?: boolean }> = {}, + options: Readonly<{ + maxIdentities?: number; + keyed?: boolean; + optimistic?: Readonly<{ + queryKey: readonly unknown[]; + update(previous: unknown, input: string): unknown; + }>; + }> = {}, ) { const client = queryClient(); const intents: MutationIntent[] = []; @@ -435,6 +442,9 @@ describe("application mutation intent admission", () => { scope, execute, invalidate: [], + ...(options.optimistic === undefined + ? {} + : { optimistic: options.optimistic }), }), { wrapper: wrapper(client) }, ); @@ -647,5 +657,101 @@ describe("application mutation intent admission", () => { vi.useRealTimers(); } }); + + // 1106/03-01. A same-key resend refused before the write (429, the + // edge's 503 RATE_LIMIT_*) or never sent says nothing about the first + // request, which may have applied. It stays unknown, and the next save + // carries its key, not a new one (review experiment 03-R1 X1-X3: keys + // key-1, key-1, key-2). + it.each([ + [ + "refused by the edge's 503 RATE_LIMIT_UNAVAILABLE", + createFailure("SERVER_FAILURE", "CREATE_REPLAYED", 0, { + code: "RATE_LIMIT_UNAVAILABLE", + httpStatus: 503, + effect: "NOT_APPLIED", + }), + ], + [ + "refused with 429", + createFailure("RATE_LIMITED", "CREATE_REPLAYED", 0, { + code: "RATE_LIMIT_EXCEEDED", + httpStatus: 429, + effect: "NOT_APPLIED", + }), + ], + [ + "not sent", + createFailure("NETWORK_UNREACHABLE", "CREATE_REPLAYED", 0, { + effect: "NOT_STARTED", + }), + ], + ])("keeps the request unknown with its key when the resend is %s", async (_label, refusal) => { + const { hook, intents } = renderKeyedCreate([ + unknown, + { ok: false, error: refusal }, + ]); + await act(() => hook.result.current.submit("same-input")); + + let resent: ApplicationResult | null | undefined; + await act(async () => { + resent = await hook.result.current.resendUnknownEffect(); + }); + + expect(resent).toMatchObject({ + ok: false, + error: { kind: refusal.kind, effect: refusal.effect }, + }); + expect(hook.result.current.state.indicator).toBe( + "mutation-effect-unknown", + ); + expect(hook.result.current.canResendUnknownEffect).toBe(true); + + await act(() => hook.result.current.submit("same-input")); + + expect(intents.map((intent) => intent.idempotencyKey)).toEqual([ + "key-1", + "key-1", + "key-1", + ]); + }); + + // 1106/03-01. The same when the resend fails in the coordinator itself + // before anything is sent (here the page's optimistic update throws). + it("keeps the request unknown with its key when the resend fails before sending", async () => { + let projectionBroken = false; + const { hook, intents } = renderKeyedCreate([unknown], { + optimistic: { + queryKey: ["resource", "replayed-projection"], + update: (_previous, input) => { + if (projectionBroken) throw new Error("projection defect"); + return [input]; + }, + }, + }); + await act(() => hook.result.current.submit("same-input")); + + projectionBroken = true; + let resent: ApplicationResult | null | undefined; + await act(async () => { + resent = await hook.result.current.resendUnknownEffect(); + }); + + expect(resent).toMatchObject({ + ok: false, + error: { effect: "NOT_STARTED" }, + }); + expect(hook.result.current.state.indicator).toBe( + "mutation-effect-unknown", + ); + + projectionBroken = false; + await act(() => hook.result.current.submit("same-input")); + + expect(intents.map((intent) => intent.idempotencyKey)).toEqual([ + "key-1", + "key-1", + ]); + }); }); }); diff --git a/tests/component/form-foundation.test.tsx b/tests/component/form-foundation.test.tsx index cb9410ea..c97136f3 100644 --- a/tests/component/form-foundation.test.tsx +++ b/tests/component/form-foundation.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom -import { render, screen, waitFor } from "@testing-library/react"; +import { fireEvent, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { useState } from "react"; import { createMemoryRouter, RouterProvider, useNavigate } from "react-router-dom"; @@ -889,7 +889,12 @@ describe("correcting a field after a server validation refusal", () => { + {form.result} + {mutation.state.indicator ?? "none"} + {form.formErrors.join(" ")} ); } @@ -1141,4 +1146,71 @@ describe("correcting a field after a server validation refusal", () => { expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled(); expect(fetcher).toHaveBeenCalledTimes(1); }); + + // 1106/03-01. The answer is lost, and the same-key resend meets the edge + // rate limiter's 503 RATE_LIMIT_UNAVAILABLE, refused before the write. The + // first request may still have applied: the result stays unknown, a save + // sends nothing new, and the next resend carries the same key (review + // experiment 03-R1 X5: keys key-1, key-1, key-2). + it("keeps a lost create unknown when its resend is refused before the write", async () => { + const user = userEvent.setup(); + const fetcher = vi + .fn() + .mockRejectedValueOnce(new TypeError("Failed to fetch")) + .mockResolvedValueOnce( + Response.json( + { + success: false, + error: { + code: "RATE_LIMIT_UNAVAILABLE", + category: "TRANSIENT_DEPENDENCY", + retryable: true, + }, + meta, + }, + { status: 503 }, + ), + ) + .mockImplementation(async () => + Response.json({ + success: true, + data: { id: "entity-1", name: "Saved" }, + meta, + }), + ); + const { container } = render(, { + wrapper: wrapper(queryClient()), + }); + + await user.type(screen.getByRole("textbox", { name: /Name/ }), "Saved"); + await user.click(screen.getByRole("button", { name: "Submit" })); + await waitFor(() => + expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"), + ); + await user.click(screen.getByRole("button", { name: "Resend" })); + await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2)); + + await waitFor(() => + expect(screen.getByTestId("form-errors")).toHaveTextContent( + formatMessage("ko-KR", "form.resendLater"), + ), + ); + expect(screen.getByTestId("result")).toHaveTextContent("effect-unknown"); + expect(screen.getByTestId("indicator")).toHaveTextContent( + "mutation-effect-unknown", + ); + expect(screen.getByRole("button", { name: "Submit" })).toBeDisabled(); + // A save that reaches the form anyway (Enter in the field) sends nothing. + const form = container.querySelector("form"); + if (!form) throw new Error("expected the form"); + fireEvent.submit(form); + expect(fetcher).toHaveBeenCalledTimes(2); + + await user.click(screen.getByRole("button", { name: "Resend" })); + + await waitFor(() => + expect(screen.getByTestId("result")).toHaveTextContent("success"), + ); + expect(sentKeys(fetcher)).toEqual(["key-1", "key-1", "key-1"]); + }); });