aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/client/sync/manager.ts
blob: b5da89adffaf59c5d16c8eb6feb3f14fcb3bbaab (plain)
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
import type { ConflictResolver } from "./conflict";
import {
	CrdtEntityType,
	type CrdtSyncStateManager,
	crdtSyncStateManager as defaultCrdtSyncStateManager,
} from "./crdt";
import type { PullService, SyncPullResult } from "./pull";
import type { PushService, SyncPushResult } from "./push";
import type { PendingChanges, SyncQueue, SyncQueueState } from "./queue";

/**
 * Sync result from a full sync operation
 */
export interface SyncResult {
	success: boolean;
	pushResult: SyncPushResult | null;
	pullResult: SyncPullResult | null;
	conflictsResolved: number;
	/** Number of CRDT documents stored during sync */
	crdtDocumentsStored: number;
	error?: string;
}

/**
 * Options for creating a sync manager
 */
export interface SyncManagerOptions {
	syncQueue: SyncQueue;
	pushService: PushService;
	pullService: PullService;
	conflictResolver: ConflictResolver;
	/**
	 * CRDT sync state manager for storing CRDT document binaries
	 * Default: singleton crdtSyncStateManager
	 */
	crdtSyncStateManager?: CrdtSyncStateManager;
	/**
	 * Debounce time in ms before syncing after coming online
	 * Default: 1000ms
	 */
	debounceMs?: number;
	/**
	 * Whether to auto-sync when coming online
	 * Default: true
	 */
	autoSync?: boolean;
}

/**
 * Listener for sync manager events
 */
export type SyncManagerListener = (event: SyncManagerEvent) => void;

export type SyncManagerEvent =
	| { type: "online" }
	| { type: "offline" }
	| { type: "sync_start" }
	| { type: "sync_complete"; result: SyncResult }
	| { type: "sync_error"; error: string }
	| { type: "crdt_documents_stored"; count: number };

/**
 * Sync Manager
 *
 * Orchestrates the sync process and handles auto-sync on reconnect:
 * 1. Monitors online/offline status
 * 2. Triggers sync when coming back online
 * 3. Coordinates push, pull, and conflict resolution
 * 4. Manages sync state and notifies listeners
 * 5. Stores CRDT document binaries for conflict-free sync
 */
export class SyncManager {
	private syncQueue: SyncQueue;
	private pushService: PushService;
	private pullService: PullService;
	private conflictResolver: ConflictResolver;
	private crdtSyncStateManager: CrdtSyncStateManager;
	private debounceMs: number;
	private autoSync: boolean;
	private listeners: Set<SyncManagerListener> = new Set();
	private isOnline: boolean;
	private syncInProgress = false;
	private pendingSyncTimeout: ReturnType<typeof setTimeout> | null = null;
	private boundOnlineHandler: () => void;
	private boundOfflineHandler: () => void;
	private started = false;

	constructor(options: SyncManagerOptions) {
		this.syncQueue = options.syncQueue;
		this.pushService = options.pushService;
		this.pullService = options.pullService;
		this.conflictResolver = options.conflictResolver;
		this.crdtSyncStateManager =
			options.crdtSyncStateManager ?? defaultCrdtSyncStateManager;
		this.debounceMs = options.debounceMs ?? 1000;
		this.autoSync = options.autoSync ?? true;
		this.isOnline = typeof navigator !== "undefined" ? navigator.onLine : true;

		// Bind handlers for proper removal later
		this.boundOnlineHandler = this.handleOnline.bind(this);
		this.boundOfflineHandler = this.handleOffline.bind(this);
	}

	/**
	 * Start monitoring network status and auto-syncing
	 */
	start(): void {
		if (this.started) return;
		this.started = true;

		if (typeof window !== "undefined") {
			window.addEventListener("online", this.boundOnlineHandler);
			window.addEventListener("offline", this.boundOfflineHandler);
		}
	}

	/**
	 * Stop monitoring and cleanup
	 */
	stop(): void {
		if (!this.started) return;
		this.started = false;

		if (typeof window !== "undefined") {
			window.removeEventListener("online", this.boundOnlineHandler);
			window.removeEventListener("offline", this.boundOfflineHandler);
		}

		if (this.pendingSyncTimeout) {
			clearTimeout(this.pendingSyncTimeout);
			this.pendingSyncTimeout = null;
		}
	}

	/**
	 * Subscribe to sync manager events
	 */
	subscribe(listener: SyncManagerListener): () => void {
		this.listeners.add(listener);
		return () => this.listeners.delete(listener);
	}

	/**
	 * Notify all listeners of an event
	 */
	private notifyListeners(event: SyncManagerEvent): void {
		for (const listener of this.listeners) {
			listener(event);
		}
	}

	/**
	 * Handle online event
	 */
	private handleOnline(): void {
		this.isOnline = true;
		this.notifyListeners({ type: "online" });

		if (this.autoSync) {
			this.scheduleSyncWithDebounce();
		}
	}

