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(
303 storage,
304 this.config.collections,
305 this.config.mutationCodec,
306 )
307 this.executor = new TransactionExecutor(
308 this.scheduler,
309 this.outbox,
310 this.config,
311 this,
312 )
313 this.leaderElection = this.createLeaderElection()
314
315 // Request leadership first
316 const isLeader = await this.leaderElection.requestLeadership()
317 // Disposal may have run while leadership was pending.
318 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
319 if (this.disposed) {
320 this.leaderElection.releaseLeadership()
321 this.initResolve()
322 return
323 }
324 this.isLeaderState = isLeader
325
326 // Set up event listeners after leadership is established
327 // This prevents the callback from being called multiple times
328 this.setupEventListeners()
329
330 // Notify initial leadership state
331 if (this.config.onLeadershipChange) {
332 this.config.onLeadershipChange(isLeader)
333 }
334
335 if (isLeader) {
336 await this.loadAndReplayTransactions()
337 }
338 this.initResolve()
339 } catch (error) {
340 console.warn(`Failed to initialize offline executor:`, error)
341 this.initReject(error instanceof Error ? error : new Error(String(error)))
342 }
343 }
344
345 private async loadAndReplayTransactions(): Promise<void> {
346 if (!this.executor) {
347 return
348 }
349
350 // Startup must observe a failed read instead of reporting an empty outbox.
351 await this.executor.loadPendingTransactions()
352
353 // Replay completion is separate from initialization and durable admission.
354 this.executor.executeAll().catch((error) => {
355 console.warn(`Failed to execute transactions:`, error)
356 })
357 }
358
359 get isOfflineEnabled(): boolean {
360 return !this.disposed && this.mode === `offline` && this.isLeaderState
361 }
362
363 /**
364 * Wait for the executor to fully initialize.
365 * This ensures that pending transactions are loaded and optimistic state is restored.
366 */
367 async waitForInit(): Promise<void> {
368 return this.initPromise
369 }
370
371 createOfflineTransaction(
372 options: CreateOfflineTransactionOptions,
373 ): Transaction | OfflineTransactionAPI {
374 const mutationFn = this.config.mutationFns[options.mutationFnName]
375
376 if (!mutationFn) {
377 throw new Error(`Unknown mutation function: ${options.mutationFnName}`)
378 }
379
380 // Check leadership immediately and use the appropriate primitive
381 if (!this.isOfflineEnabled) {
382 // Non-leader: use createTransaction directly with the resolved mutation function
383 // We need to wrap it to add the idempotency key
384 return createTransaction({
385 autoCommit: options.autoCommit ?? true,
386 mutationFn: (params) =>
387 mutationFn({
388 ...params,
389 idempotencyKey: options.idempotencyKey || safeRandomUUID(),
390 }),
391 metadata: options.metadata,
392 })
393 }
394
395 // Leader: use OfflineTransaction wrapper for offline persistence
396 return new OfflineTransactionAPI(
397 options,
398 mutationFn,
399 this.persistTransaction.bind(this),
400 this,
401 )
402 }
403
404 createOfflineAction<T>(options: CreateOfflineActionOptions<T>) {
405 const mutationFn = this.config.mutationFns[options.mutationFnName]
406
407 if (!mutationFn) {
408 throw new Error(`Unknown mutation function: ${options.mutationFnName}`)
409 }
410
411 // Return a wrapper that checks leadership status at call time
412 return (variables: T) => {
413 // Check leadership when action is called, not when it's created
414 if (!this.isOfflineEnabled) {
415 // Non-leader: use createOptimisticAction directly
416 const action = createOptimisticAction({
417 mutationFn: (vars, params) =>
418 mutationFn({
419 ...vars,
420 ...params,
421 idempotencyKey: safeRandomUUID(),
422 }),
423 onMutate: options.onMutate,
424 })
425 return action(variables)
426 }
427
428 // Leader: use the offline action wrapper
429 const action = createOfflineAction(
430 options,
431 mutationFn,
432 this.persistTransaction.bind(this),
433 this,
434 )
435 return action(variables)
436 }
437 }
438
439 private async persistTransaction(
440 transaction: OfflineTransaction,
441 ): Promise<void> {
442 // Wait for initialization to complete
443 await this.initPromise
444
445 if (!this.isOfflineEnabled || !this.outbox || !this.executor) {
446 throw new NonRetriableError(`Offline transaction was not admitted`)
447 }
448
449 try {
450 this.executor.assertHealthy()
451 await this.outbox.add(transaction)
452 // A shared queue error belongs to its execution, not every caller
453 // that durably admitted a transaction. Per-ID signals settle callers.
454 this.executor.execute(transaction).catch((error) => {
455 console.warn(`Failed to execute transactions:`, error)
456 })
457 } catch (error) {
458 console.error(
459 `Failed to persist offline transaction ${transaction.id}:`,
460 error,
461 )
462 throw error
463 }
464 }
465
466 private rememberSettled(transactionId: string): void {
467 this.settledTransactions.add(transactionId)
468 if (this.settledTransactions.size > SETTLED_TRANSACTIONS_REMEMBERED)
469 this.settledTransactions.delete(
470 this.settledTransactions.values().next().value!,
471 )
472 }
473
474 // Method for OfflineTransaction to wait for completion
475 async waitForTransactionCompletion(transactionId: string): Promise<any> {
476 const existing = this.pendingTransactionPromises.get(transactionId)
477 if (existing) {
478 return existing.promise
479 }
480 if (this.settledTransactions.has(transactionId))
481 throw new Error(
482 `Offline transaction ${transactionId} already settled; wait for it before it settles`,
483 )
484
485 const deferred: {
486 promise: Promise<any>
487 resolve: (result: any) => void
488 reject: (error: Error) => void
489 } = {} as any
490
491 deferred.promise = new Promise((resolve, reject) => {
492 deferred.resolve = resolve
493 deferred.reject = reject
494 })
495
496 this.pendingTransactionPromises.set(transactionId, deferred)
497 return deferred.promise
498 }
499
500 // Method for TransactionExecutor to signal completion
501 resolveTransaction(transactionId: string, result: any): void {
502 this.rememberSettled(transactionId)
503 const deferred = this.pendingTransactionPromises.get(transactionId)
504 if (deferred) {
505 deferred.resolve(result)
506 this.pendingTransactionPromises.delete(transactionId)
507 }
508
509 // Clean up the restoration transaction - the sync will provide authoritative data
510 this.cleanupRestorationTransaction(transactionId)
511 }
512
513 // Method for TransactionExecutor to signal failure
514 rejectTransaction(transactionId: string, error: Error): void {
515 this.rememberSettled(transactionId)
516 const deferred = this.pendingTransactionPromises.get(transactionId)
517 if (deferred) {
518 deferred.reject(error)
519 this.pendingTransactionPromises.delete(transactionId)
520 }
521
522 // Clean up the restoration transaction and rollback optimistic state
523 this.cleanupRestorationTransaction(transactionId, true)
524 }
525
526 // Method for TransactionExecutor to register restoration transactions
527 registerRestorationTransaction(
528 offlineTransactionId: string,
529 restorationTransaction: Transaction,
530 ): void {
531 this.restorationTransactions.set(
532 offlineTransactionId,
533 restorationTransaction,
534 )
535 }
536
537 private cleanupRestorationTransaction(
538 transactionId: string,
539 shouldRollback = false,
540 ): void {
541 const restorationTx = this.restorationTransactions.get(transactionId)
542 if (!restorationTx) {
543 return
544 }
545
546 this.restorationTransactions.delete(transactionId)
547
548 if (shouldRollback) {
549 restorationTx.rollback()
550 return
551 }
552
553 // Mark as completed: every Collection that tracked it recomputes and
554 // releases it. The actual data will come from the sync.
555 restorationTx.setState(`completed`)
556 restorationTx.isPersisted.resolve(restorationTx)
557 restorationTx.touchCollection()
558 }
559
560 async removeFromOutbox(id: string): Promise<void> {
561 if (!this.outbox) {
562 return
563 }
564 await this.outbox.remove(id)
565 }
566
567 async peekOutbox(): Promise<Array<OfflineTransaction>> {
568 if (!this.outbox) {
569 return []
570 }
571 return this.outbox.getAll()
572 }
573
574 async clearOutbox(): Promise<void> {
575 if (!this.outbox || !this.executor) {
576 return
577 }
578 await this.outbox.clear()
579 this.executor.clear()
580 }
581
582 getPendingCount(): number {
583 if (!this.executor) {
584 return 0
585 }
586 return this.executor.getPendingCount()
587 }
588
589 getRunningCount(): number {
590 if (!this.executor) {
591 return 0
592 }
593 return this.executor.getRunningCount()
594 }
595
596 getOnlineDetector(): OnlineDetector {
597 return this.onlineDetector
598 }
599
600 isOnline(): boolean {
601 return this.onlineDetector.isOnline()
602 }
603
604 dispose(): void {
605 this.disposed = true
606 this.executor?.pause()
607 for (const collection of Object.values(this.config.collections)) {
608 collection.deferDataRefresh = null
609 }
610
611 if (this.unsubscribeOnline) {
612 this.unsubscribeOnline()
613 this.unsubscribeOnline = null
614 }
615
616 if (this.unsubscribeLeadership) {
617 this.unsubscribeLeadership()
618 this.unsubscribeLeadership = null
619 }
620
621 if (this.leaderElection) {
622 this.leaderElection.releaseLeadership()
623
624 if (`dispose` in this.leaderElection) {
625 ;(this.leaderElection as any).dispose()
626 }
627 }
628
629 this.onlineDetector.dispose()
630 }
631}
632
633export function startOfflineExecutor(config: OfflineConfig): OfflineExecutor {
634 return new OfflineExecutor(config)
635}