Files
clean-architecture-frontend…/tests/component/application-mutation-admission.test.tsx
T
DongHyeonka 47fec5c27c fix(query): 처리 중 409의 Retry-After 전 재전송은 그 시각까지 기다린다 (백엔드 1101/02-01)
문제
짝 백엔드는 같은 키의 첫 요청이 아직 실행 중이면 409
IDEMPOTENT_IN_FLIGHT, retryable=true, Retry-After: 2를 준다(백엔드
docs/web/http-contract.md §2). 클라이언트 행동은 "같은 키로 Retry-After 뒤
재전송"이다.
- 같은 키: 0929/03-01이 이 409를 MAYBE_APPLIED로 두어 코디네이터가 intent를
  붙든다. 재전송은 같은 키를 쓴다(기존 vertical 테스트가 [K, K, K]를
  고정). 이 부분은 이미 맞다.
- Retry-After: 지키지 않는다. V3는 응답 metadata에 retryAfterMs를 읽지만
  feature binding이 PROBLEM을 AppFailure로 옮길 때 버린다. V2는 409의
  Retry-After를 읽지 않는다. 그래서 결과 불명 화면의 "같은 요청으로 다시
  보내기"(또는 같은 입력 다시 저장)를 바로 누르면 즉시 나가서 같은 409를
  한 번 더 받는다.

고른 방법
재전송이 그 시각 전이면 기다렸다 보낸다.
- feature binding이 PROBLEM의 metadata.retryAfterMs를 AppFailure에 싣는다.
  V2는 409의 Retry-After도 읽는다(409는 여전히 자동 재시도하지 않는다).
- mutation 코디네이터(application-query.ts)가 MAYBE_APPLIED로 남기는
  admission에 resendNotBefore = 지금 + min(retryAfterMs, 5초)를 적는다.
  같은 intent를 다시 쓰는 submit(재전송 버튼, 같은 입력 저장)이 그 시각까지
  기다린 뒤 보낸다. 기다리는 동안 admission이 ACTIVE라 화면은 pending이다.
  scope가 바뀌면 기존 mutationFn 검사가 NOT_STARTED로 막는다.
- 상한 5초는 V3 실행기의 Retry-After 상한(RETRY_AFTER_CEILING_MS)과 같다.
  더 일찍 보내도 같은 키라 서버가 다시 409를 줄 뿐 두 번 적용하지 않으므로,
  긴 Retry-After를 다 기다리게 하지 않는다.

버린 대안
- Retry-After 전에는 버튼을 막기: 화면과 시각 회귀 골든이 바뀌고, 다시
  열어 줄 타이머와 문구가 더 든다. 기다렸다 보내는 쪽이 변경이 작다.
- V3 실행기가 키별 "이 시각 전 금지" 표를 들기: 실행기에 키를 기억하는
  상태와 정리 규칙이 생긴다. 재전송을 만드는 곳은 코디네이터 하나다.
- 그대로 두기(이른 재전송은 409를 한 번 더 받을 뿐): 서버 문서가 허용하는
  동작이지만 사용자는 같은 결과 불명 화면을 한 번 더 본다. 요구는
  Retry-After를 지키는 것이다.

위험·한계
- AppFailure.retryAfterMs가 V3 PROBLEM에도 실린다(추가 필드). 이 값을 읽는
  곳은 코디네이터뿐이다.
- 기다림은 MAYBE_APPLIED로 남은 admission을 다시 보낼 때만 생긴다. 다른
  상태(NOT_APPLIED 등)는 그대로다.
- 시계는 performance.now(), 대기는 setTimeout이다. 탭이 백그라운드면
  브라우저가 타이머를 늦출 수 있다(더 늦게 보낼 뿐이다).

검증
- RED: 4행 실패.
  - tests/features/reference-feature/reference-production-vertical.test.tsx
    처리 중 409(Retry-After: 1) 뒤 재전송 간격 39.7ms(기대 990ms 이상)
  - tests/component/application-mutation-admission.test.tsx 재전송이
    retryAfterMs 300을 기다리지 않음
  - tests/features/reference-feature/reference-http-problem-mapping.test.ts
    retryAfterMs 없음
  - tests/integration/http-client.test.ts V2 409 retryAfterMs 없음
  상한 행은 수정 전에도 통과하고, 상한을 뺀 변이에서 시간 초과로 실패하는
  것을 확인했다.
