diff --git a/docs/architecture/client-cache-and-storage.md b/docs/architecture/client-cache-and-storage.md index afa249fd..f7915853 100644 --- a/docs/architecture/client-cache-and-storage.md +++ b/docs/architecture/client-cache-and-storage.md @@ -466,6 +466,13 @@ normative key layout: non-finite number, DOM/native object를 fail-closed로 거절한다. - array 순서는 의미가 있으므로 유지한다. - query namespace는 arbitrary caller string이 아니라 registry reference다. + 현재 구현(03-01): `QueryDefinition.namespace`에 무효화 registry의 + `QueryNamespaceIdentity` 객체를 그대로 넘긴다(참조 기능이 이렇게 한다). + 예전 형태인 문자열 id와 `namespaceVersion` 쌍도 아직 받는다. 어느 등록 + topic도 닿지 않는 namespace로 bound query가 만들어지면 cache coordinator가 + namespace당 한 번 `cache.operation.failed`(`operation: + unregistered-query-namespace`) 진단을 남긴다. 저장으로 무효화할 일이 없는 + 정적 조회는 `invalidation: "NONE"`으로 선언해 이 진단에서 뺀다. - cross-tab event에는 전체 query key나 filter를 넣지 않는다. 현재 `src/contracts/query-keys.ts`의 `canonicalize()`는 object key order는 diff --git a/src/adapters/query-cache/tanstack-cache-coordinator.ts b/src/adapters/query-cache/tanstack-cache-coordinator.ts index 305db5d7..83581774 100644 --- a/src/adapters/query-cache/tanstack-cache-coordinator.ts +++ b/src/adapters/query-cache/tanstack-cache-coordinator.ts @@ -10,6 +10,8 @@ import type { import { INVALIDATION_REGISTRY_BOUNDS } from "../../contracts/query-invalidation.ts"; import { createQueryInvalidationPrefix, + QUERY_KEY_SCHEMA_VERSION, + QUERY_WITHOUT_INVALIDATION_META, queryNamespaceIdentityKey, type QueryNamespaceIdentity, } from "../../contracts/query-keys.ts"; @@ -49,6 +51,32 @@ export function createTanStackCacheCoordinator( receiveRemote(delivery); }); + // 03-01. A save invalidates topics, and a topic reaches only registered + // namespaces. A bound query under any other namespace never refreshes after + // a save, silently, so each such namespace is reported once. + const reportedNamespaces = new Set(); + const unsubscribeQueryCache = dependencies.queryClient + .getQueryCache() + .subscribe((event) => { + if (event.type !== "added") return; + if ( + event.query.meta?.invalidation === + QUERY_WITHOUT_INVALIDATION_META.invalidation + ) { + return; + } + const namespaceKey = boundQueryNamespaceKey(event.query.queryKey); + if ( + namespaceKey === null || + reportedNamespaces.has(namespaceKey) || + dependencies.invalidationIndex.topicsForNamespace.has(namespaceKey) + ) { + return; + } + reportedNamespaces.add(namespaceKey); + report("unregistered-query-namespace"); + }); + function namespacesFor( topic: QueryInvalidationTopic, ): readonly QueryNamespaceIdentity[] { @@ -277,6 +305,7 @@ export function createTanStackCacheCoordinator( if (disposed) return; disposed = true; unsubscribe?.(); + unsubscribeQueryCache(); dependencies.crossContext?.close(); pendingRemote.clear(); mutationLeases.clear(); @@ -320,3 +349,23 @@ function validateConfiguration( } } } + +/** + * 03-01. The registry key of a `bindQuery` key's namespace, read from the + * prefix `createQueryInvalidationPrefix` builds. Any other key is not a bound + * query and yields `null`. + */ +function boundQueryNamespaceKey(queryKey: readonly unknown[]): string | null { + const [root, schemaVersion, namespaceId, namespaceVersion] = queryKey; + if (root !== "query" || schemaVersion !== QUERY_KEY_SCHEMA_VERSION) { + return null; + } + try { + return queryNamespaceIdentityKey({ + namespaceId: namespaceId as string, + namespaceVersion: namespaceVersion as number, + }); + } catch { + return null; + } +} diff --git a/src/contracts/query-keys.ts b/src/contracts/query-keys.ts index 8de078e3..3f32544b 100644 --- a/src/contracts/query-keys.ts +++ b/src/contracts/query-keys.ts @@ -65,6 +65,18 @@ export function createQueryInvalidationPrefix( ] as const); } +/** + * 03-01. The TanStack query `meta` of a bound query declared + * `invalidation: "NONE"` (`QueryDefinition`). `useApplicationQuery` sets it and + * the cache coordinator reads it, so a static lookup is not reported as a + * namespace no invalidation topic reaches. It lives here, beside the key + * layout the coordinator already reads, so the coordinator does not pull + * `server-state.ts` into the initial bundle. + */ +export const QUERY_WITHOUT_INVALIDATION_META = Object.freeze({ + invalidation: "NONE" as const, +}); + export function createBoundQueryKey( namespace: QueryNamespaceIdentity, scopeFingerprint: string, diff --git a/src/contracts/server-state.ts b/src/contracts/server-state.ts index f7476c64..d0da23fd 100644 --- a/src/contracts/server-state.ts +++ b/src/contracts/server-state.ts @@ -3,6 +3,7 @@ import type { QueryInvalidationTopic } from "./query-invalidation.ts"; import { createBoundQueryKey, defineQueryNamespaceIdentity, + type QueryNamespaceIdentity, type RuntimeIdentityBinding, } from "./query-keys.ts"; import type { CacheScopeSnapshot } from "./server-state-scope.ts"; @@ -152,24 +153,41 @@ export type BoundQuery = Readonly<{ profile: ServerStateProfile; identity: RuntimeIdentityBinding; scope: CacheScopeSnapshot; + /** 03-01. Copied from `QueryDefinition.invalidation`. */ + invalidation?: "NONE"; measureResult(value: Value): QueryResultMeasure; execute(context: Readonly<{ signal: AbortSignal }>): Promise>; }>; +/** + * 03-01. Pass the registry's `QueryNamespaceIdentity` (the object the + * feature's invalidation registry lists) as `namespace`. The older pair of a + * caller-written id and `namespaceVersion` still binds, but nothing ties it to + * the registry: a typo there only shows up as the cache coordinator's + * `unregistered-query-namespace` diagnostic. + */ +type QueryDefinitionNamespace = + | Readonly<{ namespace: QueryNamespaceIdentity; namespaceVersion?: never }> + | Readonly<{ namespace: string; namespaceVersion: number }>; + export type QueryDefinition = Readonly<{ definitionId: string; definitionVersion: number; owner: string; - namespace: string; - namespaceVersion: number; operationId: string; profileId: ServerStateProfileId; + /** + * 03-01. `"NONE"` declares a query no save invalidates (a static lookup). + * Without it, a namespace no registered topic reaches is reported. + */ + invalidation?: "NONE"; measureResult(value: Value): QueryResultMeasure; execute( input: Input, context: Readonly<{ signal: AbortSignal }>, ): Promise>; -}>; +}> & + QueryDefinitionNamespace; export function bindQuery( definition: QueryDefinition, @@ -181,10 +199,16 @@ export function bindQuery( `Query definition requires measureResult: ${definition.definitionId}`, ); } - const namespace = defineQueryNamespaceIdentity( - definition.namespace, - definition.namespaceVersion, - ); + const namespace = + typeof definition.namespace === "string" + ? defineQueryNamespaceIdentity( + definition.namespace, + definition.namespaceVersion as number, + ) + : defineQueryNamespaceIdentity( + definition.namespace.namespaceId, + definition.namespace.namespaceVersion, + ); const identity = scope.identities.intern(input); return Object.freeze({ definitionId: definition.definitionId, @@ -199,6 +223,9 @@ export function bindQuery( profile: getServerStateProfile(definition.profileId), identity, scope, + ...(definition.invalidation === undefined + ? {} + : { invalidation: definition.invalidation }), measureResult: (value: Value) => definition.measureResult(value), execute: (context) => definition.execute(input, context), }); diff --git a/src/features/reference-feature/presentation/use-reference-feature.ts b/src/features/reference-feature/presentation/use-reference-feature.ts index ca1f9761..fd51b25c 100644 --- a/src/features/reference-feature/presentation/use-reference-feature.ts +++ b/src/features/reference-feature/presentation/use-reference-feature.ts @@ -87,9 +87,7 @@ export function useReferenceDetail(resourceId: string) { definitionId: "reference-resource-detail-v1", definitionVersion: 1, owner: REFERENCE_FEATURE_ID, - namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceId, - namespaceVersion: - REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceVersion, + namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE, operationId: "GET_REFERENCE_RESOURCE", profileId: "DETAIL_STANDARD", measureResult: measureResourceView, @@ -124,9 +122,7 @@ export function useReferenceFeature() { definitionId: "reference-resource-list-v1", definitionVersion: 1, owner: REFERENCE_FEATURE_ID, - namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceId, - namespaceVersion: - REFERENCE_RESOURCE_QUERY_NAMESPACE.namespaceVersion, + namespace: REFERENCE_RESOURCE_QUERY_NAMESPACE, operationId: "LIST_REFERENCE_RESOURCES", profileId: "LIST_STANDARD", measureResult: measureResourceList, diff --git a/src/presentation/adapters/query/application-query.ts b/src/presentation/adapters/query/application-query.ts index c747c916..aa87347f 100644 --- a/src/presentation/adapters/query/application-query.ts +++ b/src/presentation/adapters/query/application-query.ts @@ -37,7 +37,10 @@ import { MUTATION_COORDINATOR_BOUNDS, type MutationDuplicatePolicy, } from "../../../contracts/server-state.ts"; -import { runtimeIdentityToken } from "../../../contracts/query-keys.ts"; +import { + QUERY_WITHOUT_INVALIDATION_META, + runtimeIdentityToken, +} from "../../../contracts/query-keys.ts"; import { useQueryInvalidationCoordinator } from "./query-invalidation-provider.tsx"; import { useMutationIntentFactory } from "./mutation-intent-provider.tsx"; import { @@ -81,6 +84,8 @@ export function useApplicationQuery( "measureResult" in options ? options.measureResult : undefined; const queryDefinitionId = "definitionId" in options ? options.definitionId : "APPLICATION_QUERY"; + const invalidation = + "invalidation" in options ? options.invalidation : undefined; const [staleFailure, setStaleFailure] = useState(false); useEffect(() => { identity?.acquire(); @@ -89,6 +94,9 @@ export function useApplicationQuery( const query = useQuery({ queryKey, enabled, + ...(invalidation === "NONE" + ? { meta: QUERY_WITHOUT_INVALIDATION_META } + : {}), retry: false, staleTime: profile?.staleTimeMs, gcTime: profile?.gcTimeMs, diff --git a/tests/unit/tanstack-cache-coordinator.test.ts b/tests/unit/tanstack-cache-coordinator.test.ts index aa8aa888..dc89ac2e 100644 --- a/tests/unit/tanstack-cache-coordinator.test.ts +++ b/tests/unit/tanstack-cache-coordinator.test.ts @@ -11,6 +11,7 @@ import { indexInvalidationRegistry, } from "../../src/contracts/query-invalidation.ts"; import { + createBoundQueryKey, createRuntimeIdentityRegistry, defineQueryNamespaceIdentity, type QueryNamespaceIdentity, @@ -344,6 +345,60 @@ describe("TanStack cross-context cache coordinator", () => { coordinator.dispose(); }); + /** + * 03-01 (E7). A save invalidates topics, and a topic reaches only registered + * namespaces. A bound query under any other namespace (a typo, a bumped + * version, a namespace left out of the registry) silently never refreshes, + * so the coordinator reports it once per namespace. + */ + it("reports a bound query whose namespace no registered topic reaches (03-01)", async () => { + const queryClient = createClient(); + const record = vi.fn(); + const coordinator = createTanStackCacheCoordinator({ + queryClient, + invalidationIndex: invalidationIndex(), + topicVersions: topicVersions(), + diagnostics: { record }, + }); + const typo = defineQueryNamespaceIdentity("resource-x", 1); + const bumpedOnly = defineQueryNamespaceIdentity("resource-a", 2); + const declaredStatic = defineQueryNamespaceIdentity("lookup-static", 1); + + queryClient.setQueryData(realBoundQueryKey(NAMESPACE_A), "registered"); + queryClient.setQueryData(realBoundQueryKey(typo), "typo"); + queryClient.setQueryData( + createBoundQueryKey(typo, "scope-fingerprint-0002", 1, "identity-token-again"), + "typo again", + ); + queryClient.setQueryData(realBoundQueryKey(bumpedOnly), "bumped"); + queryClient.setQueryData(["legacy-key", 1], "not a bound query"); + await queryClient.prefetchQuery({ + queryKey: realBoundQueryKey(declaredStatic), + queryFn: async () => "static lookup", + meta: { invalidation: "NONE" }, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(record).toHaveBeenCalledTimes(2); + expect(record).toHaveBeenCalledWith({ + level: "warn", + eventId: "cache.operation.failed", + context: { + operation: "unregistered-query-namespace", + error_kind: "QUERY_CACHE_FAILURE", + }, + }); + coordinator.dispose(); + + // A disposed coordinator stops watching the cache. + queryClient.setQueryData( + realBoundQueryKey(defineQueryNamespaceIdentity("resource-y", 1)), + "after dispose", + ); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(record).toHaveBeenCalledTimes(2); + }); + it("rejects an unregistered topic before opening a mutation lease", () => { const coordinator = createTanStackCacheCoordinator({ queryClient: createClient(),