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