Open History to see the last commit
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
225 if (this.scheduler.getPendingCount() > 0) {
226 const barrierPromise = this.executor.executeAll()
227
228 for (const collection of Object.values(this.config.collections)) {
229 collection.deferDataRefresh = barrierPromise
230 }
231
232 barrierPromise
233 .catch((error) => {
234 console.warn(
235 `Failed to execute transactions on connectivity change:`,
236 error,
237 )
238 })
239 .finally(() => {
240 for (const collection of Object.values(this.config.collections)) {
241 if (collection.deferDataRefresh === barrierPromise) {
242 collection.deferDataRefresh = null
243 }
244 }
245 })
246 } else {
247 this.executor.executeAll().catch((error) => {
248 console.warn(
249 `Failed to execute transactions on connectivity change:`,
250 error,
251 )
252 })
253 }
254 }
255 })
256 }
257
258 private async initialize(): Promise<void> {
259 return withSpan(`executor.initialize`, {}, async (span) => {
260 try {
261 // Probe storage and create adapter
262 const { storage, diagnostic } = await this.createStorage()
263
264 // Cast to writable to set readonly properties
265 ;(this as any).storage = storage
266 ;(this as any).storageDiagnostic = diagnostic
267 ;(this as any).mode = diagnostic.mode
268
269 span.setAttribute(`storage.mode`, diagnostic.mode)
270 span.setAttribute(`storage.code`, diagnostic.code)
271
272 if (!storage) {
273 // Online-only mode - notify callback and skip offline setup
274 if (this.config.onStorageFailure) {
275 this.config.onStorageFailure(diagnostic)
276 }
277 span.setAttribute(`result`, `online-only`)
278 this.initResolve()
279 return
280 }
281
282 // Storage available - set up offline components
283 this.outbox = new OutboxManager(storage, this.config.collections)
284 this.executor = new TransactionExecutor(
285 this.scheduler,
286 this.outbox,
287 this.config,
288 this,
289 )
290 this.leaderElection = this.createLeaderElection()
291
292 // Request leadership first
293 const isLeader = await this.leaderElection.requestLeadership()
294 this.isLeaderState = isLeader
295 span.setAttribute(`isLeader`, isLeader)
296
297 // Set up event listeners after leadership is established
298 // This prevents the callback from being called multiple times
299 this.setupEventListeners()
300
301 // Notify initial leadership state
302 if (this.config.onLeadershipChange) {
303 this.config.onLeadershipChange(isLeader)
304 }
305
306 if (isLeader) {
307 await this.loadAndReplayTransactions()
308 }
309 span.setAttribute(`result`, `offline-enabled`)
310 this.initResolve()
311 } catch (error) {
312 console.warn(`Failed to initialize offline executor:`, error)
313 span.setAttribute(`result`, `failed`)
314 this.initReject(
315 error instanceof Error ? error : new Error(String(error)),
316 )
317 }
318 })
319 }
320
321 private async loadAndReplayTransactions(): Promise<void> {
322 if (!this.executor) {
323 return
324 }
325
326 try {
327 // Load pending transactions and restore optimistic state
328 await this.executor.loadPendingTransactions()
329
330 // Start execution in the background - don't await to avoid blocking initialization
331 // The transactions will execute and complete asynchronously
332 this.executor.executeAll().catch((error) => {
333 console.warn(`Failed to execute transactions:`, error)
334 })
335 } catch (error) {
336 console.warn(`Failed to load and replay transactions:`, error)
337 }
338 }
339
340 get isOfflineEnabled(): boolean {
341 return this.mode === `offline` && this.isLeaderState
342 }
343
344 /**
345 * Wait for the executor to fully initialize.
346 * This ensures that pending transactions are loaded and optimistic state is restored.
347 */
348 async waitForInit(): Promise<void> {
349 return this.initPromise
350 }
351
352 createOfflineTransaction(
353 options: CreateOfflineTransactionOptions,
354 ): Transaction | OfflineTransactionAPI {
355 const mutationFn = this.config.mutationFns[options.mutationFnName]
356
357 if (!mutationFn) {
358 throw new Error(`Unknown mutation function: ${options.mutationFnName}`)
359 }
360
361 // Check leadership immediately and use the appropriate primitive
362 if (!this.isOfflineEnabled) {
363 // Non-leader: use createTransaction directly with the resolved mutation function
364 // We need to wrap it to add the idempotency key
365 return createTransaction({
366 autoCommit: options.autoCommit ?? true,
367 mutationFn: (params) =>
368 mutationFn({
369 ...params,
370 idempotencyKey: options.idempotencyKey || crypto.randomUUID(),
371 }),
372 metadata: options.metadata,
373 })
374 }
375
376 // Leader: use OfflineTransaction wrapper for offline persistence
377 return new OfflineTransactionAPI(
378 options,
379 mutationFn,
380 this.persistTransaction.bind(this),
381 this,
382 )
383 }
384
385 createOfflineAction<T>(options: CreateOfflineActionOptions<T>) {
386 const mutationFn = this.config.mutationFns[options.mutationFnName]
387
388 if (!mutationFn) {
389 throw new Error(`Unknown mutation function: ${options.mutationFnName}`)
390 }
391
392 // Return a wrapper that checks leadership status at call time
393 return (variables: T) => {
394 // Check leadership when action is called, not when it's created
395 if (!this.isOfflineEnabled) {
396 // Non-leader: use createOptimisticAction directly
397 const action = createOptimisticAction({
398 mutationFn: (vars, params) =>
399 mutationFn({
400 ...vars,
401 ...params,
402 idempotencyKey: crypto.randomUUID(),
403 }),
404 onMutate: options.onMutate,
405 })
406 return action(variables)
407 }
408
409 // Leader: use the offline action wrapper
410 const action = createOfflineAction(
411 options,
412 mutationFn,
413 this.persistTransaction.bind(this),
414 this,
415 )
416 return action(variables)
417 }
418 }
419
420 private async persistTransaction(
421 transaction: OfflineTransaction,
422 ): Promise<void> {
423 // Wait for initialization to complete
424 await this.initPromise
425
426 return withNestedSpan(
427 `executor.persistTransaction`,
428 {
429 'transaction.id': transaction.id,
430 'transaction.mutationFnName': transaction.mutationFnName,
431 },
432 async (span) => {
433 if (!this.isOfflineEnabled || !this.outbox || !this.executor) {
434 span.setAttribute(`result`, `skipped_not_leader`)
435 this.resolveTransaction(transaction.id, undefined)
436 return
437 }
438
439 try {
440 await this.outbox.add(transaction)
441 await this.executor.execute(transaction)
442 span.setAttribute(`result`, `persisted`)
443 } catch (error) {
444 console.error(
445 `Failed to persist offline transaction ${transaction.id}:`,
446 error,
447 )
448 span.setAttribute(`result`, `failed`)
449 throw error
450 }
451 },
452 )
453 }
454
455 // Method for OfflineTransaction to wait for completion
456 async waitForTransactionCompletion(transactionId: string): Promise<any> {
457 const existing = this.pendingTransactionPromises.get(transactionId)
458 if (existing) {
459 return existing.promise
460 }
461
462 const deferred: {
463 promise: Promise<any>
464 resolve: (result: any) => void
465 reject: (error: Error) => void
466 } = {} as any
467
468 deferred.promise = new Promise((resolve, reject) => {
469 deferred.resolve = resolve
470 deferred.reject = reject
471 })
472
473 this.pendingTransactionPromises.set(transactionId, deferred)
474 return deferred.promise
475 }
476
477 // Method for TransactionExecutor to signal completion
478 resolveTransaction(transactionId: string, result: any): void {
479 const deferred = this.pendingTransactionPromises.get(transactionId)
480 if (deferred) {
481 deferred.resolve(result)
482 this.pendingTransactionPromises.delete(transactionId)
483 }
484
485 // Clean up the restoration transaction - the sync will provide authoritative data
486 this.cleanupRestorationTransaction(transactionId)
487 }
488
489 // Method for TransactionExecutor to signal failure
490 rejectTransaction(transactionId: string, error: Error): void {
491 const deferred = this.pendingTransactionPromises.get(transactionId)
492 if (deferred) {
493 deferred.reject(error)
494 this.pendingTransactionPromises.delete(transactionId)
495 }
496
497 // Clean up the restoration transaction and rollback optimistic state
498 this.cleanupRestorationTransaction(transactionId, true)
499 }
500
501 // Method for TransactionExecutor to register restoration transactions
502 registerRestorationTransaction(
503 offlineTransactionId: string,
504 restorationTransaction: Transaction,
505 ): void {
506 this.restorationTransactions.set(
507 offlineTransactionId,
508 restorationTransaction,
509 )
510 }
511
512 private cleanupRestorationTransaction(
513 transactionId: string,
514 shouldRollback = false,
515 ): void {
516 const restorationTx = this.restorationTransactions.get(transactionId)
517 if (!restorationTx) {
518 return
519 }
520
521 this.restorationTransactions.delete(transactionId)
522
523 if (shouldRollback) {
524 restorationTx.rollback()
525 return
526 }
527
528 // Mark as completed so recomputeOptimisticState removes it from consideration.
529 // The actual data will come from the sync.
530 restorationTx.setState(`completed`)
531
532 // Remove from each collection's transaction map and recompute
533 const touchedCollections = new Set<string>()
534 for (const mutation of restorationTx.mutations) {
535 // Defensive check for corrupted deserialized data
536 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
537 if (!mutation.collection) {
538 continue
539 }
540 const collectionId = mutation.collection.id
541 if (touchedCollections.has(collectionId)) {
542 continue
543 }
544 touchedCollections.add(collectionId)
545 mutation.collection._state.transactions.delete(restorationTx.id)
546 mutation.collection._state.recomputeOptimisticState(false)
547 }
548 }
549
550 async removeFromOutbox(id: string): Promise<void> {
551 if (!this.outbox) {
552 return
553 }
554 await this.outbox.remove(id)
555 }
556
557 async peekOutbox(): Promise<Array<OfflineTransaction>> {
558 if (!this.outbox) {
559 return []
560 }
561 return this.outbox.getAll()
562 }
563
564 async clearOutbox(): Promise<void> {
565 if (!this.outbox || !this.executor) {
566 return
567 }
568 await this.outbox.clear()
569 this.executor.clear()
570 }
571
572 getPendingCount(): number {
573 if (!this.executor) {
574 return 0
575 }
576 return this.executor.getPendingCount()
577 }
578
579 getRunningCount(): number {
580 if (!this.executor) {
581 return 0
582 }
583 return this.executor.getRunningCount()
584 }
585
586 getOnlineDetector(): OnlineDetector {
587 return this.onlineDetector
588 }
589
590 isOnline(): boolean {
591 return this.onlineDetector.isOnline()
592 }
593
594 dispose(): void {
595 for (const collection of Object.values(this.config.collections)) {
596 collection.deferDataRefresh = null
597 }
598
599 if (this.unsubscribeOnline) {
600 this.unsubscribeOnline()
601 this.unsubscribeOnline = null
602 }
603
604 if (this.unsubscribeLeadership) {
605 this.unsubscribeLeadership()
606 this.unsubscribeLeadership = null
607 }
608
609 if (this.leaderElection) {
610 this.leaderElection.releaseLeadership()
611
612 if (`dispose` in this.leaderElection) {
613 ;(this.leaderElection as any).dispose()
614 }
615 }
616
617 this.onlineDetector.dispose()
618 }
619}
620
621export function startOfflineExecutor(config: OfflineConfig): OfflineExecutor {
622 return new OfflineExecutor(config)
623}