Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

OfflineExecutor.ts

595 lines17.2 KB

1// Storage adapters
2import { createOptimisticAction, createTransaction } from '@tanstack/db'
3import { IndexedDBAdapter } from './storage/IndexedDBAdapter'
4import { LocalStorageAdapter } from './storage/LocalStorageAdapter'
5​
6// Core components
7import { OutboxManager } from './outbox/OutboxManager'
8import { KeyScheduler } from './executor/KeyScheduler'
9import { TransactionExecutor } from './executor/TransactionExecutor'
10​
11// Coordination
12import { WebLocksLeader } from './coordination/WebLocksLeader'
13import { BroadcastChannelLeader } from './coordination/BroadcastChannelLeader'
14​
15// Connectivity
16import { WebOnlineDetector } from './connectivity/OnlineDetector'
17​
18// API
19import { OfflineTransaction as OfflineTransactionAPI } from './api/OfflineTransaction'
20import { createOfflineAction } from './api/OfflineAction'
21​
22// TanStack DB primitives
23​
24// Replay
25import { withNestedSpan, withSpan } from './telemetry/tracer'
26import type {
27 CreateOfflineActionOptions,
28 CreateOfflineTransactionOptions,
29 LeaderElection,
30 OfflineConfig,
31 OfflineMode,
32 OfflineTransaction,
33 OnlineDetector,
34 StorageAdapter,
35 StorageDiagnostic,
36} from './types'
37import type { Transaction } from '@tanstack/db'
38​
39export class OfflineExecutor {
40 private config: OfflineConfig
41​
42 // @ts-expect-error - Set during async initialization in initialize()
43 private storage: StorageAdapter | null
44 private outbox: OutboxManager | null
45 private scheduler: KeyScheduler
46 private executor: TransactionExecutor | null
47 private leaderElection: LeaderElection | null
48 private onlineDetector: OnlineDetector
49 private isLeaderState = false
50 private unsubscribeOnline: (() => void) | null = null
51 private unsubscribeLeadership: (() => void) | null = null
52​
53 // Public diagnostic properties
54 public readonly mode: OfflineMode
55 public readonly storageDiagnostic: StorageDiagnostic
56​
57 // Track initialization completion
58 private initPromise: Promise<void>
59 private initResolve!: () => void
60 private initReject!: (error: Error) => void
61​
62 // Coordination mechanism for blocking transactions
63 private pendingTransactionPromises: Map<
64 string,
65 {
66 promise: Promise<any>
67 resolve: (result: any) => void
68 reject: (error: Error) => void
69 }
70 > = new Map()
71​
72 // Track restoration transactions for cleanup when offline transactions complete
73 private restorationTransactions: Map<string, Transaction> = new Map()
74​
75 constructor(config: OfflineConfig) {
76 this.config = config
77 this.scheduler = new KeyScheduler()
78 this.onlineDetector = config.onlineDetector ?? new WebOnlineDetector()
79​
80 // Initialize as pending - will be set by async initialization
81 this.storage = null
82 this.outbox = null
83 this.executor = null
84 this.leaderElection = null
85​
86 // Temporary diagnostic - will be updated by async initialization
87 this.mode = `offline`
88 this.storageDiagnostic = {
89 code: `STORAGE_AVAILABLE`,
90 mode: `offline`,
91 message: `Initializing storage...`,
92 }
93​
94 // Create initialization promise
95 this.initPromise = new Promise((resolve, reject) => {
96 this.initResolve = resolve
97 this.initReject = reject
98 })
99​
100 this.initialize()
101 }
102​
103 /**
104 * Probe storage availability and create appropriate adapter.
105 * Returns null if no storage is available (online-only mode).
106 */
107 private async createStorage(): Promise<{
108 storage: StorageAdapter | null
109 diagnostic: StorageDiagnostic
110 }> {
111 // If user provided custom storage, use it without probing
112 if (this.config.storage) {
113 return {
114 storage: this.config.storage,
115 diagnostic: {
116 code: `STORAGE_AVAILABLE`,
117 mode: `offline`,
118 message: `Using custom storage adapter`,
119 },
120 }
121 }
122​
123 // Probe IndexedDB first
124 const idbProbe = await IndexedDBAdapter.probe()
125 if (idbProbe.available) {
126 return {
127 storage: new IndexedDBAdapter(),
128 diagnostic: {
129 code: `STORAGE_AVAILABLE`,
130 mode: `offline`,
131 message: `Using IndexedDB for offline storage`,
132 },
133 }
134 }
135​
136 // IndexedDB failed, try localStorage
137 const lsProbe = LocalStorageAdapter.probe()
138 if (lsProbe.available) {
139 return {
140 storage: new LocalStorageAdapter(),
141 diagnostic: {
142 code: `INDEXEDDB_UNAVAILABLE`,
143 mode: `offline`,
144 message: `IndexedDB unavailable, using localStorage fallback`,
145 error: idbProbe.error,
146 },
147 }
148 }
149​
150 // Both failed - determine the diagnostic code
151 const isSecurityError =
152 idbProbe.error?.name === `SecurityError` ||
153 lsProbe.error?.name === `SecurityError`
154 const isQuotaError =
155 idbProbe.error?.name === `QuotaExceededError` ||
156 lsProbe.error?.name === `QuotaExceededError`
157​
158 let code: StorageDiagnostic[`code`]
159 let message: string
160​
161 if (isSecurityError) {
162 code = `STORAGE_BLOCKED`
163 message = `Storage blocked (private mode or security restrictions). Running in online-only mode.`
164 } else if (isQuotaError) {
165 code = `QUOTA_EXCEEDED`
166 message = `Storage quota exceeded. Running in online-only mode.`
167 } else {
168 code = `UNKNOWN_ERROR`
169 message = `Storage unavailable due to unknown error. Running in online-only mode.`
170 }
171​
172 return {
173 storage: null,
174 diagnostic: {
175 code,
176 mode: `online-only`,
177 message,
178 error: idbProbe.error || lsProbe.error,
179 },
180 }
181 }
182​
183 private createLeaderElection(): LeaderElection {
184 if (this.config.leaderElection) {
185 return this.config.leaderElection
186 }
187​
188 if (WebLocksLeader.isSupported()) {
189 return new WebLocksLeader()
190 } else if (BroadcastChannelLeader.isSupported()) {
191 return new BroadcastChannelLeader()
192 } else {
193 // Fallback: always be leader in environments without multi-tab support
194 return {
195 requestLeadership: () => Promise.resolve(true),
196 releaseLeadership: () => {},
197 isLeader: () => true,
198 onLeadershipChange: () => () => {},
199 }
200 }
201 }
202​
203 private setupEventListeners(): void {
204 // Only set up leader election listeners if we have storage
205 if (this.leaderElection) {
206 this.unsubscribeLeadership = this.leaderElection.onLeadershipChange(
207 (isLeader) => {
208 this.isLeaderState = isLeader
209​
210 if (this.config.onLeadershipChange) {
211 this.config.onLeadershipChange(isLeader)
212 }
213​
214 if (isLeader) {
215 this.loadAndReplayTransactions()
216 }
217 },
218 )
219 }
220​
221 this.unsubscribeOnline = this.onlineDetector.subscribe(() => {
222 if (this.isOfflineEnabled && this.executor) {
223 this.executor.resetRetryDelays()
224 this.executor.executeAll().catch((error) => {
225 console.warn(
226 `Failed to execute transactions on connectivity change:`,
227 error,
228 )
229 })
230 }
231 })
232 }
233​
234 private async initialize(): Promise<void> {
235 return withSpan(`executor.initialize`, {}, async (span) => {
236 try {
237 // Probe storage and create adapter
238 const { storage, diagnostic } = await this.createStorage()
239​
240 // Cast to writable to set readonly properties
241 ;(this as any).storage = storage
242 ;(this as any).storageDiagnostic = diagnostic
243 ;(this as any).mode = diagnostic.mode
244​
245 span.setAttribute(`storage.mode`, diagnostic.mode)
246 span.setAttribute(`storage.code`, diagnostic.code)
247​
248 if (!storage) {
249 // Online-only mode - notify callback and skip offline setup
250 if (this.config.onStorageFailure) {
251 this.config.onStorageFailure(diagnostic)
252 }
253 span.setAttribute(`result`, `online-only`)
254 this.initResolve()
255 return
256 }
257​
258 // Storage available - set up offline components
259 this.outbox = new OutboxManager(storage, this.config.collections)
260 this.executor = new TransactionExecutor(
261 this.scheduler,
262 this.outbox,
263 this.config,
264 this,
265 )
266 this.leaderElection = this.createLeaderElection()
267​
268 // Request leadership first
269 const isLeader = await this.leaderElection.requestLeadership()
270 this.isLeaderState = isLeader
271 span.setAttribute(`isLeader`, isLeader)
272​
273 // Set up event listeners after leadership is established
274 // This prevents the callback from being called multiple times
275 this.setupEventListeners()
276​
277 // Notify initial leadership state
278 if (this.config.onLeadershipChange) {
279 this.config.onLeadershipChange(isLeader)
280 }
281​
282 if (isLeader) {
283 await this.loadAndReplayTransactions()
284 }
285 span.setAttribute(`result`, `offline-enabled`)
286 this.initResolve()
287 } catch (error) {
288 console.warn(`Failed to initialize offline executor:`, error)
289 span.setAttribute(`result`, `failed`)
290 this.initReject(
291 error instanceof Error ? error : new Error(String(error)),
292 )
293 }
294 })
295 }
296​
297 private async loadAndReplayTransactions(): Promise<void> {
298 if (!this.executor) {
299 return
300 }
301​
302 try {
303 // Load pending transactions and restore optimistic state
304 await this.executor.loadPendingTransactions()
305​
306 // Start execution in the background - don't await to avoid blocking initialization
307 // The transactions will execute and complete asynchronously
308 this.executor.executeAll().catch((error) => {
309 console.warn(`Failed to execute transactions:`, error)
310 })
311 } catch (error) {
312 console.warn(`Failed to load and replay transactions:`, error)
313 }
314 }
315​
316 get isOfflineEnabled(): boolean {
317 return this.mode === `offline` && this.isLeaderState
318 }
319​
320 /**
321 * Wait for the executor to fully initialize.
322 * This ensures that pending transactions are loaded and optimistic state is restored.
323 */
324 async waitForInit(): Promise<void> {
325 return this.initPromise
326 }
327​
328 createOfflineTransaction(
329 options: CreateOfflineTransactionOptions,
330 ): Transaction | OfflineTransactionAPI {
331 const mutationFn = this.config.mutationFns[options.mutationFnName]
332​
333 if (!mutationFn) {
334 throw new Error(`Unknown mutation function: ${options.mutationFnName}`)
335 }
336​
337 // Check leadership immediately and use the appropriate primitive
338 if (!this.isOfflineEnabled) {
339 // Non-leader: use createTransaction directly with the resolved mutation function
340 // We need to wrap it to add the idempotency key
341 return createTransaction({
342 autoCommit: options.autoCommit ?? true,
343 mutationFn: (params) =>
344 mutationFn({
345 ...params,
346 idempotencyKey: options.idempotencyKey || crypto.randomUUID(),
347 }),
348 metadata: options.metadata,
349 })
350 }
351​
352 // Leader: use OfflineTransaction wrapper for offline persistence
353 return new OfflineTransactionAPI(
354 options,
355 mutationFn,
356 this.persistTransaction.bind(this),
357 this,
358 )
359 }
360​
361 createOfflineAction<T>(options: CreateOfflineActionOptions<T>) {
362 const mutationFn = this.config.mutationFns[options.mutationFnName]
363​
364 if (!mutationFn) {
365 throw new Error(`Unknown mutation function: ${options.mutationFnName}`)
366 }
367​
368 // Return a wrapper that checks leadership status at call time
369 return (variables: T) => {
370 // Check leadership when action is called, not when it's created
371 if (!this.isOfflineEnabled) {
372 // Non-leader: use createOptimisticAction directly
373 const action = createOptimisticAction({
374 mutationFn: (vars, params) =>
375 mutationFn({
376 ...vars,
377 ...params,
378 idempotencyKey: crypto.randomUUID(),
379 }),
380 onMutate: options.onMutate,
381 })
382 return action(variables)
383 }
384​
385 // Leader: use the offline action wrapper
386 const action = createOfflineAction(
387 options,
388 mutationFn,
389 this.persistTransaction.bind(this),
390 this,
391 )
392 return action(variables)
393 }
394 }
395​
396 private async persistTransaction(
397 transaction: OfflineTransaction,
398 ): Promise<void> {
399 // Wait for initialization to complete
400 await this.initPromise
401​
402 return withNestedSpan(
403 `executor.persistTransaction`,
404 {
405 'transaction.id': transaction.id,
406 'transaction.mutationFnName': transaction.mutationFnName,
407 },
408 async (span) => {
409 if (!this.isOfflineEnabled || !this.outbox || !this.executor) {
410 span.setAttribute(`result`, `skipped_not_leader`)
411 this.resolveTransaction(transaction.id, undefined)
412 return
413 }
414​
415 try {
416 await this.outbox.add(transaction)
417 await this.executor.execute(transaction)
418 span.setAttribute(`result`, `persisted`)
419 } catch (error) {
420 console.error(
421 `Failed to persist offline transaction ${transaction.id}:`,
422 error,
423 )
424 span.setAttribute(`result`, `failed`)
425 throw error
426 }
427 },
428 )
429 }
430​
431 // Method for OfflineTransaction to wait for completion
432 async waitForTransactionCompletion(transactionId: string): Promise<any> {
433 const existing = this.pendingTransactionPromises.get(transactionId)
434 if (existing) {
435 return existing.promise
436 }
437​
438 const deferred: {
439 promise: Promise<any>
440 resolve: (result: any) => void
441 reject: (error: Error) => void
442 } = {} as any
443​
444 deferred.promise = new Promise((resolve, reject) => {
445 deferred.resolve = resolve
446 deferred.reject = reject
447 })
448​
449 this.pendingTransactionPromises.set(transactionId, deferred)
450 return deferred.promise
451 }
452​
453 // Method for TransactionExecutor to signal completion
454 resolveTransaction(transactionId: string, result: any): void {
455 const deferred = this.pendingTransactionPromises.get(transactionId)
456 if (deferred) {
457 deferred.resolve(result)
458 this.pendingTransactionPromises.delete(transactionId)
459 }
460​
461 // Clean up the restoration transaction - the sync will provide authoritative data
462 this.cleanupRestorationTransaction(transactionId)
463 }
464​
465 // Method for TransactionExecutor to signal failure
466 rejectTransaction(transactionId: string, error: Error): void {
467 const deferred = this.pendingTransactionPromises.get(transactionId)
468 if (deferred) {
469 deferred.reject(error)
470 this.pendingTransactionPromises.delete(transactionId)
471 }
472​
473 // Clean up the restoration transaction and rollback optimistic state
474 this.cleanupRestorationTransaction(transactionId, true)
475 }
476​
477 // Method for TransactionExecutor to register restoration transactions
478 registerRestorationTransaction(
479 offlineTransactionId: string,
480 restorationTransaction: Transaction,
481 ): void {
482 this.restorationTransactions.set(
483 offlineTransactionId,
484 restorationTransaction,
485 )
486 }
487​
488 private cleanupRestorationTransaction(
489 transactionId: string,
490 shouldRollback = false,
491 ): void {
492 const restorationTx = this.restorationTransactions.get(transactionId)
493 if (!restorationTx) {
494 return
495 }
496​
497 this.restorationTransactions.delete(transactionId)
498​
499 if (shouldRollback) {
500 restorationTx.rollback()
501 return
502 }
503​
504 // Mark as completed so recomputeOptimisticState removes it from consideration.
505 // The actual data will come from the sync.
506 restorationTx.setState(`completed`)
507​
508 // Remove from each collection's transaction map and recompute
509 const touchedCollections = new Set<string>()
510 for (const mutation of restorationTx.mutations) {
511 // Defensive check for corrupted deserialized data
512 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
513 if (!mutation.collection) {
514 continue
515 }
516 const collectionId = mutation.collection.id
517 if (touchedCollections.has(collectionId)) {
518 continue
519 }
520 touchedCollections.add(collectionId)
521 mutation.collection._state.transactions.delete(restorationTx.id)
522 mutation.collection._state.recomputeOptimisticState(false)
523 }
524 }
525​
526 async removeFromOutbox(id: string): Promise<void> {
527 if (!this.outbox) {
528 return
529 }
530 await this.outbox.remove(id)
531 }
532​
533 async peekOutbox(): Promise<Array<OfflineTransaction>> {
534 if (!this.outbox) {
535 return []
536 }
537 return this.outbox.getAll()
538 }
539​
540 async clearOutbox(): Promise<void> {
541 if (!this.outbox || !this.executor) {
542 return
543 }
544 await this.outbox.clear()
545 this.executor.clear()
546 }
547​
548 getPendingCount(): number {
549 if (!this.executor) {
550 return 0
551 }
552 return this.executor.getPendingCount()
553 }
554​
555 getRunningCount(): number {
556 if (!this.executor) {
557 return 0
558 }
559 return this.executor.getRunningCount()
560 }
561​
562 getOnlineDetector(): OnlineDetector {
563 return this.onlineDetector
564 }
565​
566 isOnline(): boolean {
567 return this.onlineDetector.isOnline()
568 }
569​
570 dispose(): void {
571 if (this.unsubscribeOnline) {
572 this.unsubscribeOnline()
573 this.unsubscribeOnline = null
574 }
575​
576 if (this.unsubscribeLeadership) {
577 this.unsubscribeLeadership()
578 this.unsubscribeLeadership = null
579 }
580​
581 if (this.leaderElection) {
582 this.leaderElection.releaseLeadership()
583​
584 if (`dispose` in this.leaderElection) {
585 ;(this.leaderElection as any).dispose()
586 }
587 }
588​
589 this.onlineDetector.dispose()
590 }
592​
593export function startOfflineExecutor(config: OfflineConfig): OfflineExecutor {
594 return new OfflineExecutor(config)