fix: index many-to-many query invalidation

This commit is contained in:
DongHyeonka
2026-08-01 23:17:09 +09:00
parent 853c2e3f30
commit 73a50426d6
18 changed files with 574 additions and 325 deletions
@@ -2,42 +2,30 @@ 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 { isCacheInvalidationTopic } from "../../contracts/cache-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 InstalledQueryInvalidationDefinition = Readonly<{
namespace: readonly unknown[];
invalidationTopic: QueryInvalidationTopic;
crossContext: "invalidate-only";
version: number;
persistence: "disabled";
}>;
export type TanStackCacheCoordinatorDependencies = Readonly<{
queryClient: QueryClient;
queryRegistry: Readonly<
Record<string, InstalledQueryInvalidationDefinition>
>;
invalidationIndex: InvalidationRegistryIndex;
topicVersions: ReadonlyMap<string, number>;
crossContext?: BrowserCrossContextInvalidation;
diagnostics?: DiagnosticsPort;
}>;
type RuntimeDefinition = Readonly<{
namespace: readonly unknown[];
topic: QueryInvalidationTopic;
version: number;
}>;
const MAX_NAMESPACE_PARTS = 8;
const MAX_NAMESPACE_BYTES = 1_024;
/**
* Joins registry-owned invalidation topics to TanStack Query without putting a
* query key or cached value on the cross-context wire.
@@ -45,7 +33,10 @@ const MAX_NAMESPACE_BYTES = 1_024;
export function createTanStackCacheCoordinator(
dependencies: TanStackCacheCoordinatorDependencies,
): QueryInvalidationCoordinator {
const definitions = buildDefinitions(dependencies.queryRegistry);
validateConfiguration(
dependencies.invalidationIndex,
dependencies.topicVersions,
);
const mutationLeases = new Map<QueryInvalidationTopic, number>();
const pendingRemote = new Set<QueryInvalidationTopic>();
let disposed = false;
@@ -58,8 +49,10 @@ export function createTanStackCacheCoordinator(
receiveRemote(delivery);
});
function definition(topic: QueryInvalidationTopic): RuntimeDefinition {
const selected = definitions.get(topic);
function namespacesFor(
topic: QueryInvalidationTopic,
): readonly QueryNamespaceIdentity[] {
const selected = dependencies.invalidationIndex.namespacesForTopic.get(topic);
if (!selected) {
throw new TypeError("Unregistered query invalidation topic.");
}
@@ -67,7 +60,7 @@ export function createTanStackCacheCoordinator(
}
async function invalidateLocal(
topic: QueryInvalidationTopic,
topics: readonly QueryInvalidationTopic[],
expectedGeneration = lifecycleGeneration,
): Promise<void> {
if (
@@ -77,15 +70,22 @@ export function createTanStackCacheCoordinator(
) {
return;
}
const selected = definition(topic);
try {
await dependencies.queryClient.invalidateQueries({
queryKey: selected.namespace,
exact: false,
refetchType: "active",
});
} catch {
report("invalidate");
const namespaces = new Map<string, QueryNamespaceIdentity>();
for (const topic of topics) {
for (const namespace of namespacesFor(topic)) {
namespaces.set(queryNamespaceIdentityKey(namespace), namespace);
}
}
for (const namespace of namespaces.values()) {
try {
await dependencies.queryClient.invalidateQueries({
queryKey: createQueryInvalidationPrefix(namespace),
exact: false,
refetchType: "active",
});
} catch {
report("invalidate");
}
}
}
@@ -93,19 +93,23 @@ export function createTanStackCacheCoordinator(
delivery: CrossContextInvalidationDelivery,
): void {
if (disposed) return;
const selected = definitions.get(delivery.event.topic);
if (!selected) {
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 candidate of definitions.values()) {
pendingRemote.add(candidate.topic);
for (const topic of dependencies.invalidationIndex.namespacesForTopic.keys()) {
pendingRemote.add(topic as QueryInvalidationTopic);
}
report("sequence-gap");
} else {
pendingRemote.add(selected.topic);
pendingRemote.add(selectedTopic);
}
if (!resetting) void flushRemote();
}
@@ -128,8 +132,8 @@ export function createTanStackCacheCoordinator(
if (ready.length === 0) return;
for (const topic of ready) {
pendingRemote.delete(topic);
await invalidateLocal(topic, expectedGeneration);
}
await invalidateLocal(ready, expectedGeneration);
}
})
.catch(() => {
@@ -154,7 +158,7 @@ export function createTanStackCacheCoordinator(
topics: readonly QueryInvalidationTopic[],
): readonly QueryInvalidationTopic[] {
const unique = [...new Set(topics)];
for (const topic of unique) definition(topic);
for (const topic of unique) namespacesFor(topic);
return unique;
}
@@ -179,12 +183,15 @@ export function createTanStackCacheCoordinator(
): Promise<void> {
if (disposed) return;
const selectedTopics = uniqueTopics(topics);
await invalidateLocal(selectedTopics);
for (const topic of selectedTopics) {
const selected = definition(topic);
await invalidateLocal(topic);
const topicVersion = dependencies.topicVersions.get(topic);
if (topicVersion === undefined) {
throw new TypeError("Unregistered query invalidation topic.");
}
const published = dependencies.crossContext?.publish({
topic,
topicVersion: selected.version,
topicVersion,
});
if (published && !published.ok) {
report("cross-context-publish");
@@ -276,57 +283,37 @@ export function createTanStackCacheCoordinator(
});
}
function buildDefinitions(
registry: Readonly<
Record<string, InstalledQueryInvalidationDefinition>
>,
): ReadonlyMap<string, RuntimeDefinition> {
const definitions = new Map<string, RuntimeDefinition>();
for (const candidate of Object.values(registry)) {
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 (
!candidate ||
!isCacheInvalidationTopic(candidate.invalidationTopic) ||
candidate.crossContext !== "invalidate-only" ||
candidate.persistence !== "disabled" ||
!Number.isSafeInteger(candidate.version) ||
candidate.version < 1 ||
!isSafeNamespace(candidate.namespace) ||
definitions.has(candidate.invalidationTopic)
namespaces.length < 1 ||
!Number.isSafeInteger(version) ||
(version ?? 0) < 1
) {
throw new TypeError("Query invalidation registry is invalid.");
}
definitions.set(
candidate.invalidationTopic,
Object.freeze({
namespace: Object.freeze(structuredClone(candidate.namespace)),
topic: candidate.invalidationTopic,
version: candidate.version,
}),
);
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);
}
}
// An empty registry is a legitimate state: a template with no installed
// feature has no invalidation topic. Every per-entry rule above still
// applies, and an unregistered topic still fails at the call site.
return definitions;
}
function isSafeNamespace(value: unknown): value is readonly unknown[] {
if (
!Array.isArray(value) ||
value.length < 1 ||
value.length > MAX_NAMESPACE_PARTS ||
typeof value[0] !== "string"
) {
return false;
}
try {
const serialized = JSON.stringify(value);
return (
typeof serialized === "string" &&
new TextEncoder().encode(serialized).byteLength <=
MAX_NAMESPACE_BYTES
);
} catch {
return false;
for (const topic of topicVersions.keys()) {
if (!index.namespacesForTopic.has(topic)) {
throw new TypeError("Query invalidation registry is invalid.");
}
}
}