333 lines
9.2 KiB
TypeScript
333 lines
9.2 KiB
TypeScript
import type { QueryClient } from "@tanstack/react-query";
|
|
|
|
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts";
|
|
import type {
|
|
QueryInvalidationCoordinator,
|
|
QueryInvalidationTopic,
|
|
QueryMutationLease,
|
|
} from "../../contracts/query-invalidation.ts";
|
|
import { isCacheInvalidationTopic } from "../../contracts/cache-invalidation.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>
|
|
>;
|
|
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.
|
|
*/
|
|
export function createTanStackCacheCoordinator(
|
|
dependencies: TanStackCacheCoordinatorDependencies,
|
|
): QueryInvalidationCoordinator {
|
|
const definitions = buildDefinitions(dependencies.queryRegistry);
|
|
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 definition(topic: QueryInvalidationTopic): RuntimeDefinition {
|
|
const selected = definitions.get(topic);
|
|
if (!selected) {
|
|
throw new TypeError("Unregistered query invalidation topic.");
|
|
}
|
|
return selected;
|
|
}
|
|
|
|
async function invalidateLocal(
|
|
topic: QueryInvalidationTopic,
|
|
expectedGeneration = lifecycleGeneration,
|
|
): Promise<void> {
|
|
if (
|
|
disposed ||
|
|
resetting ||
|
|
expectedGeneration !== lifecycleGeneration
|
|
) {
|
|
return;
|
|
}
|
|
const selected = definition(topic);
|
|
try {
|
|
await dependencies.queryClient.invalidateQueries({
|
|
queryKey: selected.namespace,
|
|
exact: false,
|
|
refetchType: "active",
|
|
});
|
|
} catch {
|
|
report("invalidate");
|
|
}
|
|
}
|
|
|
|
function receiveRemote(
|
|
delivery: CrossContextInvalidationDelivery,
|
|
): void {
|
|
if (disposed) return;
|
|
const selected = definitions.get(delivery.event.topic);
|
|
if (!selected) {
|
|
report("unknown-topic");
|
|
return;
|
|
}
|
|
|
|
if (delivery.ordering === "GAP") {
|
|
for (const candidate of definitions.values()) {
|
|
pendingRemote.add(candidate.topic);
|
|
}
|
|
report("sequence-gap");
|
|
} else {
|
|
pendingRemote.add(selected.topic);
|
|
}
|
|
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(topic, 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) definition(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);
|
|
for (const topic of selectedTopics) {
|
|
const selected = definition(topic);
|
|
await invalidateLocal(topic);
|
|
const published = dependencies.crossContext?.publish({
|
|
topic,
|
|
topicVersion: selected.version,
|
|
});
|
|
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 buildDefinitions(
|
|
registry: Readonly<
|
|
Record<string, InstalledQueryInvalidationDefinition>
|
|
>,
|
|
): ReadonlyMap<string, RuntimeDefinition> {
|
|
const definitions = new Map<string, RuntimeDefinition>();
|
|
for (const candidate of Object.values(registry)) {
|
|
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)
|
|
) {
|
|
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,
|
|
}),
|
|
);
|
|
}
|
|
// 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;
|
|
}
|
|
}
|