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