aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/client/sync/crdt/sync-state.ts
blob: 391ccf07f614744badca308f53c1438c553ef29f (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
/**
 * CRDT Sync State Management
 *
 * This module handles the serialization and persistence of CRDT sync state.
 * It tracks which documents have been synced and stores the binary state
 * for incremental sync operations.
 *
 * Design:
 * - Sync state is stored in IndexedDB alongside entity data
 * - Each entity has a corresponding CRDT binary stored in sync state
 * - The state tracks sync vectors for efficient incremental updates
 */

import Dexie from "dexie";
import { type CrdtEntityTypeValue, createDocumentId } from "./types";

/**
 * Sync state entry for a single CRDT document
 */
export interface CrdtSyncStateEntry {
	/** Document ID in format entityType:entityId */
	documentId: string;
	/** Entity type */
	entityType: CrdtEntityTypeValue;
	/** Entity ID */
	entityId: string;
	/** Binary representation of the CRDT document */
	binary: Uint8Array;
	/** Last sync timestamp */
	lastSyncedAt: number;
	/** Sync version from server */
	syncVersion: number;
}

/**
 * Sync metadata for tracking overall sync state
 */
export interface CrdtSyncMetadata {
	/** Unique key for metadata storage */
	key: string;
	/** Last successful sync timestamp */
	lastSyncAt: number;
	/** Server sync version watermark */
	syncVersionWatermark: number;
	/** Actor ID for this client */
	actorId: string;
}

/**
 * Database for storing CRDT sync state
 * Separate from main app database to avoid migration conflicts
 */
class CrdtSyncDatabase extends Dexie {
	syncState!: Dexie.Table<CrdtSyncStateEntry, string>;
	metadata!: Dexie.Table<CrdtSyncMetadata, string>;

	constructor() {
		super("kioku-crdt-sync");

		this.version(1).stores({
			// Primary key is documentId, indexed by entityType and entityId
			syncState: "documentId, entityType, entityId, lastSyncedAt",
			// Simple key-value store for metadata
			metadata: "key",
		});
	}
}

/**
 * Singleton instance of the CRDT sync database
 */
export const crdtSyncDb = new CrdtSyncDatabase();

/**
 * CRDT Sync State Manager
 *
 * Provides operations for managing CRDT sync state:
 * - Store/retrieve CRDT document binaries
 * - Track sync progress
 * - Manage sync metadata
 */
export class CrdtSyncStateManager {
	private readonly metadataKey = "sync-metadata";

	/**
	 * Get the CRDT binary for an entity
	 */
	async getDocumentBinary(
		entityType: CrdtEntityTypeValue,
		entityId: string,
	): Promise<Uint8Array | null> {
		const documentId = createDocumentId(entityType, entityId);
		const entry = await crdtSyncDb.syncState.get(documentId);
		return entry?.binary ?? null;
	}

	/**
	 * Store the CRDT binary for an entity
	 */
	async setDocumentBinary(
		entityType: CrdtEntityTypeValue,
		entityId: string,
		binary: Uint8Array,
		syncVersion: number,
	): Promise<void> {
		const documentId = createDocumentId(entityType, entityId);
		const entry: CrdtSyncStateEntry = {
			documentId,
			entityType,
			entityId,
			binary,
			lastSyncedAt: Date.now(),
			syncVersion,
		};
		await crdtSyncDb.syncState.put(entry);
	}

	/**
	 * Get all CRDT binaries for an entity type
	 */
	async getDocumentsByType(
		entityType: CrdtEntityTypeValue,
	): Promise<CrdtSyncStateEntry[]> {
		return crdtSyncDb.syncState
			.where("entityType")
			.equals(entityType)
			.toArray();
	}

	/**
	 * Delete the CRDT binary for an entity
	 */
	async deleteDocument(
		entityType: CrdtEntityTypeValue,
		entityId: string,
	): Promise<void> {
		const documentId = createDocumentId(entityType, entityId);
		await crdtSyncDb.syncState.delete(documentId);
	}

	/**
	 * Delete all CRDT binaries for an entity type
	 */
	async deleteDocumentsByType(entityType: CrdtEntityTypeValue): Promise<void> {
		await crdtSyncDb.syncState.where("entityType").equals(entityType).delete();
	}

	/**
	 * Get sync metadata
	 */
	async getMetadata(): Promise<CrdtSyncMetadata | null> {
		const metadata = await crdtSyncDb.metadata.get(this.metadataKey);
		return metadata ?? null;
	}

	/**
	 * Update sync metadata
	 */
	async setMetadata(
		updates: Partial<Omit<CrdtSyncMetadata, "key">>,
	): Promise<void> {
		const existing = await this.getMetadata();
		const metadata: CrdtSyncMetadata = {
			key: this.metadataKey,
			lastSyncAt: updates.lastSyncAt ?? existing?.lastSyncAt ?? 0,
			syncVersionWatermark:
				updates.syncVersionWatermark ?? existing?.syncVersionWatermark ?? 0,
			actorId: updates.actorId ?? existing?.actorId ?? "",
		};
		await crdtSyncDb.metadata.put(metadata);
	}

	/**
	 * Get the last sync timestamp
	 */
	async getLastSyncAt(): Promise<number> {
		const metadata = await this.getMetadata();
		return metadata?.lastSyncAt ?? 0;
	}

	/**
	 * Update the last sync timestamp
	 */
	async setLastSyncAt(timestamp: number): Promise<void> {
		await this.setMetadata({ lastSyncAt: timestamp });
	}

	/**
	 * Get the sync version watermark
	 */
	async getSyncVersionWatermark(): Promise<number> {
		const metadata = await this.getMetadata();
		return metadata?.syncVersionWatermark ?? 0;
	}

	/**
	 * Update the sync version watermark
	 */
	async setSyncVersionWatermark(version: number): Promise<void> {
		await this.setMetadata({ syncVersionWatermark: version });
	}

	/**
	 * Clear all sync state (for full resync)
	 */
	async clearAll(): Promise<void> {
		await crdtSyncDb.syncState.clear();
		await crdtSyncDb.metadata.clear();
	}

	/**
	 * Get count of stored documents by type
	 */
	async getDocumentCountByType(
		entityType: CrdtEntityTypeValue,
	): Promise<number> {
		return crdtSyncDb.syncState.where("entityType").equals(entityType).count();
	}

	/**
	 * Get total count of stored documents
	 */
	async getTotalDocumentCount(): Promise<number> {
		return crdtSyncDb.syncState.count();
	}

	/**
	 * Check if a document exists in sync state
	 */
	async hasDocument(
		entityType: CrdtEntityTypeValue,
		entityId: string,
	): Promise<boolean> {
		const documentId = createDocumentId(entityType, entityId);
		const count = await crdtSyncDb.syncState
			.where("documentId")
			.equals(documentId)
			.count();
		return count > 0;
	}

	/**
	 * Get documents that have been synced since a given timestamp
	 */
	async getDocumentsSyncedSince(
		timestamp: number,
	): Promise<CrdtSyncStateEntry[]> {
		return crdtSyncDb.syncState
			.where("lastSyncedAt")
			.above(timestamp)
			.toArray();
	}

	/**
	 * Batch update multiple documents
	 */
	async batchSetDocuments(
		entries: Array<{
			entityType: CrdtEntityTypeValue;
			entityId: string;
			binary: Uint8Array;
			syncVersion: number;
		}>,
	): Promise<void> {
		const now = Date.now();
		const syncEntries: CrdtSyncStateEntry[] = entries.map((entry) => ({
			documentId: createDocumentId(entry.entityType, entry.entityId),
			entityType: entry.entityType,
			entityId: entry.entityId,
			binary: entry.binary,
			lastSyncedAt: now,
			syncVersion: entry.syncVersion,
		}));

		await crdtSyncDb.syncState.bulkPut(syncEntries);
	}

	/**
	 * Batch delete multiple documents
	 */
	async batchDeleteDocuments(
		entries: Array<{
			entityType: CrdtEntityTypeValue;
			entityId: string;
		}>,
	): Promise<void> {
		const documentIds = entries.map((entry) =>
			createDocumentId(entry.entityType, entry.entityId),
		);
		await crdtSyncDb.syncState.bulkDelete(documentIds);
	}
}

/**
 * Singleton instance of the sync state manager
 */
export const crdtSyncStateManager = new CrdtSyncStateManager();

/**
 * Serialize CRDT binary to base64 for network transport
 */
export function binaryToBase64(binary: Uint8Array): string {
	// Use standard base64 encoding
	const bytes = new Uint8Array(binary);
	let binaryStr = "";
	for (const byte of bytes) {
		binaryStr += String.fromCharCode(byte);
	}
	return btoa(binaryStr);
}

/**
 * Deserialize base64 string to CRDT binary
 */
export function base64ToBinary(base64: string): Uint8Array {
	const binaryStr = atob(base64);
	const bytes = new Uint8Array(binaryStr.length);
	for (let i = 0; i < binaryStr.length; i++) {
		bytes[i] = binaryStr.charCodeAt(i);
	}
	return bytes;
}

/**
 * CRDT changes payload for sync API
 */
export interface CrdtSyncPayload {
	/** Document ID */
	documentId: string;
	/** Entity type */
	entityType: CrdtEntityTypeValue;
	/** Entity ID */
	entityId: string;
	/** Base64-encoded CRDT binary */
	binary: string;
}

/**
 * Convert sync state entries to sync payload format
 */
export function entriesToSyncPayload(
	entries: CrdtSyncStateEntry[],
): CrdtSyncPayload[] {
	return entries.map((entry) => ({
		documentId: entry.documentId,
		entityType: entry.entityType,
		entityId: entry.entityId,
		binary: binaryToBase64(entry.binary),
	}));
}

/**
 * Convert sync payload to sync state entries
 */
export function syncPayloadToEntries(
	payloads: CrdtSyncPayload[],
	syncVersion: number,
): Array<{
	entityType: CrdtEntityTypeValue;
	entityId: string;
	binary: Uint8Array;
	syncVersion: number;
}> {
	return payloads.map((payload) => ({
		entityType: payload.entityType,
		entityId: payload.entityId,
		binary: base64ToBinary(payload.binary),
		syncVersion,
	}));
}