Files
clean-architecture-frontend…/src/adapters/query-cache/tanstack-cache-coordinator.ts
T
DongHyeonka ffb6782b0c fix(query): 무효화 topic이 닿지 않는 조회 namespace를 진단으로 알린다 (03-01)
문제
QueryDefinition의 namespace는 아무 문자열, namespaceVersion은 아무
숫자다. bindQuery는 이 둘로 쿼리 키를 만들 뿐 무효화 registry에 있는지
보지 않는다. 저장 뒤 무효화는 topic -> 등록 namespace 접두사로만 가므로,
namespace 오타나 version만 올린 조회, registry에 빠진 namespace의 조회는
저장 뒤에도 갱신되지 않는다. 오류도 진단도 없다(E7). 문서는 "query
namespace는 registry reference"라고 적지만(client-cache-and-storage.md),
참조 기능도 registry 객체에서 두 필드를 꺼내 문자열로 다시 넘긴다.

고른 방법
- 런타임 검사(리뷰 ②): cache coordinator가 QueryCache의 "added"
  이벤트를 구독한다. bindQuery 키 접두사(["query", 2, id, version])를
  읽어 registry 인덱스(topicsForNamespace)에 없으면 namespace당 한 번
  cache.operation.failed(operation: unregistered-query-namespace) 진단을
  남긴다. registry와 TanStack 키의 연결은 원래 이 coordinator가 갖고
  있으므로(무효화 접두사) 새 결합을 만들지 않는다. dispose 때 구독을 푼다.
- 정적 조회 예외: QueryDefinition에 선택 필드 invalidation: "NONE"을
  더한다. bindQuery가 BoundQuery로 옮기고, useApplicationQuery가 공유 상수
  QUERY_WITHOUT_INVALIDATION_META를 TanStack meta로 넣고, coordinator가 같은
  상수로 읽는다. 상수는 query-keys.ts에 둔다. server-state.ts에 두면
  coordinator(초기 청크)가 그 모듈 전체를 끌어와 초기 JS에 server-state
  청크가 하나 생긴다(측정: +1,407 B gzip, 파일 16 -> 17).
- 타입(리뷰 ①, 추가만): QueryDefinition.namespace가 registry의
  QueryNamespaceIdentity 객체를 그대로 받는다. 참조 기능의 두 조회는 등록
  객체를 넘긴다. 문자열 id + namespaceVersion 쌍도 계속 받는다.

버린 대안
- 문자열 쌍을 없애고 객체만 받기(리뷰 ①의 원안): 공개 타입 시그니처를
  깨서 다운스트림 조회 정의를 모두 고쳐야 한다. 이번 범위에서는 공개
  포트를 추가만 한다. 문자열 쌍의 오타는 위 진단이 잡는다.
- useApplicationQuery에서 검사하고 QueryInvalidationCoordinator에 메서드
  추가: 공개 인터페이스가 늘고, 다른 경로로 cache에 들어오는 bound 키는
  못 본다.
- 개발 빌드에서 throw(리뷰 ②): QueryCache 구독 콜백에서 throw하면 TanStack
  알림 경로가 깨진다. 진단 1건으로 완료 기준("타입 오류 또는 진단 1건")을
  채운다.
- 진단에 namespace id 싣기: id는 80바이트까지 허용돼 진단 값 문법(64자)을
  넘으면 기록 전체가 버려진다. id 없이 operation만 남겼다.

위험·한계
- 런타임 검사라 그 조회가 처음 cache에 들어갈 때(화면을 열 때) 드러난다.
- "등록은 했지만 edge가 없음"은 registry 인덱스가 시작 때 orphan
  namespace로 거절하므로 여기까지 오지 않는다.
- 진단에서 어느 namespace인지는 알 수 없다. 개수만 보인다.
- useApplicationQuery -> meta 연결은 타입 검사로만 확인했다. 그 경로의
  런타임 테스트는 없다.
- 공개 타입은 추가만 했다(QueryDefinition namespace 유니언, invalidation,
  BoundQuery.invalidation, 상수 1개).

검증
- RED(수정 전): tests/unit/tanstack-cache-coordinator.test.ts "reports a
  bound query whose namespace no registered topic reaches (03-01)" 실패.
  "expected vi.fn() to be called 2 times, but got 0 times".
- GREEN: 같은 파일 10/10, tests/features/reference-feature 포함 17 files /
  89 tests 통과. 변이 M20(참조 목록 조회 namespace를 문자열 오타 쌍으로)을
  넣으면 reference-page.test.tsx가 실패하는 것을 확인하고 원복했다.
