frontend-quality-gates / merge / static checks (pull_request) Successful in 2m26s
frontend-quality-gates / merge / tests (pull_request) Failing after 15m50s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 11m10s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / main / checker self-tests (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
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 / external-provenance-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-019 / hosting-header (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-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
useApplicationQuery가 "데이터가 있고 마지막 조회가 실패했다"는 파생 값을 effect로 state에 복사한다. 다시 시도가 그 값을 지운 뒤 refetch해도, 조회 중에 effect가 다시 돌아 true로 되돌린다. 그래서 낡은 데이터의 다시 시도가 진행 중에도 지난 실패(stale-degraded)를 보인다(1112/01-05). query·mutation 실패 진단은 원인을 버린다. cache의 onError가 모든 실패를 cache.operation.failed로 남기는데, ApplicationQueryError에 kind가 없어 safeErrorKind가 이름(APPLICATION_QUERY_ERROR)을 쓴다. 404, 필드 거절, abort가 한 가지로 남는다. 예상 밖 throw는 정의 이름 대신 고정 문자열 (APPLICATION_QUERY, APPLICATION_MUTATION)을 쓴다(1112/01-04). 고른 방법: staleFailure를 query.isError && hasData && !isFetching으로 렌더 중에 계산하고 state와 effect를 지운다. 다시 시도 중은 refreshing이다. ApplicationQueryError가 failure.kind를 kind로 싣는다. 예상 밖 throw는 query 정의 ID와 mutation 정의 ID를 쓰고, 정의가 없는 legacy mutation만 옛 이름을 둔다. 버린 대안: cache onError가 ApplicationQueryError를 아예 세지 않기 (서버 실패를 cache 진단에서 잃는다). 위험·한계: 낡은 데이터의 배경 재조회 중에도 stale 대신 refreshing을 보인다. 진단 error_kind 값이 바뀌어 그 값을 읽는 대시보드가 있으면 바꿔야 한다(템플릿 안에는 없다). 검증: tests/component/application-query-bridge.test.tsx의 새 시험 셋이 고치기 전 코드에서 실패하고 고친 뒤 통과한다(desktop, PR 본문). Refs: 1112/01-04, 1112/01-05
326 lines
11 KiB
TypeScript
326 lines
11 KiB
TypeScript
// @vitest-environment jsdom
|
|
|
|
import { onlineManager } from "@tanstack/react-query";
|
|
import { act, renderHook, waitFor } from "@testing-library/react";
|
|
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
type ApplicationResult,
|
|
useApplicationQuery,
|
|
} from "../../src/presentation/adapters/query/application-query.ts";
|
|
import { createQueryClient } from "../../src/adapters/query-cache/index.ts";
|
|
import { createFailure } from "../../src/contracts/errors.ts";
|
|
import { queryClient, wrapper } from "./application-query-fixture.tsx";
|
|
|
|
describe("application query inbound bridge", () => {
|
|
it("latches a background failure over stale data and clears it on retry success", async () => {
|
|
const client = queryClient();
|
|
const responses: ApplicationResult<string[]>[] = [
|
|
{ ok: true, value: ["first"] },
|
|
{
|
|
ok: false,
|
|
error: createFailure("SERVER_FAILURE", "LIST", 0),
|
|
},
|
|
{ ok: true, value: ["recovered"] },
|
|
];
|
|
const execute = vi.fn(async () => responses.shift() ?? responses[0]);
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["resource", "list"],
|
|
execute,
|
|
}),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
|
|
await waitFor(() => expect(hook.result.current.data).toEqual(["first"]));
|
|
await act(() => hook.result.current.retry());
|
|
await waitFor(() =>
|
|
expect(hook.result.current.state.indicator).toBe("stale-degraded"),
|
|
);
|
|
expect(hook.result.current.state.base).toBe("success");
|
|
expect(hook.result.current.data).toEqual(["first"]);
|
|
|
|
await act(() => hook.result.current.retry());
|
|
await waitFor(() =>
|
|
expect(hook.result.current.data).toEqual(["recovered"]),
|
|
);
|
|
expect(hook.result.current.state.indicator).toBeNull();
|
|
expect(execute).toHaveBeenCalledTimes(3);
|
|
});
|
|
|
|
it("coalesces repeated manual retries while stale data is refetching", async () => {
|
|
const client = queryClient();
|
|
const pending: Array<
|
|
(value: ApplicationResult<string[]>) => void
|
|
> = [];
|
|
const execute = vi.fn(
|
|
({ signal }: Readonly<{ signal: AbortSignal }>) => {
|
|
if (execute.mock.calls.length === 1) {
|
|
return Promise.resolve({ ok: true as const, value: ["first"] });
|
|
}
|
|
return new Promise<ApplicationResult<string[]>>((resolve) => {
|
|
pending.push(resolve);
|
|
signal.addEventListener(
|
|
"abort",
|
|
() => resolve({ ok: true, value: ["aborted"] }),
|
|
{ once: true },
|
|
);
|
|
});
|
|
},
|
|
);
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["resource", "manual-retry-coalescing"],
|
|
execute,
|
|
}),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
|
|
await waitFor(() => expect(hook.result.current.data).toEqual(["first"]));
|
|
|
|
let firstRetry: Promise<void> = Promise.resolve();
|
|
act(() => {
|
|
firstRetry = hook.result.current.retry();
|
|
});
|
|
await waitFor(() => expect(execute).toHaveBeenCalledTimes(2));
|
|
|
|
let secondRetry: Promise<void> = Promise.resolve();
|
|
act(() => {
|
|
secondRetry = hook.result.current.retry();
|
|
});
|
|
await act(async () => {
|
|
await Promise.resolve();
|
|
await Promise.resolve();
|
|
});
|
|
|
|
const callsWhileActive = execute.mock.calls.length;
|
|
const physicalRefetches = pending.length;
|
|
act(() => {
|
|
for (const resolve of pending) {
|
|
resolve({ ok: true, value: ["recovered"] });
|
|
}
|
|
});
|
|
await act(() => Promise.all([firstRetry, secondRetry]));
|
|
await waitFor(() =>
|
|
expect(hook.result.current.data).toEqual(["recovered"]),
|
|
);
|
|
|
|
expect(callsWhileActive).toBe(2);
|
|
expect(physicalRefetches).toBe(1);
|
|
});
|
|
|
|
it("does not report a disabled query without data as loading", async () => {
|
|
// A dependent query waiting on its prerequisite is idle, not loading.
|
|
const client = queryClient();
|
|
const execute = vi.fn(async () => ({ ok: true as const, value: ["x"] }));
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["resource", "waiting-on-prerequisite"],
|
|
execute,
|
|
enabled: false,
|
|
}),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
|
|
expect(hook.result.current.state.base).toBe("idle");
|
|
expect(execute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("reports a completed query without items as empty, not idle", async () => {
|
|
const client = queryClient();
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["resource", "completed-empty"],
|
|
execute: async () => ({ ok: true as const, value: [] as string[] }),
|
|
}),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
|
|
await waitFor(() => expect(hook.result.current.state.base).toBe("empty"));
|
|
});
|
|
|
|
it("still reports a real first load as loading, including a paused offline one", async () => {
|
|
const client = queryClient();
|
|
const execute = vi.fn(
|
|
() => new Promise<ApplicationResult<string[]>>(() => {}),
|
|
);
|
|
const inFlight = renderHook(
|
|
() => useApplicationQuery({ queryKey: ["resource", "first"], execute }),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
|
|
expect(inFlight.result.current.state.base).toBe("initial-loading");
|
|
|
|
// Offline, TanStack pauses the first fetch (isFetching=false) instead of
|
|
// running it; the user is still waiting for data.
|
|
onlineManager.setOnline(false);
|
|
try {
|
|
const paused = renderHook(
|
|
() =>
|
|
useApplicationQuery({ queryKey: ["resource", "offline"], execute }),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
expect(client.getQueryState(["resource", "offline"])?.fetchStatus).toBe(
|
|
"paused",
|
|
);
|
|
expect(paused.result.current.state.base).toBe("initial-loading");
|
|
} finally {
|
|
onlineManager.setOnline(true);
|
|
}
|
|
});
|
|
|
|
it("projects an initial application failure into terminal state", async () => {
|
|
const client = queryClient();
|
|
const failure = createFailure("FORBIDDEN", "LIST", 0);
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["forbidden"],
|
|
execute: async () => ({ ok: false, error: failure }),
|
|
}),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
|
|
await waitFor(() =>
|
|
expect(hook.result.current.state.base).toBe("terminal-error"),
|
|
);
|
|
expect(hook.result.current.state.failure).toBe(failure);
|
|
});
|
|
|
|
it("normalizes an unexpected execute rejection into a safe terminal failure", async () => {
|
|
const client = queryClient();
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["unexpected-rejection"],
|
|
execute: async () => {
|
|
throw new Error("private upstream detail");
|
|
},
|
|
}),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
|
|
await waitFor(() =>
|
|
expect(hook.result.current.state.base).toBe("terminal-error"),
|
|
);
|
|
expect(hook.result.current.state.failure).toMatchObject({
|
|
kind: "UNKNOWN_FAILURE",
|
|
operationId: "APPLICATION_QUERY",
|
|
userMessageKey: "error.unknown_failure",
|
|
action: "contact-support",
|
|
});
|
|
expect(JSON.stringify(hook.result.current.state.failure)).not.toContain(
|
|
"private upstream detail",
|
|
);
|
|
});
|
|
|
|
it("passes cancellation to the application and does not retain an unmounted error", async () => {
|
|
const client = queryClient();
|
|
let aborted = false;
|
|
const execute = vi.fn(
|
|
({ signal }: { signal: AbortSignal }) =>
|
|
new Promise<ApplicationResult<unknown>>((resolve) => {
|
|
signal.addEventListener(
|
|
"abort",
|
|
() => {
|
|
aborted = true;
|
|
resolve({
|
|
ok: false,
|
|
error: createFailure("REQUEST_ABORTED", "LIST", 0),
|
|
});
|
|
},
|
|
{ once: true },
|
|
);
|
|
}),
|
|
);
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["cancelled"],
|
|
execute,
|
|
}),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
|
|
await waitFor(() => expect(execute).toHaveBeenCalledOnce());
|
|
hook.unmount();
|
|
await waitFor(() => expect(aborted).toBe(true));
|
|
expect(client.getQueryState(["cancelled"])?.status).not.toBe("error");
|
|
});
|
|
|
|
// 1112/01-05. Whether stale data failed is the query's own state, read
|
|
// while rendering. Copied into state by an effect, it came back over the
|
|
// retry's reset, so a retry of stale data still said the old failure.
|
|
it("shows a retry of stale data as refreshing, not as the old failure", async () => {
|
|
const client = queryClient();
|
|
let release: ((value: ApplicationResult<string[]>) => void) | undefined;
|
|
const execute = vi
|
|
.fn<() => Promise<ApplicationResult<string[]>>>()
|
|
.mockResolvedValueOnce({ ok: true, value: ["first"] })
|
|
.mockResolvedValueOnce({ ok: false, error: createFailure("SERVER_FAILURE", "LIST", 0) })
|
|
.mockImplementationOnce(
|
|
() => new Promise((resolve) => {
|
|
release = resolve;
|
|
}),
|
|
);
|
|
const hook = renderHook(
|
|
() => useApplicationQuery({ queryKey: ["resource", "stale-retry"], execute }),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
await waitFor(() => expect(hook.result.current.data).toEqual(["first"]));
|
|
await act(() => hook.result.current.retry());
|
|
await waitFor(() => expect(hook.result.current.state.indicator).toBe("stale-degraded"));
|
|
|
|
act(() => {
|
|
void hook.result.current.retry();
|
|
});
|
|
|
|
await waitFor(() => expect(hook.result.current.state.indicator).toBe("refreshing"));
|
|
await act(async () => release?.({ ok: true, value: ["recovered"] }));
|
|
await waitFor(() => expect(hook.result.current.state.indicator).toBeNull());
|
|
});
|
|
|
|
// 1112/01-04. A failed query or mutation was recorded as one kind,
|
|
// APPLICATION_QUERY_ERROR, whatever it was; an unexpected throw lost the
|
|
// definition it came from.
|
|
it("names the failure's kind in the cache diagnostics", async () => {
|
|
const record = vi.fn();
|
|
const client = createQueryClient({ diagnostics: { record } });
|
|
renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["resource", "missing"],
|
|
execute: async () => ({ ok: false, error: createFailure("NOT_FOUND", "GET", 0) }),
|
|
}),
|
|
{ wrapper: wrapper(client) },
|
|
);
|
|
|
|
await waitFor(() => expect(record).toHaveBeenCalled());
|
|
expect(record.mock.calls[0]?.[0]).toMatchObject({
|
|
eventId: "cache.operation.failed",
|
|
context: { operation: "query", error_kind: "NOT_FOUND" },
|
|
});
|
|
});
|
|
|
|
it("names the query definition of an unexpected throw", async () => {
|
|
const hook = renderHook(
|
|
() =>
|
|
useApplicationQuery({
|
|
queryKey: ["resource", "throws"],
|
|
definitionId: "resource-list-v1",
|
|
execute: async () => {
|
|
throw new Error("boom");
|
|
},
|
|
} as Parameters<typeof useApplicationQuery<string[]>>[0]),
|
|
{ wrapper: wrapper(queryClient()) },
|
|
);
|
|
|
|
await waitFor(() => expect(hook.result.current.state.failure).toBeDefined());
|
|
expect(hook.result.current.state.failure?.operationId).toBe("resource-list-v1");
|
|
});
|
|
});
|