UNPKG

@tanstack/offline-transactions

Version:

Offline-first transaction capabilities for TanStack DB

355 lines (354 loc) • 13.7 kB
import { IndexedDBAdapter } from "./storage/IndexedDBAdapter.js"; import { LocalStorageAdapter } from "./storage/LocalStorageAdapter.js"; import { OutboxManager } from "./outbox/OutboxManager.js"; import { KeyScheduler } from "./executor/KeyScheduler.js"; import { TransactionExecutor } from "./executor/TransactionExecutor.js"; import { WebLocksLeader } from "./coordination/WebLocksLeader.js"; import { BroadcastChannelLeader } from "./coordination/BroadcastChannelLeader.js"; import { WebOnlineDetector } from "./connectivity/OnlineDetector.js"; import { OfflineTransaction } from "./api/OfflineTransaction.js"; import { createOfflineAction } from "./api/OfflineAction.js"; import { NonRetriableError } from "./types.js"; import { createOptimisticAction, createTransaction, safeRandomUUID } from "@tanstack/db"; // src/OfflineExecutor.ts /** How many settled ids an executor remembers to reject late waiters. */ var SETTLED_TRANSACTIONS_REMEMBERED = 1e3; var completionOwners = /* @__PURE__ */ new WeakMap(); /** A replacement may add Collections while retaining every prior registry entry. */ function retainsCollections(configured, prior) { return Object.entries(prior).every(([name, collection]) => configured[name] === collection); } var OfflineExecutor = class { constructor(config) { this.isLeaderState = false; this.disposed = false; this.unsubscribeOnline = null; this.unsubscribeLeadership = null; this.pendingTransactionPromises = /* @__PURE__ */ new Map(); this.settledTransactions = /* @__PURE__ */ new Set(); this.restorationTransactions = /* @__PURE__ */ new Map(); this.config = config; this.scheduler = new KeyScheduler(); this.onlineDetector = config.onlineDetector ?? new WebOnlineDetector(); this.storage = null; this.outbox = null; this.executor = null; this.leaderElection = null; this.mode = `offline`; this.storageDiagnostic = { code: `STORAGE_AVAILABLE`, mode: `offline`, message: `Initializing storage...` }; this.initPromise = new Promise((resolve, reject) => { this.initResolve = resolve; this.initReject = reject; }); this.initPromise.catch(() => {}); this.initialize(); } /** * Probe storage availability and create appropriate adapter. * Returns null if no storage is available (online-only mode). */ async createStorage() { if (this.config.storage) return { storage: this.config.storage, diagnostic: { code: `STORAGE_AVAILABLE`, mode: `offline`, message: `Using custom storage adapter` } }; const idbProbe = await IndexedDBAdapter.probe(); if (idbProbe.available) return { storage: new IndexedDBAdapter(), diagnostic: { code: `STORAGE_AVAILABLE`, mode: `offline`, message: `Using IndexedDB for offline storage` } }; const lsProbe = LocalStorageAdapter.probe(); if (lsProbe.available) return { storage: new LocalStorageAdapter(), diagnostic: { code: `INDEXEDDB_UNAVAILABLE`, mode: `offline`, message: `IndexedDB unavailable, using localStorage fallback`, error: idbProbe.error } }; const isSecurityError = idbProbe.error?.name === `SecurityError` || lsProbe.error?.name === `SecurityError`; const isQuotaError = idbProbe.error?.name === `QuotaExceededError` || lsProbe.error?.name === `QuotaExceededError`; let code; let message; if (isSecurityError) { code = `STORAGE_BLOCKED`; message = `Storage blocked (private mode or security restrictions). Running in online-only mode.`; } else if (isQuotaError) { code = `QUOTA_EXCEEDED`; message = `Storage quota exceeded. Running in online-only mode.`; } else { code = `UNKNOWN_ERROR`; message = `Storage unavailable due to unknown error. Running in online-only mode.`; } return { storage: null, diagnostic: { code, mode: `online-only`, message, error: idbProbe.error || lsProbe.error } }; } createLeaderElection() { if (this.config.leaderElection) return this.config.leaderElection; if (WebLocksLeader.isSupported()) return new WebLocksLeader(); else if (BroadcastChannelLeader.isSupported()) return new BroadcastChannelLeader(); else return { requestLeadership: () => Promise.resolve(true), releaseLeadership: () => {}, isLeader: () => true, onLeadershipChange: () => () => {} }; } setupEventListeners() { if (this.leaderElection) this.unsubscribeLeadership = this.leaderElection.onLeadershipChange((isLeader) => { if (this.disposed || isLeader === this.isLeaderState) return; this.isLeaderState = isLeader; if (!isLeader) this.executor?.pause(); if (this.config.onLeadershipChange) this.config.onLeadershipChange(isLeader); if (isLeader) this.loadAndReplayTransactions().catch((error) => { console.warn(`Failed to load and replay transactions:`, error); }); }); this.unsubscribeOnline = this.onlineDetector.subscribe(() => { if (this.isOfflineEnabled && this.executor) { this.executor.resetRetryDelays(); if (this.scheduler.getPendingCount() > 0) { const barrierPromise = this.executor.executeAll(); for (const collection of Object.values(this.config.collections)) collection.deferDataRefresh = barrierPromise; barrierPromise.catch((error) => { console.warn(`Failed to execute transactions on connectivity change:`, error); }).finally(() => { for (const collection of Object.values(this.config.collections)) if (collection.deferDataRefresh === barrierPromise) collection.deferDataRefresh = null; }); } else this.executor.executeAll().catch((error) => { console.warn(`Failed to execute transactions on connectivity change:`, error); }); } }); } async initialize() { try { const { storage, diagnostic } = await this.createStorage(); if (this.disposed) { this.initResolve(); return; } this.storage = storage; this.storageDiagnostic = diagnostic; this.mode = diagnostic.mode; if (!storage) { if (this.config.onStorageFailure) this.config.onStorageFailure(diagnostic); this.initResolve(); return; } this.outbox = new OutboxManager(storage, this.config.collections, this.config.mutationCodec); this.executor = new TransactionExecutor(this.scheduler, this.outbox, this.config, this); this.leaderElection = this.createLeaderElection(); const isLeader = await this.leaderElection.requestLeadership(); if (this.disposed) { this.leaderElection.releaseLeadership(); this.initResolve(); return; } this.isLeaderState = isLeader; this.setupEventListeners(); if (this.config.onLeadershipChange) this.config.onLeadershipChange(isLeader); if (isLeader) await this.loadAndReplayTransactions(); this.initResolve(); } catch (error) { console.warn(`Failed to initialize offline executor:`, error); this.initReject(error instanceof Error ? error : new Error(String(error))); } } async loadAndReplayTransactions() { if (!this.executor) return; await this.executor.loadPendingTransactions(); this.executor.executeAll().catch((error) => { console.warn(`Failed to execute transactions:`, error); }); } get isOfflineEnabled() { return !this.disposed && this.mode === `offline` && this.isLeaderState; } /** * Wait for the executor to fully initialize. * This ensures that pending transactions are loaded and optimistic state is restored. */ async waitForInit() { return this.initPromise; } createOfflineTransaction(options) { const mutationFn = this.config.mutationFns[options.mutationFnName]; if (!mutationFn) throw new Error(`Unknown mutation function: ${options.mutationFnName}`); if (!this.isOfflineEnabled) return createTransaction({ autoCommit: options.autoCommit ?? true, mutationFn: (params) => mutationFn({ ...params, idempotencyKey: options.idempotencyKey || safeRandomUUID() }), metadata: options.metadata }); return new OfflineTransaction(options, mutationFn, this.persistTransaction.bind(this), this); } createOfflineAction(options) { const mutationFn = this.config.mutationFns[options.mutationFnName]; if (!mutationFn) throw new Error(`Unknown mutation function: ${options.mutationFnName}`); return (variables) => { if (!this.isOfflineEnabled) return createOptimisticAction({ mutationFn: (vars, params) => mutationFn({ ...vars, ...params, idempotencyKey: safeRandomUUID() }), onMutate: options.onMutate })(variables); return createOfflineAction(options, mutationFn, this.persistTransaction.bind(this), this)(variables); }; } async persistTransaction(transaction) { await this.initPromise; if (!this.isOfflineEnabled || !this.outbox || !this.executor) throw new NonRetriableError(`Offline transaction was not admitted`); try { this.executor.assertHealthy(); await this.outbox.add(transaction); this.executor.execute(transaction).catch((error) => { console.warn(`Failed to execute transactions:`, error); }); } catch (error) { console.error(`Failed to persist offline transaction ${transaction.id}:`, error); throw error; } } rememberSettled(transactionId) { this.settledTransactions.add(transactionId); if (this.settledTransactions.size > SETTLED_TRANSACTIONS_REMEMBERED) this.settledTransactions.delete(this.settledTransactions.values().next().value); } async waitForTransactionCompletion(transactionId) { const existing = this.pendingTransactionPromises.get(transactionId); if (existing) return existing.promise; if (this.settledTransactions.has(transactionId)) throw new Error(`Offline transaction ${transactionId} already settled; wait for it before it settles`); const deferred = {}; deferred.promise = new Promise((resolve, reject) => { deferred.resolve = resolve; deferred.reject = reject; }); this.trackCompletion(); this.pendingTransactionPromises.set(transactionId, deferred); return deferred.promise; } resolveTransaction(transactionId, result) { this.settleTransaction(transactionId, result); } rejectTransaction(transactionId, error) { this.settleTransaction(transactionId, void 0, error); } trackCompletion() { if (this.pendingTransactionPromises.size > 0 || this.restorationTransactions.size > 0) return; for (const collection of Object.values(this.config.collections)) { let owners = completionOwners.get(collection); if (!owners) completionOwners.set(collection, owners = /* @__PURE__ */ new Set()); owners.add(this); } } settleTransaction(transactionId, result, error) { const candidates = /* @__PURE__ */ new Set([this]); for (const collection of Object.values(this.config.collections)) for (const owner of completionOwners.get(collection) ?? []) candidates.add(owner); const owners = [...candidates].filter((owner) => owner === this || (owner.pendingTransactionPromises.has(transactionId) || owner.restorationTransactions.has(transactionId)) && (retainsCollections(this.config.collections, owner.config.collections) || retainsCollections(owner.config.collections, this.config.collections))); const cleanupErrors = []; for (const owner of owners) { owner.rememberSettled(transactionId); const deferred = owner.pendingTransactionPromises.get(transactionId); owner.pendingTransactionPromises.delete(transactionId); if (error) deferred?.reject(error); else deferred?.resolve(result); try { owner.cleanupRestorationTransaction(transactionId, !!error); } catch (cleanupError) { cleanupErrors.push(cleanupError); } if (owner.pendingTransactionPromises.size === 0 && owner.restorationTransactions.size === 0) for (const collection of Object.values(owner.config.collections)) completionOwners.get(collection)?.delete(owner); } if (cleanupErrors.length > 0) throw cleanupErrors[0]; } registerRestorationTransaction(offlineTransactionId, restorationTransaction) { this.trackCompletion(); this.restorationTransactions.set(offlineTransactionId, restorationTransaction); } cleanupRestorationTransaction(transactionId, shouldRollback = false) { const restorationTx = this.restorationTransactions.get(transactionId); if (!restorationTx) return; this.restorationTransactions.delete(transactionId); if (shouldRollback) { restorationTx.rollback(); return; } if (restorationTx.state !== `pending`) return; restorationTx.completeWithoutCommit(); restorationTx.touchCollection(); } async removeFromOutbox(id) { if (!this.outbox) return; await this.outbox.remove(id); } async peekOutbox() { if (!this.outbox) return []; return this.outbox.getAll(); } async clearOutbox() { if (!this.outbox || !this.executor) return; await this.outbox.clear(); this.executor.clear(); } getPendingCount() { if (!this.executor) return 0; return this.executor.getPendingCount(); } getRunningCount() { if (!this.executor) return 0; return this.executor.getRunningCount(); } getOnlineDetector() { return this.onlineDetector; } isOnline() { return this.onlineDetector.isOnline(); } dispose() { this.disposed = true; this.executor?.pause(); for (const collection of Object.values(this.config.collections)) collection.deferDataRefresh = null; if (this.unsubscribeOnline) { this.unsubscribeOnline(); this.unsubscribeOnline = null; } if (this.unsubscribeLeadership) { this.unsubscribeLeadership(); this.unsubscribeLeadership = null; } if (this.leaderElection) { this.leaderElection.releaseLeadership(); if (`dispose` in this.leaderElection) this.leaderElection.dispose(); } this.onlineDetector.dispose(); } }; function startOfflineExecutor(config) { return new OfflineExecutor(config); } export { OfflineExecutor, startOfflineExecutor }; //# sourceMappingURL=OfflineExecutor.js.map