@johnhenry/browsermesh-sync 0.1.0 → 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@johnhenry/browsermesh-sync",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "CRDT sync engine, delta sync, file transfer, and collaboration for BrowserMesh",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // browsermesh-sync — CRDT & sync
2
2
  export * from './sync.mjs';
3
3
  export * from './storage-indexeddb.mjs';
4
+ export * from './storage-indexeddb-chunks.mjs';
4
5
  export * from './delta-sync.mjs';
5
6
  export * from './migration.mjs';
6
7
  export * from './files.mjs';
@@ -0,0 +1,275 @@
1
+ /**
2
+ * storage-indexeddb-chunks.mjs — IndexedDB-backed content-addressed chunk
3
+ * store for `MeshFileTransfer`.
4
+ *
5
+ * Implements the same `save(cid, data)` / `get(cid)` / `has(cid)` /
6
+ * `verify(cid, data)` / `remove(cid)` / `size` / `clear()` contract as the
7
+ * in-memory `ChunkStore` (see `files.mjs`), but persists chunk bytes to a
8
+ * real IndexedDB object store so content survives a page reload — a `Map`
9
+ * can't do that, which is the entire point of this adapter.
10
+ *
11
+ * Modeled directly on this package's own `storage-indexeddb.mjs`
12
+ * (`IndexedDBSyncStorage`): same "wrap IndexedDB's callback/event API in
13
+ * promises, one object store, open-or-create on first use" shape, same
14
+ * error-handling conventions, same lazy-`open()`-on-first-use pattern.
15
+ *
16
+ * Deliberately, completely unaware of encryption: it stores and serves
17
+ * whatever opaque `Uint8Array` bytes it is handed, keyed by CID string. A
18
+ * later layer (a future `CloudStorageBackend`, per the mesh-native-services
19
+ * plan) is responsible for encrypting data before `save()` and decrypting
20
+ * after `get()` — this class has no encryption-related parameters or logic,
21
+ * by design.
22
+ *
23
+ * Interface note (unavoidable, not an oversight): `ChunkStore`'s `save`/
24
+ * `get`/`has`/`remove`/`clear` are synchronous (a `Map` allows that);
25
+ * IndexedDB is inherently asynchronous, so the equivalent methods here
26
+ * return Promises instead. Every existing caller of `ChunkStore.verify()`
27
+ * (already async, since it hashes via `crypto.subtle`) already awaits it,
28
+ * so callers that consistently `await` chunk-store calls can swap one
29
+ * implementation for the other. `size` remains a synchronous getter (same
30
+ * signature as `ChunkStore`) but is necessarily a best-effort cache of
31
+ * known keys — populated from the real object store the first time `open()`
32
+ * resolves (i.e. the first time any other method is awaited), then kept in
33
+ * sync locally by `save()`/`remove()`/`clear()`. It will read `0` for a
34
+ * freshly-constructed instance whose `open()` hasn't resolved yet, and
35
+ * won't reflect chunks written concurrently by another instance/tab
36
+ * pointed at the same database — exactly the kind of caveat you'd expect
37
+ * from making a synchronous view onto async storage.
38
+ *
39
+ * Usage:
40
+ * const store = new IndexedDBChunkStore({ dbName: 'my-app-chunks' });
41
+ * const cid = await IndexedDBChunkStore.computeCid(data);
42
+ * await store.save(cid, data);
43
+ * ...
44
+ * const bytes = await store.get(cid); // survives a reload
45
+ */
46
+
47
+ import { ChunkStore } from './files.mjs';
48
+
49
+ /**
50
+ * IndexedDB-backed, content-addressed storage for file chunks. CIDs are
51
+ * SHA-256 hex strings, computed identically to `ChunkStore` (this class
52
+ * reuses `ChunkStore.computeCid` directly rather than reimplementing
53
+ * hashing, so CIDs are byte-for-byte interchangeable between the two
54
+ * stores).
55
+ */
56
+ export class IndexedDBChunkStore {
57
+ /** @type {string} */
58
+ #dbName;
59
+
60
+ /** @type {string} */
61
+ #storeName;
62
+
63
+ /** @type {IDBDatabase|null} */
64
+ #db = null;
65
+
66
+ /** @type {Promise<void>|null} in-flight open(), so concurrent callers share it */
67
+ #opening = null;
68
+
69
+ /** Local cache of known keys, backing the synchronous `size` getter. */
70
+ #keys = new Set();
71
+
72
+ /**
73
+ * @param {object} [opts]
74
+ * @param {string} [opts.dbName='mesh-chunks'] IndexedDB database name.
75
+ * Configurable so multiple chunk stores in one page (distinct
76
+ * workspaces/buckets/tenants) can use separate databases without
77
+ * colliding.
78
+ * @param {string} [opts.storeName='chunks'] Object store name within
79
+ * the database.
80
+ */
81
+ constructor(opts = {}) {
82
+ this.#dbName = opts.dbName || 'mesh-chunks';
83
+ this.#storeName = opts.storeName || 'chunks';
84
+ }
85
+
86
+ /**
87
+ * Compute a content ID (SHA-256 hex) for data. Delegates directly to
88
+ * `ChunkStore.computeCid` so both stores are guaranteed to produce
89
+ * identical CIDs for identical bytes.
90
+ * @param {Uint8Array} data
91
+ * @returns {Promise<string>}
92
+ */
93
+ static computeCid(data) {
94
+ return ChunkStore.computeCid(data);
95
+ }
96
+
97
+ /**
98
+ * Open the IndexedDB database, creating the object store on first use,
99
+ * and prime the local key cache from what's already persisted. Safe to
100
+ * call multiple times, and safe to call concurrently — subsequent/
101
+ * concurrent calls share the same in-flight open.
102
+ * @returns {Promise<void>}
103
+ */
104
+ async open() {
105
+ if (this.#db) return;
106
+ if (this.#opening) return this.#opening;
107
+ if (typeof indexedDB === 'undefined') {
108
+ throw new Error('IndexedDB not available');
109
+ }
110
+
111
+ const storeName = this.#storeName;
112
+
113
+ this.#opening = new Promise((resolve, reject) => {
114
+ const request = indexedDB.open(this.#dbName, 1);
115
+
116
+ request.onupgradeneeded = (event) => {
117
+ const db = event.target.result;
118
+ if (!db.objectStoreNames.contains(storeName)) {
119
+ // Out-of-line keys: the CID is passed explicitly to put()/get(),
120
+ // not derived from a keyPath on the stored value. Chunk values
121
+ // are raw Uint8Array bytes (IndexedDB structured-clones typed
122
+ // arrays natively), not JSON-serializable records.
123
+ db.createObjectStore(storeName);
124
+ }
125
+ };
126
+
127
+ request.onsuccess = (event) => {
128
+ this.#db = event.target.result;
129
+ this.#db.onclose = () => { this.#db = null; };
130
+ resolve();
131
+ };
132
+
133
+ request.onerror = () => {
134
+ reject(new Error(`Failed to open IndexedDB "${this.#dbName}": ${request.error?.message}`));
135
+ };
136
+ }).then(() => this.#primeKeyCache());
137
+
138
+ try {
139
+ await this.#opening;
140
+ } finally {
141
+ this.#opening = null;
142
+ }
143
+ }
144
+
145
+ /** Populate `#keys` from whatever is already in the object store. */
146
+ async #primeKeyCache() {
147
+ return new Promise((resolve, reject) => {
148
+ const tx = this.#db.transaction(this.#storeName, 'readonly');
149
+ const store = tx.objectStore(this.#storeName);
150
+ const req = store.getAllKeys();
151
+ req.onsuccess = () => {
152
+ this.#keys = new Set(req.result);
153
+ resolve();
154
+ };
155
+ req.onerror = () => reject(new Error(`Failed to read keys from "${this.#dbName}": ${req.error?.message}`));
156
+ });
157
+ }
158
+
159
+ /**
160
+ * Store a chunk by its CID.
161
+ * @param {string} cid
162
+ * @param {Uint8Array} data
163
+ * @returns {Promise<void>}
164
+ */
165
+ async save(cid, data) {
166
+ if (!this.#db) await this.open();
167
+ return new Promise((resolve, reject) => {
168
+ const tx = this.#db.transaction(this.#storeName, 'readwrite');
169
+ const store = tx.objectStore(this.#storeName);
170
+ store.put(data, cid);
171
+ tx.oncomplete = () => {
172
+ this.#keys.add(cid);
173
+ resolve();
174
+ };
175
+ tx.onerror = () => reject(new Error(`Failed to save chunk "${cid}" to "${this.#dbName}": ${tx.error?.message}`));
176
+ tx.onabort = () => reject(new Error(`Save transaction aborted for chunk "${cid}" in "${this.#dbName}": ${tx.error?.message}`));
177
+ });
178
+ }
179
+
180
+ /**
181
+ * Retrieve a chunk by CID.
182
+ * @param {string} cid
183
+ * @returns {Promise<Uint8Array|undefined>}
184
+ */
185
+ async get(cid) {
186
+ if (!this.#db) await this.open();
187
+ return new Promise((resolve, reject) => {
188
+ const tx = this.#db.transaction(this.#storeName, 'readonly');
189
+ const store = tx.objectStore(this.#storeName);
190
+ const req = store.get(cid);
191
+ req.onsuccess = () => resolve(req.result);
192
+ req.onerror = () => reject(new Error(`Failed to get chunk "${cid}" from "${this.#dbName}": ${req.error?.message}`));
193
+ });
194
+ }
195
+
196
+ /**
197
+ * Check if a chunk exists.
198
+ * @param {string} cid
199
+ * @returns {Promise<boolean>}
200
+ */
201
+ async has(cid) {
202
+ if (!this.#db) await this.open();
203
+ return new Promise((resolve, reject) => {
204
+ const tx = this.#db.transaction(this.#storeName, 'readonly');
205
+ const store = tx.objectStore(this.#storeName);
206
+ const req = store.getKey(cid);
207
+ req.onsuccess = () => resolve(req.result !== undefined);
208
+ req.onerror = () => reject(new Error(`Failed to check chunk "${cid}" in "${this.#dbName}": ${req.error?.message}`));
209
+ });
210
+ }
211
+
212
+ /**
213
+ * Verify that data matches the expected CID.
214
+ * @param {string} cid
215
+ * @param {Uint8Array} data
216
+ * @returns {Promise<boolean>}
217
+ */
218
+ async verify(cid, data) {
219
+ const computed = await IndexedDBChunkStore.computeCid(data);
220
+ return computed === cid;
221
+ }
222
+
223
+ /**
224
+ * Remove a chunk by CID.
225
+ * @param {string} cid
226
+ * @returns {Promise<boolean>} whether a chunk with that CID existed
227
+ */
228
+ async remove(cid) {
229
+ if (!this.#db) await this.open();
230
+ const existed = this.#keys.has(cid);
231
+ return new Promise((resolve, reject) => {
232
+ const tx = this.#db.transaction(this.#storeName, 'readwrite');
233
+ const store = tx.objectStore(this.#storeName);
234
+ store.delete(cid);
235
+ tx.oncomplete = () => {
236
+ this.#keys.delete(cid);
237
+ resolve(existed);
238
+ };
239
+ tx.onerror = () => reject(new Error(`Failed to remove chunk "${cid}" from "${this.#dbName}": ${tx.error?.message}`));
240
+ tx.onabort = () => reject(new Error(`Remove transaction aborted for chunk "${cid}" in "${this.#dbName}": ${tx.error?.message}`));
241
+ });
242
+ }
243
+
244
+ /**
245
+ * Number of stored chunks, per the local key cache (see the class-level
246
+ * doc comment for the caveats of a synchronous view onto async storage).
247
+ */
248
+ get size() { return this.#keys.size; }
249
+
250
+ /**
251
+ * Clear all chunks.
252
+ * @returns {Promise<void>}
253
+ */
254
+ async clear() {
255
+ if (!this.#db) await this.open();
256
+ return new Promise((resolve, reject) => {
257
+ const tx = this.#db.transaction(this.#storeName, 'readwrite');
258
+ const store = tx.objectStore(this.#storeName);
259
+ const req = store.clear();
260
+ req.onsuccess = () => {
261
+ this.#keys.clear();
262
+ resolve();
263
+ };
264
+ req.onerror = () => reject(new Error(`Failed to clear chunks in "${this.#dbName}": ${req.error?.message}`));
265
+ });
266
+ }
267
+
268
+ /** Close the database connection, if open. */
269
+ close() {
270
+ if (this.#db) {
271
+ this.#db.close();
272
+ this.#db = null;
273
+ }
274
+ }
275
+ }
package/src/sync.mjs CHANGED
@@ -211,6 +211,23 @@ export class MeshSyncEngine {
211
211
  * The remote payload is typically obtained via `prepareSyncPayload()` on
212
212
  * a peer engine. CRDT merge is always conflict-free by design.
213
213
  *
214
+ * Subscribers are only notified when the remote payload actually carries
215
+ * causal information this document hasn't already incorporated. Without
216
+ * this check, two peers with mutual `watch()`/auto-broadcast-on-change
217
+ * (see `mesh-kv.mjs`, `manifest-sync.mjs`) would notify each other on
218
+ * every merge -- including no-op merges of state each side already has --
219
+ * producing an unbounded broadcast -> merge -> notify -> broadcast cycle
220
+ * with no timeout (see #112). The document's vector clock is a reliable,
221
+ * cheap proxy for this: every local mutation goes through `update()`
222
+ * (which increments it) or `merge()` (which folds in the remote clock via
223
+ * component-wise max), so if `doc.version` already causally dominates (or
224
+ * equals) `remoteVersion`, the remote has nothing this document hasn't
225
+ * already seen and the CRDT merge below is guaranteed to be a value-level
226
+ * no-op. The merge itself is still performed unconditionally (it's cheap
227
+ * and idempotent, and keeps `merge()`'s other guarantees -- e.g. that
228
+ * `doc.crdt`/`doc.version` always reflect the union of both sides --
229
+ * unchanged); only the notification is conditional.
230
+ *
214
231
  * @param {string} docId
215
232
  * @param {object} remoteData Must contain `crdt` and `version` fields.
216
233
  * @returns {{ conflicts: number }} Always `{ conflicts: 0 }`.
@@ -223,12 +240,17 @@ export class MeshSyncEngine {
223
240
  const remoteCrdt = Ctor.fromJSON(remoteData.crdt);
224
241
  const remoteVersion = VectorClock.fromJSON(remoteData.version);
225
242
 
243
+ const cmp = doc.version.compare(remoteVersion);
244
+ const isNewInformation = cmp !== 'after' && cmp !== 'equal';
245
+
226
246
  // CRDT merge returns a new instance.
227
247
  doc.crdt = doc.crdt.merge(remoteCrdt);
228
248
  doc.version = doc.version.merge(remoteVersion);
229
249
  doc.lastModified = Date.now();
230
250
 
231
- this.#notifySubscribers(docId, doc);
251
+ if (isNewInformation) {
252
+ this.#notifySubscribers(docId, doc);
253
+ }
232
254
  return { conflicts: 0 };
233
255
  }
234
256