frontend-quality-gates / merge / static checks (pull_request) Successful in 2m56s
frontend-quality-gates / merge / tests (pull_request) Failing after 14m26s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 9m20s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
frontend-quality-gates / main / checker self-tests (pull_request) Skipped
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
isRefusedOnEveryAttempt는 failure.code를 읽는데, 그 값은 기능의 mapProblem이 정한다(1112/01-06). 그래서 둘이 틀린다. - 기능이 백엔드 400 VALIDATION_FAILED를 자기 code로 바꾸면 모든 시도가 받는 거절인데도 결과 불명이 풀리지 않는다. - 기능이 시각·데이터베이스를 읽는 자기 거절(400)을 VALIDATION_FAILED로 바꾸면 첫 요청이 반영됐을 수 있는데도 결과 불명이 풀린다. AppFailure에 backendCode를 더한다(선택 칸, 추가만). HTTP 바인딩이 ENVELOPE_V1 operation의 PROBLEM에서 백엔드 error.code를 그대로 싣고, 판정은 이 칸과 status만 읽는다. Envelope가 없는 operation의 실패에는 싣지 않아 결과 불명이 풀리지 않는다(안전한 쪽). 버린 대안: 판정 표를 기능 code에 맞춰 늘리기(기능이 code를 바꿀 때마다 표가 어긋난다). 위험·한계: createFailure로 실패를 직접 만들어 재전송 거절을 흉내 내던 코드는 backendCode를 함께 줘야 결과 불명이 풀린다. 템플릿 안에서는 코디네이터 시험 넷뿐이고 고쳤다. 다운스트림 시험이 같은 방식이면 CHANGELOG [계약]에 적는다. mapProblem이 예외를 던져 MAPPING_CONTRACT_VIOLATION이 된 실패에는 싣지 않는다. Refs: 1112/01-06, 1106/03-01
949 lines
33 KiB
TypeScript
949 lines
33 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";
|
|
import { testMutationOperationId } from "../helpers/mutation-operation-id.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: testMutationOperationId("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: testMutationOperationId("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: testMutationOperationId("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(maxEntries?: number) {
|
|
let token = 0;
|
|
return {
|
|
...scopeSnapshot(),
|
|
identities: createRuntimeIdentityRegistry({
|
|
...(maxEntries === undefined ? {} : { maxEntries }),
|
|
tokenFactory: () => `replay-identity-token-${String(++token).padStart(4, "0")}`,
|
|
}),
|
|
};
|
|
}
|
|
|
|
function renderKeyedCreate(
|
|
outcomes: ApplicationResult<string>[],
|
|
options: Readonly<{
|
|
maxIdentities?: number;
|
|
keyed?: boolean;
|
|
resendSafe?: boolean;
|
|
optimistic?: Readonly<{
|
|
queryKey: readonly unknown[];
|
|
update(previous: unknown, input: string): unknown;
|
|
}>;
|
|
}> = {},
|
|
) {
|
|
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(options.maxIdentities);
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationMutation<string, string>({
|
|
definitionId: "replay-intent-v1",
|
|
definitionVersion: 1,
|
|
operationId: testMutationOperationId("CREATE_REPLAYED"),
|
|
requiresIdempotencyKey: options.keyed ?? true,
|
|
owner: "platform-test",
|
|
duplicatePolicy: "REJECT_WHILE_ACTIVE",
|
|
scope,
|
|
execute,
|
|
invalidate: [],
|
|
...(options.resendSafe === undefined
|
|
? {}
|
|
: { resendSafe: options.resendSafe }),
|
|
...(options.optimistic === undefined
|
|
? {}
|
|
: { optimistic: options.optimistic }),
|
|
}),
|
|
{ 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",
|
|
);
|
|
});
|
|
|
|
// 0929/03-06. The unknown request leases its input identity, so a full
|
|
// identity registry evicts other inputs first and the same input saved
|
|
// later still finds the unknown request and its key.
|
|
it("keeps the unknown input's identity when the identity registry is full", async () => {
|
|
const { hook, intents } = renderKeyedCreate([unknown], { maxIdentities: 2 });
|
|
await act(() => hook.result.current.submit("same-input"));
|
|
// A two-entry registry: the third input evicts the oldest unleased one.
|
|
await act(() => hook.result.current.submit("second-input"));
|
|
await act(() => hook.result.current.submit("third-input"));
|
|
|
|
await act(() => hook.result.current.submit("same-input"));
|
|
|
|
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
|
|
"key-1",
|
|
"key-2",
|
|
"key-3",
|
|
"key-1",
|
|
]);
|
|
});
|
|
|
|
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);
|
|
});
|
|
|
|
// 0929/03-03. A command without a key has nothing the server can match a
|
|
// second request to: resending it after a lost answer can apply it twice.
|
|
it("offers no resend for an unknown request that carries no key", async () => {
|
|
const { hook, execute } = renderKeyedCreate([unknown], { keyed: false });
|
|
await act(() => hook.result.current.submit("keyless-input"));
|
|
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
|
|
|
|
expect(hook.result.current.canResendUnknownEffect).toBe(false);
|
|
expect(hook.result.current.state.unknownEffectResendable).toBe(false);
|
|
let resent: ApplicationResult<string> | null | undefined;
|
|
await act(async () => {
|
|
resent = await hook.result.current.resendUnknownEffect();
|
|
});
|
|
|
|
expect(resent).toBeNull();
|
|
expect(execute).toHaveBeenCalledOnce();
|
|
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
|
|
});
|
|
|
|
// 0929/03-03. Saving the same input again reuses the unknown request's
|
|
// intent. Without a key that is a second request the server cannot tell
|
|
// from the first, so the hook refuses it before sending, whatever page
|
|
// calls it (review experiment X1: keys [null, null]).
|
|
it("refuses to send a keyless unknown request again for the same input", async () => {
|
|
const { hook, execute } = renderKeyedCreate([unknown], { keyed: false });
|
|
await act(() => hook.result.current.submit("keyless-input"));
|
|
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
|
|
|
|
let again: ApplicationResult<string> | undefined;
|
|
await act(async () => {
|
|
again = await hook.result.current.submit("keyless-input");
|
|
});
|
|
|
|
expect(again).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
kind: "DUPLICATE_IN_FLIGHT",
|
|
code: "UNKNOWN_EFFECT_PENDING",
|
|
effect: "NOT_STARTED",
|
|
},
|
|
});
|
|
expect(execute).toHaveBeenCalledOnce();
|
|
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
|
|
});
|
|
|
|
it("still sends another input while a keyless request is unknown", async () => {
|
|
const { hook, execute } = renderKeyedCreate([unknown], { keyed: false });
|
|
await act(() => hook.result.current.submit("first-input"));
|
|
await act(() => hook.result.current.submit("changed-input"));
|
|
|
|
expect(execute.mock.calls.map(([input]) => input)).toEqual([
|
|
"first-input",
|
|
"changed-input",
|
|
]);
|
|
});
|
|
|
|
it("offers the same-key resend for an unknown keyed request", async () => {
|
|
const { hook } = renderKeyedCreate([unknown]);
|
|
expect(hook.result.current.canResendUnknownEffect).toBe(false);
|
|
await act(() => hook.result.current.submit("keyed-input"));
|
|
|
|
expect(hook.result.current.canResendUnknownEffect).toBe(true);
|
|
expect(hook.result.current.state.unknownEffectResendable).toBe(true);
|
|
});
|
|
|
|
// 1106/03-03. An IDEMPOTENT command has no key, but applying it twice
|
|
// gives the same result: after an unknown result it is offered for
|
|
// resend and the same input is sent again, unlike NEVER (above).
|
|
it("resends an unknown IDEMPOTENT request and sends the same input again", async () => {
|
|
const { hook, intents, execute } = renderKeyedCreate([unknown, unknown], {
|
|
keyed: false,
|
|
resendSafe: true,
|
|
});
|
|
await act(() => hook.result.current.submit("idempotent-input"));
|
|
expect(hook.result.current.state.indicator).toBe("mutation-effect-unknown");
|
|
|
|
expect(hook.result.current.canResendUnknownEffect).toBe(true);
|
|
expect(hook.result.current.state.unknownEffectResendable).toBe(true);
|
|
let resent: ApplicationResult<string> | null | undefined;
|
|
await act(async () => {
|
|
resent = await hook.result.current.resendUnknownEffect();
|
|
});
|
|
expect(resent).toMatchObject({ ok: false, error: { effect: "MAYBE_APPLIED" } });
|
|
|
|
let again: ApplicationResult<string> | undefined;
|
|
await act(async () => {
|
|
again = await hook.result.current.submit("idempotent-input");
|
|
});
|
|
|
|
expect(again).toEqual({ ok: true, value: "idempotent-input" });
|
|
expect(execute).toHaveBeenCalledTimes(3);
|
|
expect(intents[1]).toBe(intents[0]);
|
|
expect(intents[2]).toBe(intents[0]);
|
|
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
|
|
undefined,
|
|
undefined,
|
|
undefined,
|
|
]);
|
|
});
|
|
|
|
// 백엔드 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();
|
|
}
|
|
});
|
|
|
|
// 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",
|
|
}),
|
|
],
|
|
// D10 supplement: these come before the idempotency check, change
|
|
// over time, or need the key to have reached the server already.
|
|
[
|
|
"refused with 401",
|
|
createFailure("AUTH_REQUIRED", "CREATE_REPLAYED", 0, {
|
|
httpStatus: 401,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
],
|
|
[
|
|
"refused with 403",
|
|
createFailure("FORBIDDEN", "CREATE_REPLAYED", 0, {
|
|
httpStatus: 403,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
],
|
|
[
|
|
"refused with 422 IDEMPOTENT_REQUEST_MISMATCH",
|
|
createFailure("UNKNOWN_CLIENT_FAILURE", "CREATE_REPLAYED", 0, {
|
|
code: "IDEMPOTENT_REQUEST_MISMATCH",
|
|
httpStatus: 422,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
],
|
|
// A code the feature declared refused before its write may be a rule
|
|
// on changing state (a name already taken).
|
|
[
|
|
"refused with a code the feature declared",
|
|
createFailure("UNKNOWN_CLIENT_FAILURE", "CREATE_REPLAYED", 0, {
|
|
code: "WORKLOG_INVALID",
|
|
httpStatus: 400,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
],
|
|
// Final review FR-01. The kind is the feature's mapProblem: the
|
|
// scaffold maps its declared code to a field error, and the reference
|
|
// gateway maps every 422 to one, whatever the code.
|
|
[
|
|
"refused with a declared code the feature maps to a field error",
|
|
createFailure("VALIDATION_REJECTED", "CREATE_REPLAYED", 0, {
|
|
code: "WORKLOG_INVALID",
|
|
httpStatus: 400,
|
|
effect: "NOT_APPLIED",
|
|
validationIssues: [{ path: "name", code: "INVALID" }],
|
|
}),
|
|
],
|
|
[
|
|
"refused with 422 IDEMPOTENT_REQUEST_MISMATCH read as a field error",
|
|
createFailure("VALIDATION_REJECTED", "CREATE_REPLAYED", 0, {
|
|
code: "IDEMPOTENT_REQUEST_MISMATCH",
|
|
httpStatus: 422,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
],
|
|
])("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<string> | 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 (D10 supplement). A refusal every attempt of the request
|
|
// gets shows the first attempt was refused too: input validation, or a
|
|
// key the server's rule rejects. The request is settled, so the form can
|
|
// take a corrected save, which goes out as a new request.
|
|
it.each([
|
|
[
|
|
"400 VALIDATION_FAILED with its field list",
|
|
createFailure("VALIDATION_REJECTED", "CREATE_REPLAYED", 0, {
|
|
code: "VALIDATION_FAILED",
|
|
backendCode: "VALIDATION_FAILED",
|
|
httpStatus: 400,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
],
|
|
[
|
|
"400 VALIDATION_FAILED whose body did not parse",
|
|
createFailure("UNKNOWN_CLIENT_FAILURE", "CREATE_REPLAYED", 0, {
|
|
code: "VALIDATION_FAILED",
|
|
backendCode: "VALIDATION_FAILED",
|
|
httpStatus: 400,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
],
|
|
[
|
|
"400 IDEMPOTENCY_KEY_INVALID",
|
|
createFailure("UNKNOWN_CLIENT_FAILURE", "CREATE_REPLAYED", 0, {
|
|
code: "IDEMPOTENCY_KEY_INVALID",
|
|
backendCode: "IDEMPOTENCY_KEY_INVALID",
|
|
httpStatus: 400,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
],
|
|
])("settles the request when the resend is refused with %s", async (_label, refusal) => {
|
|
const { hook, intents } = renderKeyedCreate([
|
|
unknown,
|
|
{ ok: false, error: refusal },
|
|
]);
|
|
await act(() => hook.result.current.submit("same-input"));
|
|
|
|
let resent: ApplicationResult<string> | null | undefined;
|
|
await act(async () => {
|
|
resent = await hook.result.current.resendUnknownEffect();
|
|
});
|
|
|
|
expect(resent).toMatchObject({
|
|
ok: false,
|
|
error: { code: refusal.code, effect: "NOT_APPLIED" },
|
|
});
|
|
expect(hook.result.current.state.indicator).toBeNull();
|
|
expect(hook.result.current.canResendUnknownEffect).toBe(false);
|
|
|
|
await act(() => hook.result.current.submit("corrected-input"));
|
|
|
|
expect(intents.map((intent) => intent.idempotencyKey)).toEqual([
|
|
"key-1",
|
|
"key-1",
|
|
"key-2",
|
|
]);
|
|
});
|
|
|
|
// 1106/03-01 (D10 supplement) on the IDEMPOTENT path (1106/03-03). A 404
|
|
// the operation reads as not applied is a common answer once the first
|
|
// attempt applied, so the request stays unknown; input validation
|
|
// settles it.
|
|
it.each([
|
|
[
|
|
"refused with 404",
|
|
createFailure("NOT_FOUND", "CREATE_REPLAYED", 0, {
|
|
httpStatus: 404,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
"mutation-effect-unknown",
|
|
],
|
|
[
|
|
"refused with 400 VALIDATION_FAILED",
|
|
createFailure("VALIDATION_REJECTED", "CREATE_REPLAYED", 0, {
|
|
code: "VALIDATION_FAILED",
|
|
backendCode: "VALIDATION_FAILED",
|
|
httpStatus: 400,
|
|
effect: "NOT_APPLIED",
|
|
}),
|
|
null,
|
|
],
|
|
] as const)("decides an unknown IDEMPOTENT request by its resend %s", async (_label, refusal, indicator) => {
|
|
const { hook, execute } = renderKeyedCreate(
|
|
[unknown, { ok: false, error: refusal }],
|
|
{ keyed: false, resendSafe: true },
|
|
);
|
|
await act(() => hook.result.current.submit("idempotent-input"));
|
|
|
|
await act(async () => {
|
|
await hook.result.current.resendUnknownEffect();
|
|
});
|
|
|
|
expect(execute).toHaveBeenCalledTimes(2);
|
|
expect(hook.result.current.state.indicator).toBe(indicator);
|
|
});
|
|
|
|
// 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<string> | 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",
|
|
]);
|
|
});
|
|
});
|
|
});
|