aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/client/sync/manager.ts
blob: d935a3bdf08ba03b635293f28f6b86e6a464a10b (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
import type { ConflictResolver } from "./conflict";
import type { PullService, SyncPullResult } from "./pull";
import type { PushService, SyncPushResult } from "./push";
import type { SyncQueue, SyncQueueState } from "./queue";

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

/**
 * Options for creating a sync manager
 */
export interface SyncManagerOptions {
	syncQueue: SyncQueue;
	pushService: PushService;
	pullService: PullService;
	conflictResolver: ConflictResolver;
	/**
	 * 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 };

/**
 * 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
 */
export class SyncManager {
	private syncQueue: SyncQueue;
	private pushService: PushService;
	private pullService: PullService;
	private conflictResolver: ConflictResolver;
	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.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,
				error: "Offline",
			};
		}

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

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

		try {
			await this.syncQueue.startSync();

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

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

			// Step 3: Resolve any conflicts
			let conflictsResolved = 0;
			if (this.conflictResolver.hasConflicts(pushResult)) {
				const resolution = await this.conflictResolver.resolveConflicts(
					pushResult,
					pullResult,
				);
				conflictsResolved = resolution.decks.length + resolution.cards.length;
			}

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

			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,
				error: errorMessage,
			};

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

	/**
	 * 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;
	}
}

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