@johnhenry/browsermesh-sync 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ /**
2
+ * silent-catch.mjs — debug-gated structured logger for the
3
+ * `try { … } catch { /* ignore *\/ }` pattern.
4
+ *
5
+ * Vendored from clawser-silent-catch.mjs (fully standalone, no other
6
+ * clawser-app imports) so this package doesn't need to reach into web/.
7
+ *
8
+ * Replaces silent catches with an opt-in inspectable record. Default
9
+ * behaviour is unchanged (silent), so this is a drop-in replacement.
10
+ * Users surface the events by enabling debug mode:
11
+ *
12
+ * localStorage.setItem('clawser_debug', 'true') // persistent
13
+ * // or, in DevTools: clawserDebug.enable()
14
+ */
15
+
16
+ let enabled = false;
17
+ try {
18
+ if (typeof localStorage !== 'undefined') {
19
+ enabled = localStorage.getItem('clawser_debug') === 'true';
20
+ }
21
+ } catch {
22
+ // localStorage may throw in privacy / sandbox contexts — treat as disabled
23
+ }
24
+
25
+ /** Re-check the localStorage flag; called by clawserDebug.enable/disable. */
26
+ export function refreshSilentCatchState() {
27
+ try {
28
+ if (typeof localStorage !== 'undefined') {
29
+ enabled = localStorage.getItem('clawser_debug') === 'true';
30
+ }
31
+ } catch {
32
+ enabled = false;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Log a silent-catch event. No-op unless debug mode is enabled.
38
+ *
39
+ * @param {string} module — file/component (e.g. 'clawser-pod')
40
+ * @param {string} operation — what was attempted (e.g. 'relay-disconnect')
41
+ * @param {*} error — the caught value
42
+ * @param {object} [context] — extra structured fields
43
+ */
44
+ export function silentCatch(module, operation, error, context) {
45
+ // Re-read the flag each call so toggles in DevTools take effect without
46
+ // restart. Cheap (one localStorage hit per silent catch in debug mode;
47
+ // catches happen rarely on hot paths).
48
+ if (!enabled) {
49
+ refreshSilentCatchState();
50
+ if (!enabled) return;
51
+ }
52
+ const entry = { module, operation, error: error?.message || String(error) };
53
+ if (context) Object.assign(entry, context);
54
+ console.warn('[clawser:silent-catch]', entry);
55
+ }
package/src/sync.mjs ADDED
@@ -0,0 +1,419 @@
1
+ /**
2
+ * clawser-mesh-sync.js — CRDT State Replication Engine.
3
+ * Manages CRDT documents with storage persistence and delta-based peer sync.
4
+ *
5
+ * Usage:
6
+ * const sync = new MeshSyncEngine({ storage: new InMemorySyncStorage() });
7
+ * const doc = sync.create('config', 'lww-map');
8
+ * sync.update(doc.id, (crdt) => crdt.set('theme', 'dark', Date.now(), 'node1'));
9
+ * const state = sync.getState(doc.id);
10
+ */
11
+
12
+ import {
13
+ VectorClock, LWWRegister, GCounter, PNCounter, ORSet, RGA, LWWMap,
14
+ } from '@johnhenry/browsermesh-primitives';
15
+
16
+ /** @type {readonly string[]} Supported CRDT type identifiers. */
17
+ const CRDT_TYPES = Object.freeze([
18
+ 'lww-register', 'g-counter', 'pn-counter', 'or-set', 'rga', 'lww-map',
19
+ ]);
20
+
21
+ /**
22
+ * Map each type name to its constructor.
23
+ * @type {Record<string, Function>}
24
+ */
25
+ const CRDT_CONSTRUCTORS = {
26
+ 'lww-register': LWWRegister,
27
+ 'g-counter': GCounter,
28
+ 'pn-counter': PNCounter,
29
+ 'or-set': ORSet,
30
+ 'rga': RGA,
31
+ 'lww-map': LWWMap,
32
+ };
33
+
34
+ // ── SyncDocument ─────────────────────────────────────────────────────────────
35
+
36
+ /**
37
+ * A managed CRDT document with metadata for synchronization.
38
+ */
39
+ export class SyncDocument {
40
+ /**
41
+ * @param {object} opts
42
+ * @param {string} opts.id Unique document identifier.
43
+ * @param {string} opts.type One of CRDT_TYPES.
44
+ * @param {string} opts.owner Owning pod / node ID.
45
+ * @param {object} opts.crdt Live CRDT instance.
46
+ * @param {VectorClock} [opts.version] Causality clock for sync.
47
+ * @param {number} [opts.created]
48
+ * @param {number} [opts.lastModified]
49
+ * @param {string[]} [opts.acl] Pod IDs with write access.
50
+ */
51
+ constructor({ id, type, owner, crdt, version, created, lastModified, acl }) {
52
+ this.id = id;
53
+ this.type = type;
54
+ this.owner = owner;
55
+ this.crdt = crdt;
56
+ this.version = version || new VectorClock();
57
+ this.created = created || Date.now();
58
+ this.lastModified = lastModified || this.created;
59
+ this.acl = acl || [];
60
+ }
61
+
62
+ /** Serialize the document to a plain JSON-compatible object. */
63
+ toJSON() {
64
+ return {
65
+ id: this.id,
66
+ type: this.type,
67
+ owner: this.owner,
68
+ crdt: this.crdt.toJSON(),
69
+ version: this.version.toJSON(),
70
+ created: this.created,
71
+ lastModified: this.lastModified,
72
+ acl: [...this.acl],
73
+ };
74
+ }
75
+
76
+ /**
77
+ * Reconstruct a SyncDocument from a serialized plain object.
78
+ * @param {object} data
79
+ * @returns {SyncDocument}
80
+ */
81
+ static fromJSON(data) {
82
+ const Ctor = CRDT_CONSTRUCTORS[data.type];
83
+ if (!Ctor) throw new Error(`Unknown CRDT type: ${data.type}`);
84
+ return new SyncDocument({
85
+ id: data.id,
86
+ type: data.type,
87
+ owner: data.owner,
88
+ crdt: Ctor.fromJSON(data.crdt),
89
+ version: VectorClock.fromJSON(data.version),
90
+ created: data.created,
91
+ lastModified: data.lastModified,
92
+ acl: data.acl || [],
93
+ });
94
+ }
95
+ }
96
+
97
+ // ── MeshSyncEngine ───────────────────────────────────────────────────────────
98
+
99
+ /**
100
+ * Manages a set of CRDT documents with create / read / update / merge
101
+ * operations, subscriber notifications, persistence, and auto-sync.
102
+ */
103
+ export class MeshSyncEngine {
104
+ /** @type {Map<string, SyncDocument>} */
105
+ #documents = new Map();
106
+ /** @type {Map<string, Set<Function>>} */
107
+ #subscriptions = new Map();
108
+ /** @type {string} */
109
+ #nodeId;
110
+ /** @type {InMemorySyncStorage|object} */
111
+ #storage;
112
+ /** @type {Map<string, number>} docId -> intervalId */
113
+ #autoSyncIntervals = new Map();
114
+ /** @type {Function} */
115
+ #onLog;
116
+
117
+ /**
118
+ * @param {object} [opts]
119
+ * @param {string} [opts.nodeId] Identity for this engine (used in vector clocks).
120
+ * @param {object} [opts.storage] Persistence adapter (save/load/clear).
121
+ * @param {Function} [opts.onLog] Logging callback (level, msg).
122
+ */
123
+ constructor(opts = {}) {
124
+ this.#nodeId = opts.nodeId || `node_${Date.now().toString(36)}`;
125
+ this.#storage = opts.storage || new InMemorySyncStorage();
126
+ this.#onLog = opts.onLog || (() => {});
127
+ }
128
+
129
+ /** The engine's node identity string. */
130
+ get nodeId() { return this.#nodeId; }
131
+
132
+ /** Number of documents currently managed. */
133
+ get size() { return this.#documents.size; }
134
+
135
+ // ── CRUD ────────────────────────────────────────────────────────────────────
136
+
137
+ /**
138
+ * Create a new CRDT document and register it with the engine.
139
+ * @param {string} id Document identifier (must be unique).
140
+ * @param {string} type One of CRDT_TYPES.
141
+ * @param {object} [opts]
142
+ * @param {string} [opts.owner]
143
+ * @param {string[]} [opts.acl]
144
+ * @returns {SyncDocument}
145
+ */
146
+ create(id, type, opts = {}) {
147
+ if (!CRDT_TYPES.includes(type)) {
148
+ throw new Error(`Unknown CRDT type: ${type}. Valid types: ${CRDT_TYPES.join(', ')}`);
149
+ }
150
+ if (this.#documents.has(id)) {
151
+ throw new Error(`Document already exists: ${id}`);
152
+ }
153
+ const Ctor = CRDT_CONSTRUCTORS[type];
154
+ const doc = new SyncDocument({
155
+ id,
156
+ type,
157
+ owner: opts.owner || this.#nodeId,
158
+ crdt: new Ctor(),
159
+ acl: opts.acl || [],
160
+ });
161
+ this.#documents.set(id, doc);
162
+ return doc;
163
+ }
164
+
165
+ /**
166
+ * Retrieve a document by ID, or null if not found.
167
+ * @param {string} docId
168
+ * @returns {SyncDocument|null}
169
+ */
170
+ get(docId) {
171
+ return this.#documents.get(docId) || null;
172
+ }
173
+
174
+ /**
175
+ * Return the user-facing value of a document's CRDT.
176
+ * For CRDTs that expose a `.value` getter, that is returned.
177
+ * For CRDTs with only a `.state()` method, `.state()` is used.
178
+ * @param {string} docId
179
+ * @returns {*} CRDT value, or null when the document does not exist.
180
+ */
181
+ getState(docId) {
182
+ const doc = this.#documents.get(docId);
183
+ if (!doc) return null;
184
+ // All current mesh-primitives CRDTs define a `.value` getter.
185
+ // LWWRegister.value can legitimately be null, so we check `undefined`.
186
+ return doc.crdt.value !== undefined ? doc.crdt.value : doc.crdt.state();
187
+ }
188
+
189
+ /**
190
+ * Apply a mutation to a document via callback.
191
+ *
192
+ * The callback receives the live CRDT instance and may call any mutating
193
+ * method on it. After the callback returns the document's vector clock is
194
+ * incremented and all subscribers are notified.
195
+ *
196
+ * @param {string} docId
197
+ * @param {Function} updateFn Receives the CRDT instance.
198
+ */
199
+ update(docId, updateFn) {
200
+ const doc = this.#documents.get(docId);
201
+ if (!doc) throw new Error(`Document not found: ${docId}`);
202
+ updateFn(doc.crdt);
203
+ doc.version = doc.version.increment(this.#nodeId);
204
+ doc.lastModified = Date.now();
205
+ this.#notifySubscribers(docId, doc);
206
+ }
207
+
208
+ /**
209
+ * Merge a remote sync payload into a local document.
210
+ *
211
+ * The remote payload is typically obtained via `prepareSyncPayload()` on
212
+ * a peer engine. CRDT merge is always conflict-free by design.
213
+ *
214
+ * @param {string} docId
215
+ * @param {object} remoteData Must contain `crdt` and `version` fields.
216
+ * @returns {{ conflicts: number }} Always `{ conflicts: 0 }`.
217
+ */
218
+ merge(docId, remoteData) {
219
+ const doc = this.#documents.get(docId);
220
+ if (!doc) throw new Error(`Document not found: ${docId}`);
221
+
222
+ const Ctor = CRDT_CONSTRUCTORS[doc.type];
223
+ const remoteCrdt = Ctor.fromJSON(remoteData.crdt);
224
+ const remoteVersion = VectorClock.fromJSON(remoteData.version);
225
+
226
+ // CRDT merge returns a new instance.
227
+ doc.crdt = doc.crdt.merge(remoteCrdt);
228
+ doc.version = doc.version.merge(remoteVersion);
229
+ doc.lastModified = Date.now();
230
+
231
+ this.#notifySubscribers(docId, doc);
232
+ return { conflicts: 0 };
233
+ }
234
+
235
+ // ── Subscriptions ──────────────────────────────────────────────────────────
236
+
237
+ /**
238
+ * Subscribe to state changes on a document.
239
+ * @param {string} docId
240
+ * @param {Function} callback Called with (currentValue, document).
241
+ * @returns {Function} Unsubscribe function.
242
+ */
243
+ subscribe(docId, callback) {
244
+ if (!this.#subscriptions.has(docId)) {
245
+ this.#subscriptions.set(docId, new Set());
246
+ }
247
+ this.#subscriptions.get(docId).add(callback);
248
+ return () => {
249
+ const subs = this.#subscriptions.get(docId);
250
+ if (subs) subs.delete(callback);
251
+ };
252
+ }
253
+
254
+ /** @param {string} docId @param {SyncDocument} doc */
255
+ #notifySubscribers(docId, doc) {
256
+ const subs = this.#subscriptions.get(docId);
257
+ if (!subs || subs.size === 0) return;
258
+ const val = doc.crdt.value !== undefined ? doc.crdt.value : doc.crdt.state();
259
+ for (const cb of subs) {
260
+ try { cb(val, doc); } catch { /* subscriber errors do not propagate */ }
261
+ }
262
+ }
263
+
264
+ // ── Lifecycle ──────────────────────────────────────────────────────────────
265
+
266
+ /**
267
+ * Delete a document and tear down its subscriptions and auto-sync.
268
+ * @param {string} docId
269
+ * @returns {boolean} True if the document existed.
270
+ */
271
+ delete(docId) {
272
+ const existed = this.#documents.delete(docId);
273
+ this.#subscriptions.delete(docId);
274
+ this.stopAutoSync(docId);
275
+ return existed;
276
+ }
277
+
278
+ /**
279
+ * Return summary metadata for all managed documents.
280
+ * @returns {Array<{id: string, type: string, owner: string, lastModified: number}>}
281
+ */
282
+ listDocuments() {
283
+ return [...this.#documents.values()].map(d => ({
284
+ id: d.id,
285
+ type: d.type,
286
+ owner: d.owner,
287
+ lastModified: d.lastModified,
288
+ }));
289
+ }
290
+
291
+ // ── Sync payloads ──────────────────────────────────────────────────────────
292
+
293
+ /**
294
+ * Build a serializable sync payload for a peer.
295
+ * @param {string} docId
296
+ * @returns {object|null} Payload or null if document not found.
297
+ */
298
+ prepareSyncPayload(docId) {
299
+ const doc = this.#documents.get(docId);
300
+ if (!doc) return null;
301
+ return {
302
+ id: doc.id,
303
+ type: doc.type,
304
+ crdt: doc.crdt.toJSON(),
305
+ version: doc.version.toJSON(),
306
+ };
307
+ }
308
+
309
+ // ── Auto-sync ──────────────────────────────────────────────────────────────
310
+
311
+ /**
312
+ * Periodically call `syncFn` with the sync payload for a document.
313
+ * The caller is responsible for actually transmitting the payload.
314
+ *
315
+ * @param {string} docId
316
+ * @param {Function} syncFn Called with the sync payload object.
317
+ * @param {number} [intervalMs=5000]
318
+ * @returns {Function} Stopper — call to cancel auto-sync for this doc.
319
+ */
320
+ startAutoSync(docId, syncFn, intervalMs = 5000) {
321
+ this.stopAutoSync(docId);
322
+ const id = setInterval(() => {
323
+ const payload = this.prepareSyncPayload(docId);
324
+ if (payload) syncFn(payload);
325
+ }, intervalMs);
326
+ this.#autoSyncIntervals.set(docId, id);
327
+ return () => this.stopAutoSync(docId);
328
+ }
329
+
330
+ /**
331
+ * Stop auto-sync for a single document.
332
+ * @param {string} docId
333
+ */
334
+ stopAutoSync(docId) {
335
+ const id = this.#autoSyncIntervals.get(docId);
336
+ if (id !== undefined) {
337
+ clearInterval(id);
338
+ this.#autoSyncIntervals.delete(docId);
339
+ }
340
+ }
341
+
342
+ /** Stop all running auto-sync intervals. */
343
+ stopAllAutoSync() {
344
+ for (const [, id] of this.#autoSyncIntervals) {
345
+ clearInterval(id);
346
+ }
347
+ this.#autoSyncIntervals.clear();
348
+ }
349
+
350
+ // ── Persistence ────────────────────────────────────────────────────────────
351
+
352
+ /**
353
+ * Persist all documents through the configured storage adapter.
354
+ */
355
+ async save() {
356
+ const docs = [];
357
+ for (const doc of this.#documents.values()) {
358
+ docs.push(doc.toJSON());
359
+ }
360
+ await this.#storage.save(docs);
361
+ }
362
+
363
+ /**
364
+ * Restore documents from the configured storage adapter.
365
+ * Existing in-memory documents are **not** cleared first — loaded documents
366
+ * are added (or overwrite by ID).
367
+ */
368
+ async load() {
369
+ const data = await this.#storage.load();
370
+ if (!data) return;
371
+ for (const item of data) {
372
+ try {
373
+ const doc = SyncDocument.fromJSON(item);
374
+ this.#documents.set(doc.id, doc);
375
+ } catch (e) {
376
+ this.#onLog(3, `Failed to load document ${item.id}: ${e.message}`);
377
+ }
378
+ }
379
+ }
380
+
381
+ // ── Teardown ───────────────────────────────────────────────────────────────
382
+
383
+ /**
384
+ * Destroy the engine — stops all auto-sync intervals and clears
385
+ * subscriptions. Does **not** delete persisted data.
386
+ */
387
+ destroy() {
388
+ this.stopAllAutoSync();
389
+ this.#subscriptions.clear();
390
+ }
391
+ }
392
+
393
+ // ── InMemorySyncStorage ──────────────────────────────────────────────────────
394
+
395
+ /**
396
+ * Trivial in-memory storage adapter for sync documents.
397
+ * Suitable for tests and ephemeral sessions.
398
+ */
399
+ export class InMemorySyncStorage {
400
+ /** @type {object[]|null} */
401
+ #data = null;
402
+
403
+ /** @param {object[]} docs */
404
+ async save(docs) {
405
+ // Deep-clone through JSON to decouple from live objects.
406
+ this.#data = JSON.parse(JSON.stringify(docs));
407
+ }
408
+
409
+ /** @returns {Promise<object[]|null>} */
410
+ async load() {
411
+ return this.#data;
412
+ }
413
+
414
+ async clear() {
415
+ this.#data = null;
416
+ }
417
+ }
418
+
419
+ export { CRDT_TYPES };