Files
clean-architecture-frontend…/tests/component/application-mutation-optimistic-cache.test.tsx
T
DongHyeonka 1fa5f3e237 fix(query)!: 제품 mutation 훅이 raw 입력을 받지 않게 한다 (1101/08-03)
문제: useApplicationMutation이 BoundMutation과 함께 raw
LegacyMutationOptions({ execute, definitionId })도 공개 overload로
받는다. raw 쓰기는 intent가 없어 Idempotency-Key 없이 나가고, scope
세대 확인과 측정 profile을 건너뛴다. 결과 불명 뒤 resendUnknownEffect()는
null이라 샘플 폼을 복사하면 "같은 요청으로 다시 보내기"를 눌러도 아무
일이 없고 새 제출도 막힌다. tsc·eslint·depcruise 어느 것도 기능 코드의
raw 사용을 막지 않는다.

고른 방법(결정대로):
- 공개 useApplicationMutation에서 raw overload를 뺀다. 남은 공개
  시그니처는 BoundMutation 하나다. 런타임 LEGACY 분기는 그대로 둔다.
- raw로 쓰인 테스트 24곳(3파일)은 tests/helpers/legacy-application-
  query-harness.ts의 useLegacyApplicationMutation으로 옮긴다. harness는
  명시적 cast로만 그 분기에 닿는다. 단언은 한 줄도 바꾸지 않았다.
- 타입 fixture: application-mutation-admission 테스트에 제품 훅에 raw
  입력을 넘기는 @ts-expect-error를 둔다. raw overload가 돌아오면
  tsconfig.test.json 검사가 TS2578로 실패한다.
- raw query({ queryKey, execute })는 남긴다. 먼저 확인했다: raw query는
  세션이 바뀐 뒤 이전 사용자의 결과를 보이지 않는다. FENCED에서
  ServerStateScopeProvider가 하위 트리를 내리고, READY는 이전
  QueryClient를 비우고 세대 key로 새 QueryClient를 붙인 뒤에 온다. 늦게
  온 이전 응답은 버려진 client에 쓰인다. 이 동작을
  server-state-generation-provider 테스트로 고정했고, 생성 저장소가 같은
  client를 비우지 않고 다시 쓰게 바꾸면 이 테스트가 실패한다(변이 확인).
  시그니처 JSDoc에 "scope·측정 profile 없이 도는 읽기 경로"와 provider
  밖에서는 훅이 막지 않는다는 위험을 적었다.
- typescript-state-and-data-flow.md 4.3의 raw 예시를 bound 정의로 바꾼다.
버린 대안: raw query까지 제거 — 다운스트림 memento의 raw query 12곳이
깨지는데 읽기는 다시 보내도 부작용이 없어 얻는 안전이 작다. 현상 유지 —
쓰기 경로의 중복 생성과 동작하지 않는 재전송이 남는다. 런타임 LEGACY
분기 제거 — legacy 전용 테스트 4건의 단언이 바뀌어 "같은 단언 유지"를
못 지킨다. 별도 tests/fixtures/typecheck + CI 명령 — package.json,
gates.json, contract-baseline.json, 명령 수를 고정한 테스트까지 바꾸고
다른 수정과 baseline 해시가 충돌한다. 같은 tsc 검사를 기존
check:types:test 게이트가 돈다.

위험·한계: 공개 계약 변경(BREAKING). 런타임에는 raw 분기가 남아 cast로
여전히 닿는다(타입으로만 막음). LegacyMutationOptions 타입은 harness가
쓰도록 application-query.ts에서 export한다(배럴에는 없음). raw query는
ServerStateGenerationProvider 밖에서 쓰면 세션 보호가 없다.

검증:
- RED: 원래 훅(raw overload 있음)으로 tsc -p tsconfig.test.json →
  "error TS2578: Unused '@ts-expect-error' directive."
- GREEN: tsc app·test·node 통과. tests/component 35 files 229 tests
  통과(옮긴 테스트 포함). tests/unit·component·features·contract·
  runtime-schema·architecture·scripts·integration(security-followup-
  archive 제외, pnpm 사용) 256 files 중 3 files 4 tests가 부하(load
  avg 32)에서 실패했고 세 파일을 3회 다시 돌려 모두 통과(78/78). eslint
  (바꾼 파일) 통과.
- 다운스트림(읽기만): memento 10곳, tech-log 34곳 모두 bound. 깨지는
  제품 호출 0곳. 두 repo의 tests/component 템플릿 소유 테스트 3파일은
  raw 호출이 있어 harness와 함께 동기화해야 한다.

BREAKING CHANGE: useApplicationMutation이 raw { execute, definitionId }
입력을 받지 않는다. BoundMutation(definitionId, definitionVersion,
operationId, requiresIdempotencyKey, owner, duplicatePolicy, scope,
invalidate, execute(input, { signal, intent }))을 넘긴다. scope는
useServerStateScope()에서 얻는다.
Refs: docs/reviews/2026-11-01-maturity-review/08-presentation.md 08-03
2026-11-03 00:53:16 +09:00

212 lines
6.8 KiB
TypeScript

// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { ApplicationResult } from "../../src/presentation/adapters/query/application-query.ts";
import { createFailure } from "../../src/contracts/errors.ts";
import {
RESOURCE_INVALIDATION_TOPIC,
queryClient,
wrapper,
} from "./application-query-fixture.tsx";
import { useLegacyApplicationMutation } from "../helpers/legacy-application-query-harness.ts";
describe("application mutation optimistic cache lifecycle", () => {
it("cancels an in-flight query before taking the optimistic snapshot", async () => {
const client = queryClient();
const key = ["resource", "ordered-update"];
client.setQueryData(key, ["existing"]);
let finishCancellation: () => void = () => {};
const cancellation = new Promise<void>((resolve) => {
finishCancellation = resolve;
});
const cancelQueries = vi
.spyOn(client, "cancelQueries")
.mockImplementation(async () => cancellation);
const getQueryData = vi.spyOn(client, "getQueryData");
const update = vi.fn((previous, input) => [
...(previous as string[]),
input,
]);
const execute = vi.fn(async () => ({
ok: true as const,
value: "created",
}));
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute,
currentData: ["existing"],
optimistic: { queryKey: key, update },
}),
{ wrapper: wrapper(client) },
);
let pending: Promise<ApplicationResult<string>> | undefined;
act(() => {
pending = hook.result.current.submit("created");
});
expect(cancelQueries).toHaveBeenCalledWith({
queryKey: key,
exact: true,
});
expect(getQueryData).not.toHaveBeenCalled();
expect(update).not.toHaveBeenCalled();
expect(execute).not.toHaveBeenCalled();
finishCancellation();
if (!pending) throw new Error("expected pending mutation");
await act(() => pending);
expect(getQueryData).toHaveBeenCalledWith(key);
expect(update).toHaveBeenCalledWith(["existing"], "created");
expect(execute).toHaveBeenCalledOnce();
expect(client.getQueryData(key)).toEqual(["existing", "created"]);
});
it("keeps a committed optimistic update when invalidation fails", async () => {
const client = queryClient();
const key = ["resource", "committed-update"];
client.setQueryData(key, ["existing"]);
vi.spyOn(client, "invalidateQueries").mockRejectedValue(
new Error("cache refresh failed"),
);
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute: async () => ({ ok: true, value: "created" }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: ["existing"],
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toEqual({ ok: true, value: "created" });
expect(client.getQueryData(key)).toEqual(["existing", "created"]);
});
it("normalizes an optimistic preparation defect without running the command", async () => {
const client = queryClient();
const key = ["resource", "invalid-optimistic-update"];
client.setQueryData(key, ["existing"]);
const execute = vi.fn(async () => ({
ok: true as const,
value: "created",
}));
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute,
currentData: ["existing"],
optimistic: {
queryKey: key,
update: () => {
throw new Error("private optimistic detail");
},
},
}),
{ wrapper: wrapper(client) },
);
let outcome;
await act(async () => {
outcome = await hook.result.current.submit("created");
});
expect(outcome).toMatchObject({
ok: false,
error: {
kind: "UNKNOWN_FAILURE",
effect: "NOT_STARTED",
operationId: "APPLICATION_MUTATION",
userMessageKey: "error.unknown_failure",
},
});
expect(JSON.stringify(outcome)).not.toContain("private optimistic detail");
expect(execute).not.toHaveBeenCalled();
expect(client.getQueryData(key)).toEqual(["existing"]);
});
it("removes an optimistic cache entry when no prior data existed", async () => {
const client = queryClient();
const key = ["resource", "new-optimistic-entry"];
const failure = createFailure("SERVER_FAILURE", "CREATE", 0, {
effect: "NOT_APPLIED",
});
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute: async () => ({ ok: false, error: failure }),
currentData: true,
optimistic: {
queryKey: key,
update: (_previous, input) => [input],
},
}),
{ wrapper: wrapper(client) },
);
let outcome;
await act(async () => {
outcome = await hook.result.current.submit("temporary");
});
expect(outcome).toEqual({ ok: false, error: failure });
expect(client.getQueryData(key)).toBeUndefined();
expect(client.getQueryState(key)).toBeUndefined();
});
it("rolls optimistic data back and exposes a resolvable conflict", async () => {
const client = queryClient();
const key = ["resource", "list"];
client.setQueryData(key, ["existing"]);
const conflict = createFailure("CONFLICT", "CREATE", 0, {
effect: "NOT_APPLIED",
});
const hook = renderHook(
() =>
useLegacyApplicationMutation<string, string>({
execute: async () => ({ ok: false, error: conflict }),
invalidate: [RESOURCE_INVALIDATION_TOPIC],
currentData: client.getQueryData(key),
optimistic: {
queryKey: key,
update: (previous, input) => [
...(previous as string[]),
input,
],
},
}),
{ wrapper: wrapper(client) },
);
let outcome;
await act(async () => {
outcome = await hook.result.current.submit("conflicting");
});
expect(outcome).toEqual({ ok: false, error: conflict });
expect(client.getQueryData(key)).toEqual(["existing"]);
expect(hook.result.current.state.indicator).toBe("mutation-conflict");
expect(hook.result.current.state.overlay).toMatchObject({
mutationPending: false,
mutationConflict: true,
});
await act(() => hook.result.current.resolveConflict());
expect(hook.result.current.state.indicator).toBeNull();
expect(client.getQueryState(key)?.isInvalidated).toBe(true);
});});