	/**
	 * Handle offline event
	 */
	private handleOffline(): void {
		this.isOnline = false;
		this.notifyListeners({ type: "offline" });

		// Cancel pending sync if going offline
		if (this.pendingSyncTimeout) {
			clearTimeout(this.pendingSyncTimeout);
			this.pendingSyncTimeout = null;
		}
	}

	/**
	 * Schedule sync with debounce to avoid rapid syncs
	 */
	private scheduleSyncWithDebounce(): void {
		if (this.pendingSyncTimeout) {
			clearTimeout(this.pendingSyncTimeout);
		}

		this.pendingSyncTimeout = setTimeout(async () => {
			this.pendingSyncTimeout = null;
			await this.sync();
		}, this.debounceMs);
	}

	/**
	 * Check if currently online
	 */
	getOnlineStatus(): boolean {
		return this.isOnline;
	}

	/**
	 * Check if sync is in progress
	 */
	isSyncing(): boolean {
		return this.syncInProgress;
	}

	/**
	 * Get current sync queue state
	 */
	async getState(): Promise<SyncQueueState> {
		return this.syncQueue.getState();
	}

	/**
	 * Perform a full sync: push then pull
	 *
	 * @returns Sync result with push/pull results and any conflicts resolved
	 */
	async sync(): Promise<SyncResult> {
		// Don't sync if offline or already syncing
		if (!this.isOnline) {
			return {
				success: false,
				pushResult: null,
				pullResult: null,
				conflictsResolved: 0,
				crdtDocumentsStored: 0,
				error: "Offline",
			};
		}

		if (this.syncInProgress) {
			return {
				success: false,
				pushResult: null,
				pullResult: null,
				conflictsResolved: 0,
				crdtDocumentsStored: 0,
				error: "Sync already in progress",
			};
		}

		this.syncInProgress = true;
		this.notifyListeners({ type: "sync_start" });

		try {
			await this.syncQueue.startSync();

			// Get pending changes before push to store CRDT documents
			const pendingChanges = await this.syncQueue.getPendingChanges();

			// Step 1: Push local changes
			const pushResult = await this.pushService.push();

			// Step 2: Store CRDT documents for successfully pushed entities
			const crdtDocumentsStored = await this.storeCrdtDocumentsAfterPush(
				pendingChanges,
				pushResult,
			);

			if (crdtDocumentsStored > 0) {
				this.notifyListeners({
					type: "crdt_documents_stored",
					count: crdtDocumentsStored,
				});
			}

			// Step 3: Pull server changes
			const pullResult = await this.pullService.pull();

			// Step 4: Resolve any conflicts using CRDT merge
			let conflictsResolved = 0;
			if (this.conflictResolver.hasConflicts(pushResult)) {
				const resolution = await this.conflictResolver.resolveConflicts(
					pushResult,
					pullResult,
				);
				conflictsResolved =
					resolution.decks.length +
					resolution.cards.length +
					resolution.noteTypes.length +
					resolution.noteFieldTypes.length +
					resolution.notes.length +
					resolution.noteFieldValues.length;
			}

			// Step 5: Update CRDT sync metadata
			await this.crdtSyncStateManager.setMetadata({
				lastSyncAt: Date.now(),
				syncVersionWatermark: pullResult.currentSyncVersion,
			});

			const result: SyncResult = {
				success: true,
				pushResult,
				pullResult,
				conflictsResolved,
				crdtDocumentsStored,
			};

			this.notifyListeners({ type: "sync_complete", result });
			return result;
		} catch (error) {
			const errorMessage =
				error instanceof Error ? error.message : "Unknown sync error";
			await this.syncQueue.failSync(errorMessage);

			const result: SyncResult = {
				success: false,
				pushResult: null,
				pullResult: null,
				conflictsResolved: 0,
				crdtDocumentsStored: 0,
				error: errorMessage,
			};

			this.notifyListeners({ type: "sync_error", error: errorMessage });
			return result;
		} finally {
			this.syncInProgress = false;
		}
	}