- 회귀: run-vitest tests/unit tests/integration tests/component
  tests/features tests/contract tests/runtime-schema(pnpm을 언급하는 파일
  12개 제외) 228 files 중 227 통과, 2369/2370. 실패 1건은
  provider-guardian-transaction의 ENOSPC(inotify watcher 한도, 이 머신의
  다른 실행 때문)로 이 변경과 무관하다.
  tsc app/test/node rc=0. 바꾼 파일 eslint rc=0.
  check-adapter-inventory PASS. verify-documentation-readiness PASS_SCOPED.
- 번들: build-frontend로 빌드해 check-bundle과 같은 분류로 초기 JS를
  gzipSync로 쟀다. 298201f 202,509 B(16 파일) -> 이 커밋까지 세 커밋 누적
  202,913 B(16 파일), +404 B. 예산 204,800 B. 예산은 바꾸지 않았다.
- 미실행: check:architecture(pnpm 스크립트 필요). depcruise 직접 실행은
  0 modules라 사실상 미검증이다. 새 import는 adapter -> contracts,
  presentation -> contracts뿐이다.

Refs: docs/reviews/2026-11-01-maturity-review/03-adapters-http-state.md
2026-11-01 22:42:44 +09:00

372 lines
11 KiB
TypeScript

import type { QueryClient } from "@tanstack/react-query";
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts";
import type {
InvalidationRegistryIndex,
QueryInvalidationCoordinator,
QueryInvalidationTopic,
QueryMutationLease,
} from "../../contracts/query-invalidation.ts";
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";
import type {
BrowserCrossContextInvalidation,
CrossContextInvalidationDelivery,
} from "../cross-context-invalidation/index.ts";
export type TanStackCacheCoordinatorDependencies = Readonly<{
queryClient: QueryClient;
invalidationIndex: InvalidationRegistryIndex;
topicVersions: ReadonlyMap<string, number>;
crossContext?: BrowserCrossContextInvalidation;
diagnostics?: DiagnosticsPort;
}>;
/**
* Joins registry-owned invalidation topics to TanStack Query without putting a
* query key or cached value on the cross-context wire.
*/
export function createTanStackCacheCoordinator(
dependencies: TanStackCacheCoordinatorDependencies,
): QueryInvalidationCoordinator {
validateConfiguration(
dependencies.invalidationIndex,
dependencies.topicVersions,
);
const mutationLeases = new Map<QueryInvalidationTopic, number>();
const pendingRemote = new Set<QueryInvalidationTopic>();
let disposed = false;
let resetting = false;
let lifecycleGeneration = 0;
let flushPromise: Promise<void> | null = null;
let resetPromise: Promise<void> | null = null;
const unsubscribe = dependencies.crossContext?.subscribe((delivery) => {
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<string>();
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[] {
const selected = dependencies.invalidationIndex.namespacesForTopic.get(topic);
if (!selected) {
throw new TypeError("Unregistered query invalidation topic.");
}
return selected;
}
async function invalidateLocal(
topics: readonly QueryInvalidationTopic[],
expectedGeneration = lifecycleGeneration,
): Promise<void> {
if (
disposed ||
resetting ||
expectedGeneration !== lifecycleGeneration
) {
return;
}
const namespaces = new Map<string, QueryNamespaceIdentity>();
for (const topic of topics) {
for (const namespace of namespacesFor(topic)) {
namespaces.set(queryNamespaceIdentityKey(namespace), namespace);
}
}
// Q-6.3-8. invalidateQueries resolves only after the active refetches
// finish, so the namespaces run side by side instead of one after another.
const results = await Promise.allSettled(
[...namespaces.values()].map(async (namespace) =>
dependencies.queryClient.invalidateQueries({
queryKey: createQueryInvalidationPrefix(namespace),
exact: false,
refetchType: "active",
}),
),
);
for (const result of results) {
if (result.status === "rejected") report("invalidate");
}
}
function receiveRemote(
delivery: CrossContextInvalidationDelivery,
): void {
if (disposed) return;
if (
!dependencies.invalidationIndex.namespacesForTopic.has(
delivery.event.topic,
)
) {
report("unknown-topic");
return;
}
const selectedTopic = delivery.event.topic as QueryInvalidationTopic;
if (delivery.ordering === "GAP") {
for (const topic of dependencies.invalidationIndex.namespacesForTopic.keys()) {
pendingRemote.add(topic as QueryInvalidationTopic);
}
report("sequence-gap");
} else {
pendingRemote.add(selectedTopic);
}
if (!resetting) void flushRemote();
}
function flushRemote(): Promise<void> {
if (disposed || resetting) return Promise.resolve();
if (flushPromise) return flushPromise;
const expectedGeneration = lifecycleGeneration;
flushPromise = Promise.resolve()
.then(async () => {
while (
!disposed &&
!resetting &&
expectedGeneration === lifecycleGeneration
) {
const ready = [...pendingRemote].filter(
(topic) => (mutationLeases.get(topic) ?? 0) === 0,
);
if (ready.length === 0) return;
for (const topic of ready) {
pendingRemote.delete(topic);
}
await invalidateLocal(ready, expectedGeneration);
}
})
.catch(() => {
report("remote-flush");
})
.finally(() => {
flushPromise = null;
if (
!disposed &&
!resetting &&
[...pendingRemote].some(
(topic) => (mutationLeases.get(topic) ?? 0) === 0,
)
) {
void flushRemote();
}
});
return flushPromise;
}
function uniqueTopics(
topics: readonly QueryInvalidationTopic[],
): readonly QueryInvalidationTopic[] {
const unique = [...new Set(topics)];
for (const topic of unique) namespacesFor(topic);
return unique;
}
function report(operation: string): void {
try {
dependencies.diagnostics?.record({
level: "warn",
eventId: "cache.operation.failed",
context: {
operation,
error_kind: "QUERY_CACHE_FAILURE",
},
});
} catch {
// Cache correctness and cleanup do not depend on diagnostics.
}
}
return Object.freeze({
async invalidate(
topics: readonly QueryInvalidationTopic[],
): Promise<void> {
if (disposed) return;
const selectedTopics = uniqueTopics(topics);
await invalidateLocal(selectedTopics);
for (const topic of selectedTopics) {
const topicVersion = dependencies.topicVersions.get(topic);
if (topicVersion === undefined) {
throw new TypeError("Unregistered query invalidation topic.");
}
const published = dependencies.crossContext?.publish({
topic,
topicVersion,
});
if (published && !published.ok) {
report("cross-context-publish");
}
}
},
beginMutation(
topics: readonly QueryInvalidationTopic[],
): QueryMutationLease {
if (disposed) {
throw new TypeError("Query invalidation coordinator is disposed.");
}
const selectedTopics = uniqueTopics(topics);
for (const topic of selectedTopics) {
mutationLeases.set(
topic,
(mutationLeases.get(topic) ?? 0) + 1,
);
}
let released = false;
return Object.freeze({
async release() {
if (released) return;
released = true;
for (const topic of selectedTopics) {
const remaining = (mutationLeases.get(topic) ?? 1) - 1;
if (remaining <= 0) {
mutationLeases.delete(topic);
} else {
mutationLeases.set(topic, remaining);
}
}
await flushRemote();
},
});
},
async resetLocal() {
if (disposed) return;
if (resetPromise) return resetPromise;
resetting = true;
lifecycleGeneration += 1;
pendingRemote.clear();
mutationLeases.clear();
const activeFlush = flushPromise;
resetPromise = (async () => {
try {
await activeFlush;
} catch {
report("reset-flush");
}
let cancellationFailed = false;
try {
await dependencies.queryClient.cancelQueries();
} catch {
report("reset-cancel");
cancellationFailed = true;
}
dependencies.queryClient.clear();
if (cancellationFailed) {
throw new TypeError("mandatory query cancellation failed");
}
})().finally(() => {
resetting = false;
resetPromise = null;
if (
!disposed &&
[...pendingRemote].some(
(topic) => (mutationLeases.get(topic) ?? 0) === 0,
)
) {
void flushRemote();
}
});
return resetPromise;
},
dispose() {
if (disposed) return;
disposed = true;
unsubscribe?.();
unsubscribeQueryCache();
dependencies.crossContext?.close();
pendingRemote.clear();
mutationLeases.clear();
flushPromise = null;
resetPromise = null;
},
});
}
function validateConfiguration(
index: InvalidationRegistryIndex,
topicVersions: ReadonlyMap<string, number>,
): void {
if (
index.namespacesForTopic.size > INVALIDATION_REGISTRY_BOUNDS.maxTopics ||
topicVersions.size !== index.namespacesForTopic.size
) {
throw new TypeError("Query invalidation registry is invalid.");
}
for (const [topic, namespaces] of index.namespacesForTopic) {
const version = topicVersions.get(topic);
if (
namespaces.length < 1 ||
!Number.isSafeInteger(version) ||
(version ?? 0) < 1
) {
throw new TypeError("Query invalidation registry is invalid.");
}
const namespaceKeys = new Set<string>();
for (const namespace of namespaces) {
const key = queryNamespaceIdentityKey(namespace);
if (namespaceKeys.has(key)) {
throw new TypeError("Query invalidation registry is invalid.");
}
namespaceKeys.add(key);
}
}
for (const topic of topicVersions.keys()) {
if (!index.namespacesForTopic.has(topic)) {
throw new TypeError("Query invalidation registry is invalid.");
}
}
}
/**
* 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;
}
}