feat: 기능 추가 과정중
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
import type { CacheScopeSnapshot } from "../../contracts/server-state-scope.ts";
|
||||
|
||||
export type ConditionalValidatorBinding = Readonly<{
|
||||
definitionId: string;
|
||||
identityToken: string;
|
||||
representationVersion: number;
|
||||
scope: CacheScopeSnapshot;
|
||||
}>;
|
||||
|
||||
export type ConditionalValidatorStore = Readonly<{
|
||||
install(
|
||||
binding: ConditionalValidatorBinding,
|
||||
validator: string,
|
||||
cacheRevision: number,
|
||||
): boolean;
|
||||
prepare(
|
||||
binding: ConditionalValidatorBinding,
|
||||
cacheRevision: number,
|
||||
): string | null;
|
||||
acceptNotModified(
|
||||
binding: ConditionalValidatorBinding,
|
||||
cacheRevision: number,
|
||||
hasMappedValue: boolean,
|
||||
): boolean;
|
||||
remove(binding: ConditionalValidatorBinding): void;
|
||||
clear(): void;
|
||||
}>;
|
||||
|
||||
type ValidatorRow = {
|
||||
validator: string;
|
||||
cacheRevision: number;
|
||||
generation: number;
|
||||
};
|
||||
|
||||
export function createConditionalValidatorStore(
|
||||
maxEntries = 1_024,
|
||||
): ConditionalValidatorStore {
|
||||
if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
|
||||
throw new TypeError("Invalid conditional validator capacity.");
|
||||
}
|
||||
const rows = new Map<string, ValidatorRow>();
|
||||
|
||||
function key(binding: ConditionalValidatorBinding): string | null {
|
||||
if (
|
||||
!binding.scope.isCurrent() ||
|
||||
!binding.definitionId ||
|
||||
!/^[A-Za-z0-9._:-]{16,128}$/.test(binding.identityToken) ||
|
||||
!Number.isSafeInteger(binding.representationVersion) ||
|
||||
binding.representationVersion < 1
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return [
|
||||
binding.scope.fingerprint,
|
||||
binding.definitionId,
|
||||
binding.identityToken,
|
||||
binding.representationVersion,
|
||||
].join(":");
|
||||
}
|
||||
|
||||
return Object.freeze({
|
||||
install(binding, validator, cacheRevision) {
|
||||
const selectedKey = key(binding);
|
||||
if (
|
||||
!selectedKey ||
|
||||
!isSafeEntityTag(validator) ||
|
||||
!Number.isSafeInteger(cacheRevision) ||
|
||||
cacheRevision < 0
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (!rows.has(selectedKey) && rows.size >= maxEntries) return false;
|
||||
rows.set(selectedKey, {
|
||||
validator,
|
||||
cacheRevision,
|
||||
generation: binding.scope.generation,
|
||||
});
|
||||
return true;
|
||||
},
|
||||
prepare(binding, cacheRevision) {
|
||||
const selectedKey = key(binding);
|
||||
if (!selectedKey) return null;
|
||||
const row = rows.get(selectedKey);
|
||||
return row &&
|
||||
row.generation === binding.scope.generation &&
|
||||
row.cacheRevision === cacheRevision
|
||||
? row.validator
|
||||
: null;
|
||||
},
|
||||
acceptNotModified(binding, cacheRevision, hasMappedValue) {
|
||||
const selectedKey = key(binding);
|
||||
if (!selectedKey || !hasMappedValue) return false;
|
||||
const row = rows.get(selectedKey);
|
||||
return Boolean(
|
||||
row &&
|
||||
row.generation === binding.scope.generation &&
|
||||
row.cacheRevision === cacheRevision,
|
||||
);
|
||||
},
|
||||
remove(binding) {
|
||||
const selectedKey = key(binding);
|
||||
if (selectedKey) rows.delete(selectedKey);
|
||||
},
|
||||
clear() {
|
||||
rows.clear();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function isSafeEntityTag(value: string): boolean {
|
||||
if (value.length < 3 || value.length > 256) return false;
|
||||
const opaque = value.startsWith('W/"')
|
||||
? value.slice(3, -1)
|
||||
: value.startsWith('"')
|
||||
? value.slice(1, -1)
|
||||
: null;
|
||||
if (opaque === null || !value.endsWith('"')) return false;
|
||||
return [...opaque].every((character) => {
|
||||
const code = character.codePointAt(0) ?? 0;
|
||||
return code === 0x21 || (code >= 0x23 && code <= 0x7e) ||
|
||||
(code >= 0x80 && code <= 0xff);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import type { Result } from "../../application/result.ts";
|
||||
import type {
|
||||
CursorPage,
|
||||
CursorPaginationProfile,
|
||||
CursorPaginationRuntime,
|
||||
} from "../../contracts/cursor-pagination.ts";
|
||||
import { createFailure } from "../../contracts/errors.ts";
|
||||
|
||||
export function createCursorPaginationRuntime<Value>(dependencies: Readonly<{
|
||||
definitionId: string;
|
||||
profile: CursorPaginationProfile;
|
||||
loadPage(
|
||||
cursor: string | null,
|
||||
context: Readonly<{ signal?: AbortSignal }>,
|
||||
): Promise<Result<CursorPage<Value>>>;
|
||||
}>): CursorPaginationRuntime<Value> {
|
||||
validateProfile(dependencies.profile);
|
||||
return Object.freeze({
|
||||
async loadAll(context) {
|
||||
const items: Value[] = [];
|
||||
const cursors = new Set<string>();
|
||||
let cursor: string | null = null;
|
||||
let snapshot: string | null | undefined;
|
||||
for (
|
||||
let pageIndex = 0;
|
||||
pageIndex < dependencies.profile.maxPages;
|
||||
pageIndex += 1
|
||||
) {
|
||||
if (context.signal?.aborted) {
|
||||
return failure("REQUEST_ABORTED", "PAGINATION_ABORTED");
|
||||
}
|
||||
const result = await dependencies.loadPage(cursor, context);
|
||||
if (!result.ok) return result;
|
||||
const page = result.value;
|
||||
if (!isValidPage(page, dependencies.profile)) {
|
||||
return failure(
|
||||
"PAGINATION_CONTRACT_VIOLATION",
|
||||
"PAGINATION_PAGE_INVALID",
|
||||
);
|
||||
}
|
||||
if (snapshot === undefined) {
|
||||
snapshot = page.snapshotToken;
|
||||
} else if (snapshot !== page.snapshotToken) {
|
||||
return failure(
|
||||
"PAGINATION_CONTRACT_VIOLATION",
|
||||
"PAGINATION_SNAPSHOT_CHANGED",
|
||||
);
|
||||
}
|
||||
items.push(...page.items);
|
||||
if (
|
||||
items.length > dependencies.profile.maxTotalItems ||
|
||||
estimatedBytes(items) > dependencies.profile.maxEstimatedBytes
|
||||
) {
|
||||
return failure(
|
||||
"RESULT_LIMIT_EXCEEDED",
|
||||
"PAGINATION_RESULT_LIMIT",
|
||||
);
|
||||
}
|
||||
if (!page.hasMore) return { ok: true, value: Object.freeze(items) };
|
||||
const nextCursor = page.nextCursor;
|
||||
if (!nextCursor || cursors.has(nextCursor)) {
|
||||
return failure(
|
||||
"PAGINATION_CONTRACT_VIOLATION",
|
||||
"PAGINATION_CURSOR_LOOP",
|
||||
);
|
||||
}
|
||||
cursors.add(nextCursor);
|
||||
cursor = nextCursor;
|
||||
}
|
||||
return failure(
|
||||
"RESULT_LIMIT_EXCEEDED",
|
||||
"PAGINATION_PAGE_LIMIT",
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
function failure(
|
||||
kind:
|
||||
| "PAGINATION_CONTRACT_VIOLATION"
|
||||
| "RESULT_LIMIT_EXCEEDED"
|
||||
| "REQUEST_ABORTED",
|
||||
code: string,
|
||||
) {
|
||||
return {
|
||||
ok: false as const,
|
||||
error: createFailure(kind, dependencies.definitionId, 0, { code }),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function validateProfile(profile: CursorPaginationProfile): void {
|
||||
if (
|
||||
!profile.profileId ||
|
||||
!Number.isSafeInteger(profile.maxPages) ||
|
||||
profile.maxPages < 1 ||
|
||||
profile.maxPages > 100 ||
|
||||
!Number.isSafeInteger(profile.maxTotalItems) ||
|
||||
profile.maxTotalItems < 1 ||
|
||||
!Number.isSafeInteger(profile.maxEstimatedBytes) ||
|
||||
profile.maxEstimatedBytes < 1 ||
|
||||
!Number.isSafeInteger(profile.maxCursorBytes) ||
|
||||
profile.maxCursorBytes < 1 ||
|
||||
profile.maxCursorBytes > 4_096
|
||||
) {
|
||||
throw new TypeError("Invalid cursor pagination profile.");
|
||||
}
|
||||
}
|
||||
|
||||
function isValidPage<Value>(
|
||||
page: CursorPage<Value>,
|
||||
profile: CursorPaginationProfile,
|
||||
): boolean {
|
||||
const encoder = new TextEncoder();
|
||||
return (
|
||||
Boolean(page) &&
|
||||
Array.isArray(page.items) &&
|
||||
typeof page.hasMore === "boolean" &&
|
||||
page.hasMore === (page.nextCursor !== null) &&
|
||||
(page.nextCursor === null ||
|
||||
(typeof page.nextCursor === "string" &&
|
||||
page.nextCursor.length > 0 &&
|
||||
encoder.encode(page.nextCursor).byteLength <=
|
||||
profile.maxCursorBytes)) &&
|
||||
(page.snapshotToken === null ||
|
||||
(typeof page.snapshotToken === "string" &&
|
||||
page.snapshotToken.length > 0 &&
|
||||
encoder.encode(page.snapshotToken).byteLength <=
|
||||
profile.maxCursorBytes)) &&
|
||||
(profile.allowSparsePage || !page.hasMore || page.items.length > 0)
|
||||
);
|
||||
}
|
||||
|
||||
function estimatedBytes(value: unknown): number {
|
||||
try {
|
||||
return new TextEncoder().encode(JSON.stringify(value)).byteLength;
|
||||
} catch {
|
||||
return Number.POSITIVE_INFINITY;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import type { AuthSessionPort } from "../../application/ports/auth-session-port.ts";
|
||||
import type { QueryInvalidationCoordinator } from "../../contracts/query-invalidation.ts";
|
||||
import {
|
||||
createRuntimeIdentityRegistry,
|
||||
type RuntimeIdentityRegistry,
|
||||
} from "../../contracts/query-keys.ts";
|
||||
import type {
|
||||
CacheScopeSnapshot,
|
||||
ServerStateScopeRuntime,
|
||||
} from "../../contracts/server-state-scope.ts";
|
||||
|
||||
export function createServerStateScopeRuntime(dependencies: Readonly<{
|
||||
session: Pick<AuthSessionPort, "subscribe">;
|
||||
queryInvalidation: QueryInvalidationCoordinator;
|
||||
tokenFactory?: () => string;
|
||||
}>): ServerStateScopeRuntime {
|
||||
const listeners = new Set<() => void>();
|
||||
let generation = 1;
|
||||
let identities = newIdentityRegistry(dependencies.tokenFactory);
|
||||
let fingerprint = scopeFingerprint(dependencies.tokenFactory);
|
||||
let disposed = false;
|
||||
let resetChain = Promise.resolve();
|
||||
|
||||
function createSnapshot(): CacheScopeSnapshot {
|
||||
const capturedGeneration = generation;
|
||||
const capturedIdentities = identities;
|
||||
return Object.freeze({
|
||||
generation: capturedGeneration,
|
||||
fingerprint,
|
||||
identities: capturedIdentities,
|
||||
isCurrent: () =>
|
||||
!disposed &&
|
||||
generation === capturedGeneration &&
|
||||
identities === capturedIdentities,
|
||||
});
|
||||
}
|
||||
let currentSnapshot = createSnapshot();
|
||||
|
||||
const unsubscribe = dependencies.session.subscribe(() => {
|
||||
if (disposed) return;
|
||||
const previousIdentities = identities;
|
||||
const targetGeneration = ++generation;
|
||||
resetChain = resetChain
|
||||
.then(() => dependencies.queryInvalidation.resetLocal())
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
previousIdentities.close();
|
||||
if (disposed || generation !== targetGeneration) return;
|
||||
identities = newIdentityRegistry(dependencies.tokenFactory);
|
||||
fingerprint = scopeFingerprint(dependencies.tokenFactory);
|
||||
currentSnapshot = createSnapshot();
|
||||
for (const listener of listeners) listener();
|
||||
});
|
||||
});
|
||||
|
||||
return Object.freeze({
|
||||
getSnapshot: () => currentSnapshot,
|
||||
subscribe(listener) {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
},
|
||||
dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
unsubscribe();
|
||||
listeners.clear();
|
||||
identities.close();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function newIdentityRegistry(
|
||||
tokenFactory: (() => string) | undefined,
|
||||
): RuntimeIdentityRegistry {
|
||||
return createRuntimeIdentityRegistry({
|
||||
...(tokenFactory ? { tokenFactory } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function scopeFingerprint(tokenFactory: (() => string) | undefined): string {
|
||||
const candidate = tokenFactory?.() ?? crypto.randomUUID();
|
||||
if (!/^[A-Za-z0-9._:-]{16,128}$/.test(candidate)) {
|
||||
throw new TypeError("Invalid cache scope fingerprint.");
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
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");
|
||||
}
|
||||
try {
|
||||
await dependencies.queryClient.cancelQueries();
|
||||
} catch {
|
||||
report("reset-cancel");
|
||||
}
|
||||
dependencies.queryClient.clear();
|
||||
})().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,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (definitions.size === 0) {
|
||||
throw new TypeError(
|
||||
"Query invalidation registry requires at least one topic.",
|
||||
);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
+22
-21
@@ -1,7 +1,13 @@
|
||||
import { MutationCache, QueryCache, QueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { createFailure } from "../../contracts/errors.js";
|
||||
import { safeErrorKind } from "../../contracts/diagnostics.js";
|
||||
import { createFailure } from "../../contracts/errors.ts";
|
||||
import { safeErrorKind } from "../../contracts/diagnostics.ts";
|
||||
import type { DiagnosticsPort } from "../../application/ports/diagnostics-port.ts";
|
||||
import type { QueryCachePort } from "../../application/ports/query-cache-port.ts";
|
||||
|
||||
export type QueryCacheDependencies = Readonly<{
|
||||
diagnostics?: DiagnosticsPort;
|
||||
}>;
|
||||
|
||||
export const QUERY_CACHE_DEFAULTS = Object.freeze({
|
||||
staleTime: 30_000,
|
||||
@@ -12,12 +18,10 @@ export const QUERY_CACHE_DEFAULTS = Object.freeze({
|
||||
persistence: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {{diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort}} [dependencies]
|
||||
*/
|
||||
export function createQueryClient(dependencies = {}) {
|
||||
/** @param {string} operation @param {unknown} error */
|
||||
function report(operation, error) {
|
||||
export function createQueryClient(
|
||||
dependencies: QueryCacheDependencies = {},
|
||||
): QueryClient {
|
||||
function report(operation: string, error: unknown): void {
|
||||
try {
|
||||
dependencies.diagnostics?.record({
|
||||
level: "warn",
|
||||
@@ -52,12 +56,10 @@ export function createQueryClient(dependencies = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {QueryClient} queryClient
|
||||
* @param {{diagnostics?: import("../../application/ports/diagnostics-port.js").DiagnosticsPort}} [dependencies]
|
||||
* @returns {import("../../application/ports/query-cache-port.js").QueryCachePort}
|
||||
*/
|
||||
export function createQueryCacheAdapter(queryClient, dependencies = {}) {
|
||||
export function createQueryCacheAdapter(
|
||||
queryClient: QueryClient,
|
||||
dependencies: QueryCacheDependencies = {},
|
||||
): QueryCachePort {
|
||||
return Object.freeze({
|
||||
read(key) {
|
||||
try {
|
||||
@@ -85,12 +87,11 @@ export function createQueryCacheAdapter(queryClient, dependencies = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} phase
|
||||
* @param {readonly unknown[]} key
|
||||
* @param {import("../../application/ports/diagnostics-port.js").DiagnosticsPort | undefined} diagnostics
|
||||
*/
|
||||
function cacheFailure(phase, key, diagnostics) {
|
||||
function cacheFailure(
|
||||
phase: string,
|
||||
key: readonly unknown[],
|
||||
diagnostics: DiagnosticsPort | undefined,
|
||||
): Readonly<{ ok: false; error: ReturnType<typeof createFailure> }> {
|
||||
const namespace = typeof key[0] === "string" ? key[0] : "unknown";
|
||||
try {
|
||||
diagnostics?.record({
|
||||
@@ -105,7 +106,7 @@ function cacheFailure(phase, key, diagnostics) {
|
||||
// Cache behavior remains independent from diagnostics.
|
||||
}
|
||||
return {
|
||||
ok: /** @type {false} */ (false),
|
||||
ok: false,
|
||||
error: createFailure("QUERY_CACHE_FAILURE", "QUERY_CACHE", 0, {
|
||||
code: `QUERY_CACHE_${phase.toUpperCase()}_FAILED`,
|
||||
causeClass: `namespace:${namespace}`,
|
||||
Reference in New Issue
Block a user