forked from TanStack/db
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOfflineExecutor.ts
More file actions
517 lines (447 loc) · 14.7 KB
/
OfflineExecutor.ts
File metadata and controls
517 lines (447 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
// Storage adapters
import { createOptimisticAction, createTransaction } from "@tanstack/db"
import { IndexedDBAdapter } from "./storage/IndexedDBAdapter"
import { LocalStorageAdapter } from "./storage/LocalStorageAdapter"
// Core components
import { OutboxManager } from "./outbox/OutboxManager"
import { KeyScheduler } from "./executor/KeyScheduler"
import { TransactionExecutor } from "./executor/TransactionExecutor"
// Coordination
import { WebLocksLeader } from "./coordination/WebLocksLeader"
import { BroadcastChannelLeader } from "./coordination/BroadcastChannelLeader"
// Connectivity
import { DefaultOnlineDetector } from "./connectivity/OnlineDetector"
// API
import { OfflineTransaction as OfflineTransactionAPI } from "./api/OfflineTransaction"
import { createOfflineAction } from "./api/OfflineAction"
// TanStack DB primitives
// Replay
import { withNestedSpan, withSpan } from "./telemetry/tracer"
import type {
CreateOfflineActionOptions,
CreateOfflineTransactionOptions,
LeaderElection,
OfflineConfig,
OfflineMode,
OfflineTransaction,
StorageAdapter,
StorageDiagnostic,
} from "./types"
import type { Transaction } from "@tanstack/db"
export class OfflineExecutor {
private config: OfflineConfig
// @ts-expect-error - Set during async initialization in initialize()
private storage: StorageAdapter | null
private outbox: OutboxManager | null
private scheduler: KeyScheduler
private executor: TransactionExecutor | null
private leaderElection: LeaderElection | null
private onlineDetector: DefaultOnlineDetector
private isLeaderState = false
private unsubscribeOnline: (() => void) | null = null
private unsubscribeLeadership: (() => void) | null = null
// Public diagnostic properties
public readonly mode: OfflineMode
public readonly storageDiagnostic: StorageDiagnostic
// Track initialization completion
private initPromise: Promise<void>
private initResolve!: () => void
private initReject!: (error: Error) => void
// Coordination mechanism for blocking transactions
private pendingTransactionPromises: Map<
string,
{
promise: Promise<any>
resolve: (result: any) => void
reject: (error: Error) => void
}
> = new Map()
constructor(config: OfflineConfig) {
this.config = config
this.scheduler = new KeyScheduler()
this.onlineDetector = new DefaultOnlineDetector()
// Initialize as pending - will be set by async initialization
this.storage = null
this.outbox = null
this.executor = null
this.leaderElection = null
// Temporary diagnostic - will be updated by async initialization
this.mode = `offline`
this.storageDiagnostic = {
code: `STORAGE_AVAILABLE`,
mode: `offline`,
message: `Initializing storage...`,
}
// Create initialization promise
this.initPromise = new Promise((resolve, reject) => {
this.initResolve = resolve
this.initReject = reject
})
this.initialize()
}
/**
* Probe storage availability and create appropriate adapter.
* Returns null if no storage is available (online-only mode).
*/
private async createStorage(): Promise<{
storage: StorageAdapter | null
diagnostic: StorageDiagnostic
}> {
// If user provided custom storage, use it without probing
if (this.config.storage) {
return {
storage: this.config.storage,
diagnostic: {
code: `STORAGE_AVAILABLE`,
mode: `offline`,
message: `Using custom storage adapter`,
},
}
}
// Probe IndexedDB first
const idbProbe = await IndexedDBAdapter.probe()
if (idbProbe.available) {
return {
storage: new IndexedDBAdapter(),
diagnostic: {
code: `STORAGE_AVAILABLE`,
mode: `offline`,
message: `Using IndexedDB for offline storage`,
},
}
}
// IndexedDB failed, try localStorage
const lsProbe = LocalStorageAdapter.probe()
if (lsProbe.available) {
return {
storage: new LocalStorageAdapter(),
diagnostic: {
code: `INDEXEDDB_UNAVAILABLE`,
mode: `offline`,
message: `IndexedDB unavailable, using localStorage fallback`,
error: idbProbe.error,
},
}
}
// Both failed - determine the diagnostic code
const isSecurityError =
idbProbe.error?.name === `SecurityError` ||
lsProbe.error?.name === `SecurityError`
const isQuotaError =
idbProbe.error?.name === `QuotaExceededError` ||
lsProbe.error?.name === `QuotaExceededError`
let code: StorageDiagnostic[`code`]
let message: string
if (isSecurityError) {
code = `STORAGE_BLOCKED`
message = `Storage blocked (private mode or security restrictions). Running in online-only mode.`
} else if (isQuotaError) {
code = `QUOTA_EXCEEDED`
message = `Storage quota exceeded. Running in online-only mode.`
} else {
code = `UNKNOWN_ERROR`
message = `Storage unavailable due to unknown error. Running in online-only mode.`
}
return {
storage: null,
diagnostic: {
code,
mode: `online-only`,
message,
error: idbProbe.error || lsProbe.error,
},
}
}
private createLeaderElection(): LeaderElection {
if (this.config.leaderElection) {
return this.config.leaderElection
}
if (WebLocksLeader.isSupported()) {
return new WebLocksLeader()
} else if (BroadcastChannelLeader.isSupported()) {
return new BroadcastChannelLeader()
} else {
// Fallback: always be leader in environments without multi-tab support
return {
requestLeadership: () => Promise.resolve(true),
releaseLeadership: () => {},
isLeader: () => true,
onLeadershipChange: () => () => {},
}
}
}
private setupEventListeners(): void {
// Only set up leader election listeners if we have storage
if (this.leaderElection) {
this.unsubscribeLeadership = this.leaderElection.onLeadershipChange(
(isLeader) => {
this.isLeaderState = isLeader
if (this.config.onLeadershipChange) {
this.config.onLeadershipChange(isLeader)
}
if (isLeader) {
this.loadAndReplayTransactions()
}
}
)
}
this.unsubscribeOnline = this.onlineDetector.subscribe(() => {
if (this.isOfflineEnabled && this.executor) {
// Reset retry delays so transactions can execute immediately when back online
this.executor.resetRetryDelays()
this.executor.executeAll().catch((error) => {
console.warn(
`Failed to execute transactions on connectivity change:`,
error
)
})
}
})
}
private async initialize(): Promise<void> {
return withSpan(`executor.initialize`, {}, async (span) => {
try {
// Probe storage and create adapter
const { storage, diagnostic } = await this.createStorage()
// Cast to writable to set readonly properties
;(this as any).storage = storage
;(this as any).storageDiagnostic = diagnostic
;(this as any).mode = diagnostic.mode
span.setAttribute(`storage.mode`, diagnostic.mode)
span.setAttribute(`storage.code`, diagnostic.code)
if (!storage) {
// Online-only mode - notify callback and skip offline setup
if (this.config.onStorageFailure) {
this.config.onStorageFailure(diagnostic)
}
span.setAttribute(`result`, `online-only`)
this.initResolve()
return
}
// Storage available - set up offline components
this.outbox = new OutboxManager(storage, this.config.collections)
this.executor = new TransactionExecutor(
this.scheduler,
this.outbox,
this.config,
this
)
this.leaderElection = this.createLeaderElection()
// Request leadership first
const isLeader = await this.leaderElection.requestLeadership()
span.setAttribute(`isLeader`, isLeader)
// Set up event listeners after leadership is established
// This prevents the callback from being called multiple times
this.setupEventListeners()
if (isLeader) {
await this.loadAndReplayTransactions()
}
span.setAttribute(`result`, `offline-enabled`)
this.initResolve()
} catch (error) {
console.warn(`Failed to initialize offline executor:`, error)
span.setAttribute(`result`, `failed`)
this.initReject(
error instanceof Error ? error : new Error(String(error))
)
}
})
}
private async loadAndReplayTransactions(): Promise<void> {
if (!this.executor) {
return
}
try {
await this.executor.loadPendingTransactions()
await this.executor.executeAll()
} catch (error) {
console.warn(`Failed to load and replay transactions:`, error)
}
}
get isOfflineEnabled(): boolean {
return this.mode === `offline` && this.isLeaderState
}
createOfflineTransaction(
options: CreateOfflineTransactionOptions
): Transaction | OfflineTransactionAPI {
const mutationFn = this.config.mutationFns[options.mutationFnName]
if (!mutationFn) {
throw new Error(`Unknown mutation function: ${options.mutationFnName}`)
}
// Check leadership immediately and use the appropriate primitive
if (!this.isOfflineEnabled) {
// Non-leader: use createTransaction directly with the resolved mutation function
// We need to wrap it to add the idempotency key
return createTransaction({
autoCommit: options.autoCommit ?? true,
mutationFn: (params) =>
mutationFn({
...params,
idempotencyKey: options.idempotencyKey || crypto.randomUUID(),
}),
metadata: options.metadata,
})
}
// Leader: use OfflineTransaction wrapper for offline persistence
return new OfflineTransactionAPI(
options,
mutationFn,
this.persistTransaction.bind(this),
this
)
}
createOfflineAction<T>(options: CreateOfflineActionOptions<T>) {
const mutationFn = this.config.mutationFns[options.mutationFnName]
if (!mutationFn) {
throw new Error(`Unknown mutation function: ${options.mutationFnName}`)
}
// Return a wrapper that checks leadership status at call time
return (variables: T) => {
// Check leadership when action is called, not when it's created
if (!this.isOfflineEnabled) {
// Non-leader: use createOptimisticAction directly
const action = createOptimisticAction({
mutationFn: (vars, params) =>
mutationFn({
...vars,
...params,
idempotencyKey: crypto.randomUUID(),
}),
onMutate: options.onMutate,
})
return action(variables)
}
// Leader: use the offline action wrapper
const action = createOfflineAction(
options,
mutationFn,
this.persistTransaction.bind(this),
this
)
return action(variables)
}
}
private async persistTransaction(
transaction: OfflineTransaction
): Promise<void> {
// Wait for initialization to complete
await this.initPromise
return withNestedSpan(
`executor.persistTransaction`,
{
"transaction.id": transaction.id,
"transaction.mutationFnName": transaction.mutationFnName,
},
async (span) => {
if (!this.isOfflineEnabled || !this.outbox || !this.executor) {
span.setAttribute(`result`, `skipped_not_leader`)
this.resolveTransaction(transaction.id, undefined)
return
}
try {
await this.outbox.add(transaction)
await this.executor.execute(transaction)
span.setAttribute(`result`, `persisted`)
} catch (error) {
console.error(
`Failed to persist offline transaction ${transaction.id}:`,
error
)
span.setAttribute(`result`, `failed`)
throw error
}
}
)
}
// Method for OfflineTransaction to wait for completion
async waitForTransactionCompletion(transactionId: string): Promise<any> {
const existing = this.pendingTransactionPromises.get(transactionId)
if (existing) {
return existing.promise
}
const deferred: {
promise: Promise<any>
resolve: (result: any) => void
reject: (error: Error) => void
} = {} as any
deferred.promise = new Promise((resolve, reject) => {
deferred.resolve = resolve
deferred.reject = reject
})
this.pendingTransactionPromises.set(transactionId, deferred)
return deferred.promise
}
// Method for TransactionExecutor to signal completion
resolveTransaction(transactionId: string, result: any): void {
const deferred = this.pendingTransactionPromises.get(transactionId)
if (deferred) {
deferred.resolve(result)
this.pendingTransactionPromises.delete(transactionId)
}
}
// Method for TransactionExecutor to signal failure
rejectTransaction(transactionId: string, error: Error): void {
const deferred = this.pendingTransactionPromises.get(transactionId)
if (deferred) {
deferred.reject(error)
this.pendingTransactionPromises.delete(transactionId)
}
}
async removeFromOutbox(id: string): Promise<void> {
if (!this.outbox) {
return
}
await this.outbox.remove(id)
}
async peekOutbox(): Promise<Array<OfflineTransaction>> {
if (!this.outbox) {
return []
}
return this.outbox.getAll()
}
async clearOutbox(): Promise<void> {
if (!this.outbox || !this.executor) {
return
}
await this.outbox.clear()
this.executor.clear()
}
notifyOnline(): void {
this.onlineDetector.notifyOnline()
}
getPendingCount(): number {
if (!this.executor) {
return 0
}
return this.executor.getPendingCount()
}
getRunningCount(): number {
if (!this.executor) {
return 0
}
return this.executor.getRunningCount()
}
getOnlineDetector(): DefaultOnlineDetector {
return this.onlineDetector
}
dispose(): void {
if (this.unsubscribeOnline) {
this.unsubscribeOnline()
this.unsubscribeOnline = null
}
if (this.unsubscribeLeadership) {
this.unsubscribeLeadership()
this.unsubscribeLeadership = null
}
if (this.leaderElection) {
this.leaderElection.releaseLeadership()
if (`dispose` in this.leaderElection) {
;(this.leaderElection as any).dispose()
}
}
this.onlineDetector.dispose()
}
}
export function startOfflineExecutor(config: OfflineConfig): OfflineExecutor {
return new OfflineExecutor(config)
}