forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-coordinator.ts
More file actions
554 lines (496 loc) · 14.8 KB
/
Copy pathsync-coordinator.ts
File metadata and controls
554 lines (496 loc) · 14.8 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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
import AsyncStorage from '@react-native-async-storage/async-storage';
import { DraftService } from './draft-service';
import { offlineQueue } from './offline-queue';
import { authService } from './auth-service';
import { useAuthStore } from '../hooks/use-auth-store';
const SYNC_STATUS_KEY = '@invoisio_sync_status';
const SYNC_HISTORY_KEY = '@invoisio_sync_history';
const LAST_SYNC_KEY = '@invoisio_last_sync';
export type SyncOperationType =
| 'drafts'
| 'invoices'
| 'notifications'
| 'offline_queue'
| 'auth_retry';
export interface SyncOperation {
id: string;
type: SyncOperationType;
status: 'pending' | 'in_progress' | 'completed' | 'failed';
startTime: number;
endTime?: number;
error?: string;
retryCount: number;
details?: {
totalItems?: number;
processedItems?: number;
failedItems?: number;
};
}
export interface SyncStatus {
isSyncing: boolean;
currentOperation: SyncOperation | null;
queue: SyncOperation[];
lastSyncTime: number | null;
overallProgress: number;
}
export interface SyncHistoryEntry {
timestamp: number;
duration: number;
operations: SyncOperation[];
success: boolean;
}
/**
* SyncCoordinator manages all synchronization operations with:
* - App-resume and connectivity-recovery triggers
* - Retry logic with exponential backoff
* - Partial failure handling
* - User-facing observability
*/
class SyncCoordinator {
private isSyncing = false;
private currentOperation: SyncOperation | null = null;
private operationQueue: SyncOperation[] = [];
private listeners: ((status: SyncStatus) => void)[] = [];
private maxRetries = 3;
private retryDelay = 1000; // Base delay in ms
/**
* Add a listener for sync status changes
*/
subscribe(listener: (status: SyncStatus) => void): () => void {
this.listeners.push(listener);
return () => {
this.listeners = this.listeners.filter(l => l !== listener);
};
}
/**
* Notify all listeners of status changes
*/
private notifyListeners(): void {
const status: SyncStatus = {
isSyncing: this.isSyncing,
currentOperation: this.currentOperation,
queue: this.operationQueue,
lastSyncTime: this.getLastSyncTime(),
overallProgress: this.calculateProgress(),
};
this.listeners.forEach(listener => listener(status));
}
/**
* Calculate overall sync progress (0-100)
*/
private calculateProgress(): number {
if (!this.isSyncing && this.operationQueue.length === 0) return 0;
const total = this.operationQueue.length + (this.currentOperation ? 1 : 0);
if (total === 0) return 0;
let completed = 0;
this.operationQueue.forEach(op => {
if (op.status === 'completed') completed++;
});
if (this.currentOperation?.status === 'completed') completed++;
return Math.round((completed / total) * 100);
}
/**
* Get last sync time from storage
*/
private getLastSyncTime(): number | null {
try {
const stored = AsyncStorage.getItem(LAST_SYNC_KEY);
return stored ? Number(stored) : null;
} catch {
return null;
}
}
/**
* Save last sync time to storage
*/
private async saveLastSyncTime(): Promise<void> {
try {
await AsyncStorage.setItem(LAST_SYNC_KEY, String(Date.now()));
} catch (error) {
console.error('Failed to save last sync time:', error);
}
}
/**
* Save sync status to storage
*/
private async saveSyncStatus(): Promise<void> {
try {
const status = {
isSyncing: this.isSyncing,
currentOperation: this.currentOperation,
queue: this.operationQueue,
lastSyncTime: this.getLastSyncTime(),
};
await AsyncStorage.setItem(SYNC_STATUS_KEY, JSON.stringify(status));
} catch (error) {
console.error('Failed to save sync status:', error);
}
}
/**
* Add sync operation to queue
*/
private enqueueOperation(type: SyncOperationType, details?: SyncOperation['details']): string {
const id = `${type}_${Date.now()}`;
const operation: SyncOperation = {
id,
type,
status: 'pending',
startTime: Date.now(),
retryCount: 0,
details,
} as SyncOperation;
this.operationQueue.push(operation);
this.notifyListeners();
return id;
}
/**
* Update operation status
*/
private updateOperation(
id: string,
updates: Partial<SyncOperation>
): void {
const index = this.operationQueue.findIndex(op => op.id === id);
if (index !== -1) {
this.operationQueue[index] = {
...this.operationQueue[index],
...updates,
} as SyncOperation;
this.notifyListeners();
} else if (this.currentOperation?.id === id) {
this.currentOperation = {
...this.currentOperation,
...updates,
} as SyncOperation;
this.notifyListeners();
}
}
/**
* Execute sync operation with retry logic
*/
private async executeOperation(
operation: SyncOperation,
executor: () => Promise<void>
): Promise<void> {
const { id, type } = operation;
this.updateOperation(id, { status: 'in_progress' });
this.currentOperation = { ...operation, status: 'in_progress' };
this.notifyListeners();
let lastError: Error | null = null;
for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
try {
await executor();
// Success
this.updateOperation(id, {
status: 'completed',
endTime: Date.now(),
});
this.currentOperation = null;
this.notifyListeners();
return;
} catch (error) {
lastError = error as Error;
console.error(`Sync operation ${type} failed (attempt ${attempt + 1}):`, error);
if (attempt < this.maxRetries) {
// Exponential backoff
const delay = this.retryDelay * Math.pow(2, attempt);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// All retries failed
this.updateOperation(id, {
status: 'failed',
endTime: Date.now(),
error: lastError?.message || 'Unknown error',
retryCount: this.maxRetries,
});
this.currentOperation = null;
this.notifyListeners();
}
/**
* Sync local drafts with server
*/
private async syncDrafts(token: string): Promise<void> {
const operationId = this.enqueueOperation('drafts');
try {
const syncStatus = await DraftService.getSyncStatus();
this.updateOperation(operationId, {
details: {
totalItems: syncStatus.unsynced,
processedItems: 0,
failedItems: 0,
},
});
await DraftService.syncLocalDrafts(token);
const finalStatus = await DraftService.getSyncStatus();
this.updateOperation(operationId, {
details: {
totalItems: syncStatus.unsynced,
processedItems: syncStatus.unsynced - finalStatus.unsynced,
failedItems: finalStatus.unsynced,
},
});
} catch (error) {
throw error;
}
}
/**
* Process offline queue
*/
private async processOfflineQueue(): Promise<void> {
const operationId = this.enqueueOperation('offline_queue');
const queueSize = offlineQueue.getQueueSize();
this.updateOperation(operationId, {
details: {
totalItems: queueSize,
processedItems: 0,
failedItems: 0,
},
});
let processed = 0;
let failed = 0;
await offlineQueue.processQueue(
() => {
processed++;
this.updateOperation(operationId, {
details: {
totalItems: queueSize,
processedItems: processed,
failedItems: failed,
},
});
},
() => {
failed++;
this.updateOperation(operationId, {
details: {
totalItems: queueSize,
processedItems: processed,
failedItems: failed,
},
});
}
);
}
/**
* Retry pending auth operations
*/
private async retryAuth(): Promise<void> {
this.enqueueOperation('auth_retry');
try {
const loginResult = await authService.retryPendingOperation();
if (loginResult) {
await useAuthStore.getState().setAuth(
loginResult.response.accessToken,
loginResult.publicKey
);
}
} catch (error) {
throw error;
}
}
/**
* Check for stale invoice status updates
*/
private async syncInvoiceStatus(_token: string): Promise<void> {
const operationId = this.enqueueOperation('invoices');
try {
// This would typically fetch recent invoices and check for status updates
// For now, we'll mark it as completed since the invoice list already refreshes
this.updateOperation(operationId, {
details: {
totalItems: 0,
processedItems: 0,
failedItems: 0,
},
});
} catch (error) {
throw error;
}
}
/**
* Catch up on pending notifications
*/
private async syncNotifications(_token: string): Promise<void> {
const operationId = this.enqueueOperation('notifications');
try {
// This would typically fetch recent notifications
// For now, we'll mark it as completed
this.updateOperation(operationId, {
details: {
totalItems: 0,
processedItems: 0,
failedItems: 0,
},
});
} catch (error) {
throw error;
}
}
/**
* Main sync orchestration method
*/
async triggerSync(options?: {
skipAuth?: boolean;
skipDrafts?: boolean;
skipQueue?: boolean;
skipInvoices?: boolean;
skipNotifications?: boolean;
}): Promise<void> {
if (this.isSyncing) {
console.log('Sync already in progress, skipping');
return;
}
this.isSyncing = true;
this.notifyListeners();
await this.saveSyncStatus();
const { accessToken } = useAuthStore.getState();
if (!accessToken) {
console.log('No access token, skipping sync');
this.isSyncing = false;
this.notifyListeners();
return;
}
const startTime = Date.now();
try {
// Step 1: Retry auth if needed
if (!options?.skipAuth) {
const authOpId = this.enqueueOperation('auth_retry');
try {
const authOp = this.operationQueue.find(op => op.id === authOpId)!;
await this.executeOperation(authOp, () => this.retryAuth());
} catch (error) {
console.error('Auth retry failed, continuing with other sync operations');
}
}
// Step 2: Sync drafts
if (!options?.skipDrafts) {
const draftsOpId = this.enqueueOperation('drafts');
try {
const draftsOp = this.operationQueue.find(op => op.id === draftsOpId)!;
await this.executeOperation(draftsOp, () => this.syncDrafts(accessToken));
} catch (error) {
console.error('Draft sync failed, continuing with other operations');
}
}
// Step 3: Process offline queue
if (!options?.skipQueue) {
const queueOpId = this.enqueueOperation('offline_queue');
try {
const queueOp = this.operationQueue.find(op => op.id === queueOpId)!;
await this.executeOperation(queueOp, () => this.processOfflineQueue());
} catch (error) {
console.error('Offline queue processing failed, continuing with other operations');
}
}
// Step 4: Sync invoice status
if (!options?.skipInvoices) {
const invoicesOpId = this.enqueueOperation('invoices');
try {
const invoicesOp = this.operationQueue.find(op => op.id === invoicesOpId)!;
await this.executeOperation(invoicesOp, () => this.syncInvoiceStatus(accessToken));
} catch (error) {
console.error('Invoice status sync failed, continuing with other operations');
}
}
// Step 5: Sync notifications
if (!options?.skipNotifications) {
const notificationsOpId = this.enqueueOperation('notifications');
try {
const notificationsOp = this.operationQueue.find(op => op.id === notificationsOpId)!;
await this.executeOperation(notificationsOp, () => this.syncNotifications(accessToken));
} catch (error) {
console.error('Notification sync failed, continuing with other operations');
}
}
// Record successful sync
await this.recordSyncHistory(startTime, this.operationQueue.filter(op => op.status !== 'pending'), true);
await this.saveLastSyncTime();
} catch (error) {
console.error('Sync coordinator error:', error);
await this.recordSyncHistory(startTime, this.operationQueue.filter(op => op.status !== 'pending'), false);
} finally {
this.isSyncing = false;
this.operationQueue = [];
this.currentOperation = null;
await this.saveSyncStatus();
this.notifyListeners();
}
}
/**
* Record sync history for debugging and user feedback
*/
private async recordSyncHistory(
startTime: number,
_operations: SyncOperation[],
success: boolean
): Promise<void> {
try {
const entry: SyncHistoryEntry = {
timestamp: startTime,
duration: Date.now() - startTime,
operations: this.operationQueue.filter(op =>
op.status !== 'pending'
),
success,
};
const history = await this.getSyncHistory();
history.unshift(entry);
// Keep only last 50 entries
const trimmedHistory = history.slice(0, 50);
await AsyncStorage.setItem(
SYNC_HISTORY_KEY,
JSON.stringify(trimmedHistory)
);
} catch (error) {
console.error('Failed to record sync history:', error);
}
}
/**
* Get sync history
*/
async getSyncHistory(): Promise<SyncHistoryEntry[]> {
try {
const stored = await AsyncStorage.getItem(SYNC_HISTORY_KEY);
return stored ? JSON.parse(stored) : [];
} catch (error) {
console.error('Failed to get sync history:', error);
return [];
}
}
/**
* Get current sync status
*/
getStatus(): SyncStatus {
return {
isSyncing: this.isSyncing,
currentOperation: this.currentOperation,
queue: this.operationQueue,
lastSyncTime: this.getLastSyncTime(),
overallProgress: this.calculateProgress(),
};
}
/**
* Clear sync history
*/
async clearHistory(): Promise<void> {
try {
await AsyncStorage.removeItem(SYNC_HISTORY_KEY);
} catch (error) {
console.error('Failed to clear sync history:', error);
}
}
/**
* Reset sync state (for testing or error recovery)
*/
async reset(): Promise<void> {
this.isSyncing = false;
this.currentOperation = null;
this.operationQueue = [];
await this.saveSyncStatus();
this.notifyListeners();
}
}
// Export singleton instance
export const syncCoordinator = new SyncCoordinator();