Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

OfflineExecutor.ts

632 lines18.6 KB

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