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