Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(queries): per query persister (#1407)

teoddfb8731e180
diff --git a/js/app/packages/queries/client.ts b/js/app/packages/queries/client.ts
index ee23b4f590..5ec7bccee7 100644
--- a/js/app/packages/queries/client.ts
+++ b/js/app/packages/queries/client.ts
@@ -1,10 +1,7 @@
import { QueryClient } from '@tanstack/solid-query';
-import { createIDBPersister } from './storage/idb';
-import {
- createPersistenceKey,
- queryKeyHasPrefix,
- setupQueryPersistence,
-} from './persistence';
+import { createPerQueryIDBStore } from './persistence/per-query-idb';
+import { partialMatchKey } from '@tanstack/query-core';
+import { createPersistenceKey, setupQueryPersistence } from './persistence';
export const queryClient = new QueryClient({
defaultOptions: {
@@ -17,25 +14,33 @@ export const queryClient = new QueryClient({
},
});
+const buster = import.meta.env.__APP_VERSION__ ?? 'dev';
+const SEVEN_DAYS_MS = 1000 * 60 * 60 * 24 * 7;
+
+// Clean up orphaned v0 databases from the old whole-cache persistence format
+try {
+ indexedDB.deleteDatabase(createPersistenceKey('channels', 0));
+ indexedDB.deleteDatabase(createPersistenceKey('email-threads', 0));
+} catch {}
+
setupQueryPersistence({
queryClient,
- buster: import.meta.env.__APP_VERSION__ ?? 'dev',
scopes: [
{
- persister: createIDBPersister({
- key: createPersistenceKey('channels', 0),
+ store: createPerQueryIDBStore({
+ dbName: createPersistenceKey('channels', 1),
}),
- // 7 days in milliseconds
- maxAgeMs: 1000 * 60 * 60 * 24 * 7,
- shouldDehydrateQuery: (q) => queryKeyHasPrefix(q.queryKey, ['channel']),
+ maxAgeMs: SEVEN_DAYS_MS,
+ buster,
+ shouldPersist: (key) => partialMatchKey(key, ['channel']),
},
{
- persister: createIDBPersister({
- key: createPersistenceKey('email-threads', 0),
+ store: createPerQueryIDBStore({
+ dbName: createPersistenceKey('email-threads', 1),
}),
- maxAgeMs: 1000 * 60 * 60 * 24 * 7,
- shouldDehydrateQuery: (q) =>
- queryKeyHasPrefix(q.queryKey, ['email', 'threadMessages']),
+ maxAgeMs: SEVEN_DAYS_MS,
+ buster,
+ shouldPersist: (key) => partialMatchKey(key, ['email', 'threadMessages']),
},
],
});
diff --git a/js/app/packages/queries/persistence.test.ts b/js/app/packages/queries/persistence.test.ts
new file mode 100644
index 0000000000..da4d2249c9
--- /dev/null
+++ b/js/app/packages/queries/persistence.test.ts
@@ -0,0 +1,270 @@
+import { partialMatchKey } from '@tanstack/query-core';
+import { QueryClient } from '@tanstack/solid-query';
+import { describe, expect, it, vi } from 'vitest';
+import type {
+ PerQueryPersistence,
+ PersistedQueryEntry,
+} from './persistence/per-query-idb';
+import { setupQueryPersistence, type PersistScope } from './persistence';
+
+function createMockStore(): PerQueryPersistence & {
+ entries: Map<string, PersistedQueryEntry>;
+ get: ReturnType<typeof vi.fn>;
+ set: ReturnType<typeof vi.fn>;
+ remove: ReturnType<typeof vi.fn>;
+ flush: ReturnType<typeof vi.fn>;
+} {
+ const entries = new Map<string, PersistedQueryEntry>();
+ return {
+ entries,
+ get: vi.fn(async (hash: string) => entries.get(hash)),
+ set: vi.fn((entry: PersistedQueryEntry) => {
+ entries.set(entry.queryHash, entry);
+ }),
+ remove: vi.fn((hash: string) => {
+ entries.delete(hash);
+ }),
+ flush: vi.fn(async () => {}),
+ };
+}
+
+function createScope(
+ prefix: readonly unknown[],
+ store: PerQueryPersistence,
+ overrides?: Partial<PersistScope>
+): PersistScope {
+ return {
+ store,
+ maxAgeMs: 1000 * 60 * 60 * 24 * 7,
+ buster: 'test',
+ shouldPersist: (key) => partialMatchKey(key, prefix),
+ ...overrides,
+ };
+}
+
+describe('setupQueryPersistence', () => {
+ it('writes only the changed query on update', () => {
+ const queryClient = new QueryClient();
+ const store = createMockStore();
+ const scope = createScope(['channel'], store);
+
+ setupQueryPersistence({ queryClient, scopes: [scope] });
+
+ queryClient.setQueryData(['channel', 'a'], { value: 1 });
+ queryClient.setQueryData(['channel', 'b'], { value: 2 });
+
+ expect(store.set).toHaveBeenCalledTimes(2);
+ const firstCall = store.set.mock.calls[0]![0] as PersistedQueryEntry;
+ const secondCall = store.set.mock.calls[1]![0] as PersistedQueryEntry;
+ expect(firstCall.queryKey).toEqual(['channel', 'a']);
+ expect(firstCall.data).toEqual({ value: 1 });
+ expect(secondCall.queryKey).toEqual(['channel', 'b']);
+ expect(secondCall.data).toEqual({ value: 2 });
+ });
+
+ it('isolates writes to the matching scope store', () => {
+ const queryClient = new QueryClient();
+ const channelStore = createMockStore();
+ const emailStore = createMockStore();
+
+ setupQueryPersistence({
+ queryClient,
+ scopes: [
+ createScope(['channel'], channelStore),
+ createScope(['email', 'threadMessages'], emailStore),
+ ],
+ });
+
+ queryClient.setQueryData(['channel', 'a'], { value: 'ch' });
+ queryClient.setQueryData(['email', 'threadMessages', 't-1'], {
+ value: 'em',
+ });
+
+ expect(channelStore.set).toHaveBeenCalledTimes(1);
+ expect(emailStore.set).toHaveBeenCalledTimes(1);
+ expect(
+ (channelStore.set.mock.calls[0]![0] as PersistedQueryEntry).queryKey
+ ).toEqual(['channel', 'a']);
+ expect(
+ (emailStore.set.mock.calls[0]![0] as PersistedQueryEntry).queryKey
+ ).toEqual(['email', 'threadMessages', 't-1']);
+ });
+
+ it('ignores queries that match no scope', () => {
+ const queryClient = new QueryClient();
+ const store = createMockStore();
+ const scope = createScope(['channel'], store);
+
+ setupQueryPersistence({ queryClient, scopes: [scope] });
+
+ queryClient.setQueryData(['preview', 'x'], { value: 'ignored' });
+
+ expect(store.set).not.toHaveBeenCalled();
+ });
+
+ it('restores query data from store on added event', async () => {
+ const queryClient = new QueryClient();
+ const store = createMockStore();
+
+ store.entries.set('["channel","a"]', {
+ queryHash: '["channel","a"]',
+ queryKey: ['channel', 'a'],
+ data: { value: 'from-idb' },
+ dataUpdatedAt: Date.now() - 1000,
+ persistedAt: Date.now() - 1000,
+ buster: 'test',
+ });
+
+ const scope = createScope(['channel'], store);
+ setupQueryPersistence({ queryClient, scopes: [scope] });
+
+ // Trigger an 'added' event by fetching (prefetchQuery triggers added)
+ void queryClient.prefetchQuery({
+ queryKey: ['channel', 'a'],
+ queryFn: () => new Promise(() => {}), // never resolves
+ });
+
+ // Let the IDB read promise resolve
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(queryClient.getQueryData(['channel', 'a'])).toEqual({
+ value: 'from-idb',
+ });
+ });
+
+ it('does not overwrite fresh fetch data with stale IDB read (race guard)', async () => {
+ const queryClient = new QueryClient();
+ const store = createMockStore();
+
+ let resolveGet!: (value: PersistedQueryEntry | undefined) => void;
+ store.get = vi.fn(
+ () =>
+ new Promise<PersistedQueryEntry | undefined>((resolve) => {
+ resolveGet = resolve;
+ })
+ );
+
+ const scope = createScope(['channel'], store);
+ setupQueryPersistence({ queryClient, scopes: [scope] });
+
+ // Trigger added event
+ void queryClient.prefetchQuery({
+ queryKey: ['channel', 'a'],
+ queryFn: () => new Promise(() => {}),
+ });
+
+ await Promise.resolve();
+
+ // Simulate fetch completing before IDB read resolves
+ queryClient.setQueryData(['channel', 'a'], { value: 'fresh' });
+
+ // Now resolve the IDB read with stale data
+ resolveGet({
+ queryHash: '["channel","a"]',
+ queryKey: ['channel', 'a'],
+ data: { value: 'stale-idb' },
+ dataUpdatedAt: Date.now() - 60000,
+ persistedAt: Date.now() - 60000,
+ buster: 'test',
+ });
+
+ await Promise.resolve();
+ await Promise.resolve();
+
+ // Fresh data should not be overwritten
+ expect(queryClient.getQueryData(['channel', 'a'])).toEqual({
+ value: 'fresh',
+ });
+ });
+
+ it('removes expired entries instead of restoring', async () => {
+ const queryClient = new QueryClient();
+ const store = createMockStore();
+ const maxAgeMs = 1000;
+
+ store.entries.set('["channel","old"]', {
+ queryHash: '["channel","old"]',
+ queryKey: ['channel', 'old'],
+ data: { value: 'expired' },
+ dataUpdatedAt: Date.now() - maxAgeMs - 1,
+ persistedAt: Date.now() - maxAgeMs - 1,
+ buster: 'test',
+ });
+
+ const scope = createScope(['channel'], store, { maxAgeMs });
+ setupQueryPersistence({ queryClient, scopes: [scope] });
+
+ void queryClient.prefetchQuery({
+ queryKey: ['channel', 'old'],
+ queryFn: () => new Promise(() => {}),
+ });
+
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(queryClient.getQueryData(['channel', 'old'])).toBeUndefined();
+ expect(store.remove).toHaveBeenCalledWith('["channel","old"]');
+ });
+
+ it('removes buster-mismatched entries instead of restoring', async () => {
+ const queryClient = new QueryClient();
+ const store = createMockStore();
+
+ store.entries.set('["channel","v"]', {
+ queryHash: '["channel","v"]',
+ queryKey: ['channel', 'v'],
+ data: { value: 'old-version' },
+ dataUpdatedAt: Date.now() - 1000,
+ persistedAt: Date.now() - 1000,
+ buster: 'old-buster',
+ });
+
+ const scope = createScope(['channel'], store, { buster: 'new-buster' });
+ setupQueryPersistence({ queryClient, scopes: [scope] });
+
+ void queryClient.prefetchQuery({
+ queryKey: ['channel', 'v'],
+ queryFn: () => new Promise(() => {}),
+ });
+
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(queryClient.getQueryData(['channel', 'v'])).toBeUndefined();
+ expect(store.remove).toHaveBeenCalledWith('["channel","v"]');
+ });
+
+ it('stops persistence on unsubscribe', () => {
+ const queryClient = new QueryClient();
+ const store = createMockStore();
+ const scope = createScope(['channel'], store);
+
+ const unsubscribe = setupQueryPersistence({
+ queryClient,
+ scopes: [scope],
+ });
+
+ queryClient.setQueryData(['channel', 'a'], { value: 1 });
+ expect(store.set).toHaveBeenCalledTimes(1);
+
+ unsubscribe();
+
+ queryClient.setQueryData(['channel', 'b'], { value: 2 });
+ expect(store.set).toHaveBeenCalledTimes(1);
+ });
+
+ it('removes entry from store on query removal', () => {
+ const queryClient = new QueryClient();
+ const store = createMockStore();
+ const scope = createScope(['channel'], store);
+
+ setupQueryPersistence({ queryClient, scopes: [scope] });
+
+ queryClient.setQueryData(['channel', 'a'], { value: 1 });
+ expect(store.set).toHaveBeenCalledTimes(1);
+
+ queryClient.removeQueries({ queryKey: ['channel', 'a'] });
+ expect(store.remove).toHaveBeenCalledWith('["channel","a"]');
+ });
+});
diff --git a/js/app/packages/queries/persistence.ts b/js/app/packages/queries/persistence.ts
index 4d22910288..353adb8056 100644
--- a/js/app/packages/queries/persistence.ts
+++ b/js/app/packages/queries/persistence.ts
@@ -1,73 +1,164 @@
-import {
- type PersistQueryClientOptions,
- persistQueryClient,
-} from '@tanstack/solid-query-persist-client';
-import type { Persister } from '@tanstack/solid-query-persist-client';
-import type { QueryKey } from '@tanstack/query-core';
+import type {
+ Query,
+ QueryCacheNotifyEvent,
+ QueryKey,
+} from '@tanstack/query-core';
+import type {
+ PerQueryPersistence,
+ PersistedQueryEntry,
+} from './persistence/per-query-idb';
-type Query = NonNullable<
- PersistQueryClientOptions['dehydrateOptions']
->['shouldDehydrateQuery'] extends ((query: infer Q) => boolean) | undefined
- ? Q
- : never;
-
-type PersistQueryClient = PersistQueryClientOptions['queryClient'];
+type PersistenceKey = `${string}-persist-v${number}`;
-/**
- * Structurally compatible QueryClient type. Accepts any QueryClient instance
- * to work around version mismatches in @tanstack packages.
- */
-type QueryClientLike = {
- getQueryCache: () => unknown;
- getMutationCache: () => unknown;
-};
+/** Builds a versioned persistence key for IDB database naming. */
+export function createPersistenceKey(
+ name: string,
+ version: number
+): PersistenceKey {
+ return `${name}-persist-v${version}`;
+}
export type PersistScope = Readonly<{
- persister: Persister;
+ store: PerQueryPersistence;
maxAgeMs: number;
- shouldDehydrateQuery: (query: Query) => boolean;
+ buster: string;
+ shouldPersist: (queryKey: QueryKey) => boolean;
}>;
-export function queryKeyHasPrefix(
- key: QueryKey,
- prefix: readonly unknown[]
-): boolean {
- if (!Array.isArray(key)) return false;
- if (prefix.length > key.length) return false;
- for (let i = 0; i < prefix.length; i++) {
- if (key[i] !== prefix[i]) return false;
- }
- return true;
+type QueryClientLike = {
+ getQueryCache: () => {
+ subscribe: (listener: (event: QueryCacheNotifyEvent) => void) => () => void;
+ };
+ getQueryState: (
+ queryKey: QueryKey
+ ) => { status: string; data: unknown; dataUpdatedAt: number } | undefined;
+ setQueryData: (
+ queryKey: QueryKey,
+ data: unknown,
+ options?: { updatedAt?: number }
+ ) => void;
+};
+
+/**
+ * Validates a persisted entry against the current cache-buster and max age.
+ * Returns 'valid' if the entry can be restored, or a reason string
+ * explaining why it should be discarded.
+ */
+export function validatePersistedEntry(
+ entry: PersistedQueryEntry,
+ buster: string,
+ maxAgeMs: number
+): 'valid' | 'buster_mismatch' | 'expired' {
+ if (entry.buster !== buster) return 'buster_mismatch';
+ if (Date.now() - entry.dataUpdatedAt > maxAgeMs) return 'expired';
+ return 'valid';
}
-type PersistenceKey = `${string}-persist-v${number}`;
+/**
+ * Attempts to restore a query's data from IDB when the query is first added
+ * to the cache. Validates the entry and guards against race conditions where
+ * a fresh fetch resolves before the IDB read completes.
+ */
+async function handleRestore(
+ queryClient: QueryClientLike,
+ scope: PersistScope,
+ query: Query
+): Promise<void> {
+ const state = queryClient.getQueryState(query.queryKey);
+ if (state && state.status === 'success') return;
-export function createPersistenceKey(
- name: string,
- version: number
-): PersistenceKey {
- return `${name}-persist-v${version}`;
+ let entry: PersistedQueryEntry | undefined;
+ try {
+ entry = await scope.store.get(query.queryHash);
+ } catch {
+ console.error('[query] IDB persistence read failed');
+ return;
+ }
+
+ if (!entry) return;
+
+ if (validatePersistedEntry(entry, scope.buster, scope.maxAgeMs) !== 'valid') {
+ scope.store.remove(query.queryHash);
+ return;
+ }
+
+ const current = queryClient.getQueryState(query.queryKey);
+ if (current && current.status === 'success') return;
+
+ queryClient.setQueryData(query.queryKey, entry.data, {
+ updatedAt: entry.dataUpdatedAt,
+ });
}
+/**
+ * Persists a query's current data to IDB when the query updates successfully.
+ */
+function handleUpdate(scope: PersistScope, query: Query): void {
+ if (query.state.status !== 'success') return;
+ scope.store.set({
+ queryHash: query.queryHash,
+ queryKey: query.queryKey,
+ data: query.state.data,
+ dataUpdatedAt: query.state.dataUpdatedAt,
+ persistedAt: Date.now(),
+ buster: scope.buster,
+ });
+}
+
+/**
+ * Sets up per-query persistence: individual queries are persisted to
+ * and restored from IDB independently, rather than serializing the entire
+ * query cache as one blob.
+ *
+ * - On 'added': restores cached data from IDB if the query has no fresh data.
+ * - On 'updated': writes the query's successful data to IDB.
+ * - On 'removed': deletes the query's entry from IDB.
+ *
+ * Returns an unsubscribe function to stop listening.
+ */
export function setupQueryPersistence(
params: Readonly<{
queryClient: QueryClientLike;
- buster: string;
scopes: readonly PersistScope[];
}>
-) {
- for (const scope of params.scopes) {
- try {
- persistQueryClient({
- queryClient: params.queryClient as PersistQueryClient,
- persister: scope.persister,
- maxAge: scope.maxAgeMs,
- buster: params.buster,
- dehydrateOptions: {
- shouldDehydrateQuery: (q) =>
- q.state.status === 'success' && scope.shouldDehydrateQuery(q),
- },
+): () => void {
+ const { queryClient, scopes } = params;
+
+ const findScope = (queryKey: QueryKey) =>
+ scopes.find((s) => s.shouldPersist(queryKey));
+
+ const flushAll = () => {
+ for (const scope of scopes) {
+ void scope.store.flush();
+ }
+ };
+
+ const onVisibilityChange = () => {
+ if (document.visibilityState === 'hidden') flushAll();
+ };
+ document.addEventListener('visibilitychange', onVisibilityChange);
+
+ const cacheUnsubscribe = queryClient.getQueryCache().subscribe((event) => {
+ const { type } = event;
+ if (type !== 'added' && type !== 'updated' && type !== 'removed') return;
+
+ const { query } = event;
+ const scope = findScope(query.queryKey);
+ if (!scope) return;
+
+ if (type === 'added') {
+ handleRestore(queryClient, scope, query).catch((err) => {
+ console.error('[query] IDB restore failed', err);
});
- } catch {}
- }
+ } else if (type === 'updated') {
+ handleUpdate(scope, query);
+ } else {
+ scope.store.remove(query.queryHash);
+ }
+ });
+
+ return () => {
+ cacheUnsubscribe();
+ document.removeEventListener('visibilitychange', onVisibilityChange);
+ };
}
diff --git a/js/app/packages/queries/persistence/per-query-idb.ts b/js/app/packages/queries/persistence/per-query-idb.ts
new file mode 100644
index 0000000000..9832d0bf29
--- /dev/null
+++ b/js/app/packages/queries/persistence/per-query-idb.ts
@@ -0,0 +1,146 @@
+import type { QueryKey } from '@tanstack/query-core';
+
+export type PersistedQueryEntry = Readonly<{
+ queryHash: string;
+ queryKey: QueryKey;
+ data: unknown;
+ dataUpdatedAt: number;
+ persistedAt: number;
+ buster: string;
+}>;
+
+export type PerQueryPersistence = {
+ get: (queryHash: string) => Promise<PersistedQueryEntry | undefined>;
+ set: (entry: PersistedQueryEntry) => void;
+ remove: (queryHash: string) => void;
+ flush: () => Promise<void>;
+};
+
+type PerQueryPersistenceOptions = Readonly<{
+ dbName: string;
+ debounceMs?: number;
+}>;
+
+const STORE_NAME = 'queries';
+const DEFAULT_DEBOUNCE_MS = 1000;
+
+const dbCache = new Map<string, IDBDatabase>();
+
+function openDB(dbName: string): Promise<IDBDatabase> {
+ const cached = dbCache.get(dbName);
+ if (cached) return Promise.resolve(cached);
+ return new Promise((resolve, reject) => {
+ const req = indexedDB.open(dbName, 1);
+ req.onupgradeneeded = () => {
+ const db = req.result;
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
+ db.createObjectStore(STORE_NAME);
+ }
+ };
+ req.onsuccess = () => {
+ const db = req.result;
+ db.onclose = () => dbCache.delete(dbName);
+ dbCache.set(dbName, db);
+ resolve(db);
+ };
+ req.onerror = () => reject(req.error);
+ });
+}
+
+async function withStore<T>(
+ dbName: string,
+ mode: IDBTransactionMode,
+ fn: (store: IDBObjectStore) => IDBRequest<T>
+): Promise<T> {
+ const db = await openDB(dbName);
+ return new Promise<T>((resolve, reject) => {
+ const tx = db.transaction(STORE_NAME, mode);
+ const store = tx.objectStore(STORE_NAME);
+ const req = fn(store);
+ req.onsuccess = () => resolve(req.result);
+ req.onerror = () => reject(req.error);
+ tx.onabort = () => reject(tx.error);
+ });
+}
+
+export function createPerQueryIDBStore(
+ options: PerQueryPersistenceOptions
+): PerQueryPersistence {
+ const { dbName } = options;
+ const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
+
+ const pendingPuts = new Map<string, PersistedQueryEntry>();
+ const pendingDeletes = new Set<string>();
+ let timer: ReturnType<typeof setTimeout> | null = null;
+
+ const flush = async () => {
+ const puts = new Map(pendingPuts);
+ const deletes = new Set(pendingDeletes);
+ pendingPuts.clear();
+ pendingDeletes.clear();
+
+ if (puts.size === 0 && deletes.size === 0) return;
+
+ try {
+ const db = await openDB(dbName);
+ const tx = db.transaction(STORE_NAME, 'readwrite');
+ const store = tx.objectStore(STORE_NAME);
+
+ for (const [hash, entry] of puts) {
+ store.put(entry, hash);
+ }
+ for (const hash of deletes) {
+ store.delete(hash);
+ }
+
+ await new Promise<void>((resolve, reject) => {
+ tx.oncomplete = () => resolve();
+ tx.onerror = () => reject(tx.error);
+ tx.onabort = () => reject(tx.error);
+ });
+ } catch (err) {
+ for (const [hash, entry] of puts) {
+ if (!pendingPuts.has(hash)) pendingPuts.set(hash, entry);
+ }
+ for (const hash of deletes) {
+ if (!pendingPuts.has(hash)) pendingDeletes.add(hash);
+ }
+ console.error('[query] IDB persistence flush failed', err);
+ }
+ };
+
+ const scheduleFlush = () => {
+ if (timer) return;
+ timer = setTimeout(() => {
+ timer = null;
+ void flush();
+ }, debounceMs);
+ };
+
+ return {
+ get: (queryHash) =>
+ withStore<PersistedQueryEntry | undefined>(dbName, 'readonly', (store) =>
+ store.get(queryHash)
+ ),
+
+ set: (entry) => {
+ pendingDeletes.delete(entry.queryHash);
+ pendingPuts.set(entry.queryHash, entry);
+ scheduleFlush();
+ },
+
+ remove: (queryHash) => {
+ pendingPuts.delete(queryHash);
+ pendingDeletes.add(queryHash);
+ scheduleFlush();
+ },
+
+ flush: async () => {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ await flush();
+ },
+ };
+}
diff --git a/js/app/packages/queries/storage/idb.ts b/js/app/packages/queries/storage/idb.ts
deleted file mode 100644
index ad782a9009..0000000000
--- a/js/app/packages/queries/storage/idb.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import type {
- PersistedClient,
- Persister,
-} from '@tanstack/solid-query-persist-client';
-
-type IDBPersisterOptions = Readonly<{
- dbName?: string;
- storeName?: string;
- key?: string;
- debounceMs?: number;
-}>;
-
-const DEFAULT_DB = 'macro-query-cache';
-const DEFAULT_STORE = 'persisted';
-const DEFAULT_KEY = 'tanstack';
-const DEFAULT_DEBOUNCE_MS = 1000;
-
-const dbCache = new Map<string, IDBDatabase>();
-
-function openDB(dbName: string, storeName: string): Promise<IDBDatabase> {
- const cached = dbCache.get(dbName);
- if (cached) return Promise.resolve(cached);
- return new Promise((resolve, reject) => {
- const req = indexedDB.open(dbName, 1);
- req.onupgradeneeded = () => {
- const db = req.result;
- if (!db.objectStoreNames.contains(storeName)) {
- db.createObjectStore(storeName);
- }
- };
- req.onsuccess = () => {
- const db = req.result;
- dbCache.set(dbName, db);
- resolve(db);
- };
- req.onerror = () => reject(req.error);
- });
-}
-
-async function withStore<T>(
- dbName: string,
- storeName: string,
- mode: IDBTransactionMode,
- fn: (store: IDBObjectStore) => IDBRequest<T>
-): Promise<T> {
- const db = await openDB(dbName, storeName);
- return new Promise<T>((resolve, reject) => {
- const tx = db.transaction(storeName, mode);
- const store = tx.objectStore(storeName);
- const req = fn(store);
- req.onsuccess = () => resolve(req.result);
- req.onerror = () => reject(req.error);
- tx.onabort = () => reject(tx.error);
- });
-}
-
-export function createIDBPersister(
- options: IDBPersisterOptions = {}
-): Persister {
- const dbName = options.dbName ?? DEFAULT_DB;
- const storeName = options.storeName ?? DEFAULT_STORE;
- const key = options.key ?? DEFAULT_KEY;
- const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
-
- let pendingClient: PersistedClient | null = null;
- let debounceTimer: ReturnType<typeof setTimeout> | null = null;
-
- const flushPersist = async () => {
- if (!pendingClient) return;
- const client = pendingClient;
- pendingClient = null;
- await withStore(dbName, storeName, 'readwrite', (store) =>
- store.put(client, key)
- );
- };
-
- return {
- persistClient: async (client: PersistedClient) => {
- pendingClient = client;
- if (debounceTimer) clearTimeout(debounceTimer);
- debounceTimer = setTimeout(() => {
- debounceTimer = null;
- flushPersist();
- }, debounceMs);
- },
- restoreClient: async () => {
- const value = await withStore<PersistedClient | undefined>(
- dbName,
- storeName,
- 'readonly',
- (store) => store.get(key)
- );
- return value;
- },
- removeClient: async () => {
- if (debounceTimer) {
- clearTimeout(debounceTimer);
- debounceTimer = null;
- pendingClient = null;
- }
- await withStore(dbName, storeName, 'readwrite', (store) =>
- store.delete(key)
- );
- },
- };
-}