From d4aa365bd9e1da4eba72b9d9fd7b451ce576b92e Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 12 Nov 2026 23:24:21 +0900 Subject: [PATCH] =?UTF-8?q?fix(query):=20stale=20=EC=8B=A4=ED=8C=A8?= =?UTF-8?q?=EB=A5=BC=20=EB=A0=8C=EB=8D=94=20=EC=A4=91=EC=97=90=20=EA=B3=84?= =?UTF-8?q?=EC=82=B0=ED=95=98=EA=B3=A0=20=EC=8B=A4=ED=8C=A8=20=EC=A7=84?= =?UTF-8?q?=EB=8B=A8=EC=9D=B4=20=EC=9B=90=EC=9D=B8=EC=9D=84=20=EB=82=A8?= =?UTF-8?q?=EA=B8=B4=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../adapters/query/application-query.ts | 35 +++++---- .../application-query-bridge.test.tsx | 73 ++++++++++++++++++- 2 files changed, 94 insertions(+), 14 deletions(-) diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index 5837e348..943488e8 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -53,11 +53,17 @@ export type ApplicationResult = Result; class ApplicationQueryError extends Error { readonly failure: AppFailure; + /** + * 1112/01-04. What the cache diagnostics record (`safeErrorKind` reads + * `kind` first): the failure's kind, not one name for every failure. + */ + readonly kind: AppFailure["kind"]; constructor(failure: AppFailure) { super(failure.kind); this.name = "ApplicationQueryError"; this.failure = failure; + this.kind = failure.kind; } } @@ -100,7 +106,6 @@ export function useApplicationQuery( "definitionId" in options ? options.definitionId : "APPLICATION_QUERY"; const invalidation = "invalidation" in options ? options.invalidation : undefined; - const [staleFailure, setStaleFailure] = useState(false); useEffect(() => { identity?.acquire(); return () => identity?.release(); @@ -170,9 +175,10 @@ export function useApplicationQuery( throw new DOMException("Query cancelled", "AbortError"); } if (error instanceof ApplicationQueryError) throw error; + // 1112/01-04. The definition it came from, as the other failures here. throw new ApplicationQueryError( normalizeUnknownFailure(error, { - operationId: "APPLICATION_QUERY", + operationId: queryDefinitionId, }), ); } finally { @@ -181,17 +187,13 @@ export function useApplicationQuery( }, }); const hasData = query.data !== undefined && query.data !== null; - - useEffect(() => { - if (query.isError && hasData) { - setStaleFailure(true); - } else if (query.isSuccess && !query.isFetching) { - setStaleFailure(false); - } - }, [hasData, query.isError, query.isFetching, query.isSuccess]); + // 1112/01-05. Read while rendering: the data is stale because the last + // fetch failed, and no fetch runs now. A retry that is running shows as + // refreshing; copied into state by an effect, the old failure came back + // over the retry's reset. + const staleFailure = query.isError && hasData && !query.isFetching; const retry = useCallback(async () => { - setStaleFailure(false); await query.refetch({ cancelRefetch: false }); }, [query]); @@ -368,6 +370,12 @@ export function useApplicationMutation( "definitionId" in options ? options.definitionId ?? "LEGACY_MUTATION" : "LEGACY_MUTATION"; + // 1112/01-04. An unexpected throw names the mutation definition it came + // from; a legacy mutation without one keeps the generic name. + const failureOperationId = + "definitionId" in options && options.definitionId + ? options.definitionId + : "APPLICATION_MUTATION"; const definitionVersion = "definitionVersion" in options ? options.definitionVersion : 0; const duplicatePolicy = @@ -701,7 +709,7 @@ export function useApplicationMutation( error instanceof ApplicationQueryError ? error.failure : normalizeUnknownFailure(error, { - operationId: "APPLICATION_MUTATION", + operationId: failureOperationId, }); const failure = mutationFailureWithEffect(reportedFailure); switch (failure.effect) { @@ -758,7 +766,7 @@ export function useApplicationMutation( .catch((error: unknown) => { const failure = withFailureEffect( normalizeUnknownFailure(error, { - operationId: "APPLICATION_MUTATION", + operationId: failureOperationId, }), "NOT_STARTED", ); @@ -794,6 +802,7 @@ export function useApplicationMutation( queryClient, definitionId, duplicatePolicy, + failureOperationId, mutationIntentFactory, mutationOperationId, requiresIdempotencyKey, diff --git a/tests/component/application-query-bridge.test.tsx b/tests/component/application-query-bridge.test.tsx index 5044a926..f83f61b5 100644 --- a/tests/component/application-query-bridge.test.tsx +++ b/tests/component/application-query-bridge.test.tsx @@ -8,6 +8,7 @@ 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"; @@ -250,5 +251,75 @@ describe("application query inbound bridge", () => { 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) => void) | undefined; + const execute = vi + .fn<() => Promise>>() + .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>[0]), + { wrapper: wrapper(queryClient()) }, + ); + + await waitFor(() => expect(hook.result.current.state.failure).toBeDefined()); + expect(hook.result.current.state.failure?.operationId).toBe("resource-list-v1"); + }); +});