Files
clean-architecture-frontend…/src/adapters/query-cache/tanstack-cache-coordinator.ts
T
DongHyeonkaandClaude Opus 5.5 fcd37a9d16 perf(query-cache): invalidate namespaces in parallel (Q-6.3-8)
TanStack 5 invalidateQueries resolves only after the active refetches
finish. The coordinator awaited each namespace in a for loop, so one
invalidation (and lease.release(), which waits on it) took the sum of
every namespace's refetch time. The namespaces now run through
Promise.allSettled; each rejected one is still reported once as
"invalidate".

Verified: new test holds the first namespace's refetch open and failed
RED (second invalidateQueries never started); it now passes and checks
that a failure is reported once. All lane gates pass except the known
removal-fixture test; provider-guardian-transaction timed out once under
load and passed on rerun.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:41:45 +09:00

323 lines
9.4 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,
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);
});
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?.();
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.");
}
}
}