	/**
	 * Store CRDT document binaries after successful push
	 * This ensures we have local CRDT state for future conflict resolution
	 */
	private async storeCrdtDocumentsAfterPush(
		pendingChanges: PendingChanges,
		pushResult: SyncPushResult,
	): Promise<number> {
		const entriesToStore: Array<{
			entityType: (typeof CrdtEntityType)[keyof typeof CrdtEntityType];
			entityId: string;
			binary: Uint8Array;
			syncVersion: number;
		}> = [];

		// Helper to find sync version from push result
		const findSyncVersion = (
			results: { id: string; syncVersion: number }[],
			id: string,
		): number | undefined => {
			return results.find((r) => r.id === id)?.syncVersion;
		};

		// Import CRDT repositories dynamically to avoid circular dependencies
		const {
			crdtDeckRepository,
			crdtNoteTypeRepository,
			crdtNoteFieldTypeRepository,
			crdtNoteRepository,
			crdtNoteFieldValueRepository,
			crdtCardRepository,
			crdtReviewLogRepository,
		} = await import("./crdt");

		// Process pushed decks
		for (const deck of pendingChanges.decks) {
			const syncVersion = findSyncVersion(pushResult.decks, deck.id);
			if (syncVersion !== undefined) {
				const result = crdtDeckRepository.toCrdtDocument(deck);
				entriesToStore.push({
					entityType: CrdtEntityType.Deck,
					entityId: deck.id,
					binary: result.binary,
					syncVersion,
				});
			}
		}

		// Process pushed note types
		for (const noteType of pendingChanges.noteTypes) {
			const syncVersion = findSyncVersion(pushResult.noteTypes, noteType.id);
			if (syncVersion !== undefined) {
				const result = crdtNoteTypeRepository.toCrdtDocument(noteType);
				entriesToStore.push({
					entityType: CrdtEntityType.NoteType,
					entityId: noteType.id,
					binary: result.binary,
					syncVersion,
				});
			}
		}

		// Process pushed note field types
		for (const fieldType of pendingChanges.noteFieldTypes) {
			const syncVersion = findSyncVersion(
				pushResult.noteFieldTypes,
				fieldType.id,
			);
			if (syncVersion !== undefined) {
				const result = crdtNoteFieldTypeRepository.toCrdtDocument(fieldType);
				entriesToStore.push({
					entityType: CrdtEntityType.NoteFieldType,
					entityId: fieldType.id,
					binary: result.binary,
					syncVersion,
				});
			}
		}

		// Process pushed notes
		for (const note of pendingChanges.notes) {
			const syncVersion = findSyncVersion(pushResult.notes, note.id);
			if (syncVersion !== undefined) {
				const result = crdtNoteRepository.toCrdtDocument(note);
				entriesToStore.push({
					entityType: CrdtEntityType.Note,
					entityId: note.id,
					binary: result.binary,
					syncVersion,
				});
			}
		}

		// Process pushed note field values
		for (const fieldValue of pendingChanges.noteFieldValues) {
			const syncVersion = findSyncVersion(
				pushResult.noteFieldValues,
				fieldValue.id,
			);
			if (syncVersion !== undefined) {
				const result = crdtNoteFieldValueRepository.toCrdtDocument(fieldValue);
				entriesToStore.push({
					entityType: CrdtEntityType.NoteFieldValue,
					entityId: fieldValue.id,
					binary: result.binary,
					syncVersion,
				});
			}
		}

		// Process pushed cards
		for (const card of pendingChanges.cards) {
			const syncVersion = findSyncVersion(pushResult.cards, card.id);
			if (syncVersion !== undefined) {
				const result = crdtCardRepository.toCrdtDocument(card);
				entriesToStore.push({
					entityType: CrdtEntityType.Card,
					entityId: card.id,
					binary: result.binary,
					syncVersion,
				});
			}
		}

		// Process pushed review logs
		for (const reviewLog of pendingChanges.reviewLogs) {
			const syncVersion = findSyncVersion(pushResult.reviewLogs, reviewLog.id);
			if (syncVersion !== undefined) {
				const result = crdtReviewLogRepository.toCrdtDocument(reviewLog);
				entriesToStore.push({
					entityType: CrdtEntityType.ReviewLog,
					entityId: reviewLog.id,
					binary: result.binary,
					syncVersion,
				});
			}
		}

		// Batch store all entries
		if (entriesToStore.length > 0) {
			await this.crdtSyncStateManager.batchSetDocuments(entriesToStore);
		}

		return entriesToStore.length;
	}

	/**
	 * Force sync even if auto-sync is disabled
	 */
	async forceSync(): Promise<SyncResult> {
		return this.sync();
	}

	/**
	 * Enable or disable auto-sync
	 */
	setAutoSync(enabled: boolean): void {
		this.autoSync = enabled;
	}

	/**
	 * Check if auto-sync is enabled
	 */
	isAutoSyncEnabled(): boolean {
		return this.autoSync;
	}

	/**
	 * Get CRDT sync statistics
	 */
	async getCrdtSyncStats(): Promise<{
		totalDocuments: number;
		lastSyncAt: number;
		syncVersionWatermark: number;
	}> {
		const [totalDocuments, metadata] = await Promise.all([
			this.crdtSyncStateManager.getTotalDocumentCount(),
			this.crdtSyncStateManager.getMetadata(),
		]);

		return {
			totalDocuments,
			lastSyncAt: metadata?.lastSyncAt ?? 0,
			syncVersionWatermark: metadata?.syncVersionWatermark ?? 0,
		};
	}

	/**
	 * Clear all CRDT sync state
	 * Use this when resetting sync or logging out
	 */
	async clearCrdtState(): Promise<void> {
		await this.crdtSyncStateManager.clearAll();
	}

	/**
	 * Check if a document has CRDT state stored
	 */
	async hasCrdtDocument(
		entityType: (typeof CrdtEntityType)[keyof typeof CrdtEntityType],
		entityId: string,
	): Promise<boolean> {
		return this.crdtSyncStateManager.hasDocument(entityType, entityId);
	}
}

/**
 * Create a sync manager with the given options
 */
export function createSyncManager(options: SyncManagerOptions): SyncManager {
	return new SyncManager(options);
}