- GREEN: 위 행 모두 통과. tests/component·features·contract/reusable-
  capability, tests/integration/http-client·http-diagnostics, tests/unit/
  http-execution-v3 62 files 491 tests 통과. tsc app·test 통과, 바꾼 파일
  eslint 통과.

Refs: clean-architecture-backend-template docs/reviews/2026-11-01-maturity-review/README.md 14.3, 15
2026-11-03 02:00:45 +09:00

564 lines
19 KiB
TypeScript

// @vitest-environment jsdom
import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import {
type ApplicationResult,
useApplicationMutation,
} from "../../src/presentation/adapters/query/application-query.ts";
import type { MutationIntentFactory } from "../../src/application/ports/mutation-intent-factory.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import type { MutationIntent } from "../../src/contracts/mutation-intent.ts";
import { createRuntimeIdentityRegistry } from "../../src/contracts/query-keys.ts";
import { MUTATION_COORDINATOR_BOUNDS } from "../../src/contracts/server-state.ts";
import {
RESOURCE_INVALIDATION_TOPIC,
deterministicMutationIntentFactory,
queryClient,
scopeSnapshot,
wrapper,
} from "./application-query-fixture.tsx";
import { useLegacyApplicationMutation } from "../helpers/legacy-application-query-harness.ts";
describe("application mutation intent admission", () => {
it("retains optimistic data when execute throws after dispatch begins", async () => {
const client = queryClient();
const key = ["resource", "thrown-unknown-effect"];
client.setQueryData(key, ["base"]);
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute: async () => {
throw new Error("private transport defect");
},
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome: ApplicationResult<string> | undefined;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toMatchObject({
ok: false,
error: {
effect: "MAYBE_APPLIED",
retryable: false,
action: "contact-support",
},
});
expect(JSON.stringify(outcome)).not.toContain("private transport defect");
expect(client.getQueryData(key)).toEqual(["base", "created"]);
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it("creates a distinct logical intent for each independently admitted submit", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const observedIntents: unknown[] = [];
const execute = vi.fn(
async (
input: string,
context: Readonly<{ signal: AbortSignal; intent?: unknown }>,
) => {
observedIntents.push(context.intent);
return { ok: true as const, value: input };
},
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "independent-intent-v1",
definitionVersion: 1,
operationId: "CREATE_WITH_INTENT",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "ALLOW_PARALLEL",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
await act(async () => {
await hook.result.current.submit("same-input");
await hook.result.current.submit("same-input");
});
expect(observedIntents).toHaveLength(2);
expect(observedIntents[0]).toMatchObject({
intentId: "intent-1",
operationId: "CREATE_WITH_INTENT",
idempotencyKey: "key-1",
});
expect(observedIntents[1]).toMatchObject({
intentId: "intent-2",
operationId: "CREATE_WITH_INTENT",
idempotencyKey: "key-2",
});
expect(observedIntents[0]).not.toEqual(observedIntents[1]);
});
it("creates no second intent when JOIN_IDENTICAL shares an admitted submit", async () => {
const client = queryClient();
const scope = scopeSnapshot();
const deterministicFactory = deterministicMutationIntentFactory();
const createIntent = vi.fn(deterministicFactory.create);
const factory: MutationIntentFactory = Object.freeze({
create: createIntent,
});
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "joined-intent-v1",
definitionVersion: 1,
operationId: "CREATE_JOINED",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "JOIN_IDENTICAL",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client, factory) },
);
let first: Promise<ApplicationResult<string>> | null = null;
let joined: Promise<ApplicationResult<string>> | null = null;
act(() => {
first = hook.result.current.submit("same-input");
joined = hook.result.current.submit("same-input");
});
expect(first).toBe(joined);
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
expect(createIntent).toHaveBeenCalledOnce();
expect(createIntent).toHaveBeenCalledWith({
operationId: "CREATE_JOINED",
canonicalInputIdentity:
"scope-fingerprint-0001:joined-intent-v1:scope-identity-token-0001",
requiresIdempotencyKey: true,
});
complete({ ok: true, value: "same-input" });
if (!first) throw new Error("expected admitted mutation");
await act(() => first);
});
it("bounds JOIN_IDENTICAL waiters without starting another mutation", async () => {
const client = queryClient();
const scope = scopeSnapshot();
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "joined-waiter-budget-v1",
definitionVersion: 1,
operationId: "CREATE_JOINED_BOUNDED",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "JOIN_IDENTICAL",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
let admitted: Promise<ApplicationResult<string>> | null = null;
let joined: readonly Promise<ApplicationResult<string>>[] = [];
let overflow: Promise<ApplicationResult<string>> | null = null;
act(() => {
admitted = hook.result.current.submit("same-input");
joined = Array.from(
{ length: MUTATION_COORDINATOR_BOUNDS.waitersPerJoinedIntent },
() => hook.result.current.submit("same-input"),
);
overflow = hook.result.current.submit("same-input");
});
expect(joined.every((waiter) => waiter === admitted)).toBe(true);
expect(overflow).not.toBe(admitted);
if (!overflow) throw new Error("expected overflow result");
await expect(overflow).resolves.toMatchObject({
ok: false,
error: {
kind: "DUPLICATE_IN_FLIGHT",
code: "JOIN_WAITER_LIMIT_EXCEEDED",
effect: "NOT_STARTED",
},
});
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
complete({ ok: true, value: "same-input" });
if (!admitted) throw new Error("expected admitted mutation");
await act(() => admitted);
});
it("keeps the legacy raw mutation path outside the intent factory", async () => {
const client = queryClient();
const createIntent = vi.fn<MutationIntentFactory["create"]>();
const factory: MutationIntentFactory = Object.freeze({
create: createIntent,
});
const execute = vi.fn(async (input: string) => ({
ok: true as const,
value: input,
}));
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-raw-path-v1",
execute,
}),
{ wrapper: wrapper(client, factory) },
);
await act(() => hook.result.current.submit("legacy-input"));
expect(execute).toHaveBeenCalledOnce();
expect(createIntent).not.toHaveBeenCalled();
});
// 1101/08-03. Type fixture, checked by `tsc -p tsconfig.test.json`: if the
// product hook takes a raw executor again, the directive below is unused
// (TS2578) and the type check fails. Only the harness reaches that path.
it("rejects a raw executor on the product hook at compile time", () => {
const raw = {
definitionId: "raw-product-call-v1",
execute: async (input: string) => ({ ok: true as const, value: input }),
};
const useRawProductMutation = () =>
useApplicationMutation<string, string>(
// @ts-expect-error a raw executor is not a BoundMutation.
raw,
);
expect(useRawProductMutation).toBeTypeOf("function");
});
it("rejects a duplicate submit by default while one is active", async () => {
const client = queryClient();
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-duplicate-rejection-v1",
execute,
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | null = null;
let duplicate: Promise<ApplicationResult<string>> | null = null;
act(() => {
first = hook.result.current.submit("created");
duplicate = hook.result.current.submit("created");
});
if (!first || !duplicate) throw new Error("expected two submissions");
await expect(duplicate).resolves.toMatchObject({
ok: false,
error: { kind: "DUPLICATE_IN_FLIGHT" },
});
expect(execute).toHaveBeenCalledOnce();
complete({ ok: true, value: "created" });
await act(() => first as Promise<ApplicationResult<string>>);
});
it("deduplicates submit and commits one optimistic mutation", async () => {
const client = queryClient();
const key = ["resource", "list"];
client.setQueryData(key, ["existing"]);
let complete: (value: ApplicationResult<string>) => void = () => {};
const execute = vi.fn(
() =>
new Promise<ApplicationResult<string>>((resolve) => {
complete = resolve;
}),
);
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
// §11.2: joining is opt-in. The default is REJECT_WHILE_ACTIVE.
duplicatePolicy: "JOIN_IDENTICAL",
execute,
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | null = null;
let duplicate: Promise<ApplicationResult<string>> | null = null;
act(() => {
first = hook.result.current.submit("created");
duplicate = hook.result.current.submit("created");
});
expect(first).toBe(duplicate);
await waitFor(() =>
expect(client.getQueryData(key)).toEqual(["existing", "created"]),
);
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
await waitFor(() =>
expect(hook.result.current.state.indicator).toBe("mutation-pending"),
);
complete({ ok: true, value: "created" });
if (!first) throw new Error("expected pending mutation");
await act(() => first);
expect(client.getQueryState(key)?.isInvalidated).toBe(true);
await waitFor(() =>
expect(hook.result.current.state.indicator).toBeNull(),
);
});
it("never joins distinct mutation inputs to the same runtime promise", async () => {
const client = queryClient();
const resolvers = new Map<
string,
(value: ApplicationResult<string>) => void
>();
const execute = vi.fn(
(input: string) =>
new Promise<ApplicationResult<string>>((resolve) => {
resolvers.set(input, resolve);
}),
);
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
definitionId: "legacy-parallel-distinct-inputs-v1",
execute,
currentData: true,
}),
{ wrapper: wrapper(client) },
);
let first: Promise<ApplicationResult<string>> | undefined;
let second: Promise<ApplicationResult<string>> | undefined;
act(() => {
first = hook.result.current.submit("first");
second = hook.result.current.submit("second");
});
expect(first).not.toBe(second);
await waitFor(() => expect(execute).toHaveBeenCalledTimes(2));
resolvers.get("first")?.({ ok: true, value: "first" });
resolvers.get("second")?.({ ok: true, value: "second" });
if (!first || !second) throw new Error("expected pending mutations");
await act(async () => {
await Promise.all([first, second]);
});
});
describe("unknown-effect replay (D-1)", () => {
function replayScope() {
let token = 0;
return {
...scopeSnapshot(),
identities: createRuntimeIdentityRegistry({
tokenFactory: () => `replay-identity-token-${String(++token).padStart(4, "0")}`,
}),
};
}
function renderKeyedCreate(
outcomes: ApplicationResult<string>[],
) {
const client = queryClient();
const intents: MutationIntent[] = [];
const sentAt: number[] = [];
const execute = vi.fn(
async (
input: string,
context: Readonly<{ signal: AbortSignal; intent: MutationIntent }>,
): Promise<ApplicationResult<string>> => {
intents.push(context.intent);
sentAt.push(performance.now());
return outcomes.shift() ?? { ok: true, value: input };
},
);
const scope = replayScope();
const hook = renderHook(
() =>
useApplicationMutation<string, string>({
definitionId: "replay-intent-v1",
definitionVersion: 1,
operationId: "CREATE_REPLAYED",
requiresIdempotencyKey: true,
owner: "platform-test",
duplicatePolicy: "REJECT_WHILE_ACTIVE",
scope,
execute,
invalidate: [],
}),
{ wrapper: wrapper(client) },
);
return { hook, intents, execute, sentAt };
}
const unknown: ApplicationResult<string> = {
ok: false,
error: createFailure("SERVER_FAILURE", "CREATE_REPLAYED", 0, {
effect: "MAYBE_APPLIED",
}),
};
it("sends the same intent when the same input is saved again after an unknown effect", async () => {
const { hook, intents } = renderKeyedCreate([unknown]);
await act(() => hook.result.current.submit("same-input"));
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
await act(() => hook.result.current.submit("same-input"));
expect(intents).toHaveLength(2);
expect(intents[1]).toBe(intents[0]);
expect(intents[1]?.idempotencyKey).toBe("key-1");
await waitFor(() =>
expect(hook.result.current.state.indicator).toBeNull(),
);
});
it("mints a new key when the input changes after an unknown effect", async () => {
const { hook, intents } = renderKeyedCreate([unknown]);
await act(() => hook.result.current.submit("first-input"));
await act(() => hook.result.current.submit("changed-input"));
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
"key-1",
"key-2",
]);
// The first request is still unresolved; a different request cannot
// settle it.
expect(hook.result.current.state.indicator).toBe(
"mutation-effect-unknown",
);
});
it("resends the unknown head request with its original key", async () => {
const { hook, intents, execute } = renderKeyedCreate([unknown, unknown]);
await act(() => hook.result.current.submit("resent-input"));
let resent: ApplicationResult<string> | null | undefined;
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toMatchObject({
ok: false,
error: { effect: "MAYBE_APPLIED" },
});
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
expect(resent).toEqual({ ok: true, value: "resent-input" });
expect(execute.mock.calls.map(([input]) => input)).toEqual([
"resent-input",
"resent-input",
"resent-input",
]);
expect(new Set(intents.map((intent) => intent.idempotencyKey))).toEqual(
new Set(["key-1"]),
);
await waitFor(() =>
expect(hook.result.current.state.indicator).toBeNull(),
);
// Nothing is left to resend once the effect is settled.
await act(async () => {
resent = await hook.result.current.resendUnknownEffect();
});
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<string> = {
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<string> = {
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();
}
});
});
});