@johnhenry/browsermesh-apps 0.1.1 → 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.
@@ -0,0 +1,253 @@
1
+ /**
2
+ * mesh-sync.mjs -- wires a `MeshSyncEngine` (`@johnhenry/browsermesh-sync`)
3
+ * to a `PeerNode`'s (this package) existing message-dispatch bus, so CRDT
4
+ * sync deltas travel over the real connection `PeerNode` already manages
5
+ * instead of a parallel message-passing path.
6
+ *
7
+ * Reuses `PeerNode`'s own envelope-routing convention rather than inventing
8
+ * a new one: outbound via `sendTo()` (accepts plain objects -- the
9
+ * underlying transport JSON-serializes them, see `WebRTCPeerConnection.send`),
10
+ * inbound via `onIncomingData()`, filtering by `envelope.type` (default
11
+ * `'mesh-sync'`) exactly the way `peer-node.mjs`'s own doc comments describe
12
+ * `ClawserPod.onMessage` routing "by `envelope.type`" -- multiple independent
13
+ * consumers of `onIncomingData()` can coexist on the same bus this way, each
14
+ * ignoring envelopes that aren't theirs.
15
+ *
16
+ * Persistence: `createMeshSync()` defaults to a real, durable
17
+ * `IndexedDBSyncStorage` (from `@johnhenry/browsermesh-sync`, Phase 1) --
18
+ * not the in-memory adapter -- because the whole point of that adapter
19
+ * existing is for a workspace's CRDT state to survive a reload. Pass
20
+ * `storage` explicitly to override (e.g. `InMemorySyncStorage` for a test
21
+ * that doesn't care about persistence).
22
+ *
23
+ * No browser-only imports at module level. (`IndexedDBSyncStorage` itself
24
+ * only touches the global `indexedDB` lazily, inside `open()`/`save()`/
25
+ * `load()`, not at construction time -- see storage-indexeddb.mjs.)
26
+ */
27
+
28
+ import { MeshSyncEngine, IndexedDBSyncStorage } from '@johnhenry/browsermesh-sync'
29
+
30
+ /** Default `envelope.type` used to route sync payloads on the shared `onIncomingData()` bus. */
31
+ const DEFAULT_ENVELOPE_TYPE = 'mesh-sync'
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // MeshSyncBinding
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /**
38
+ * Binds a `MeshSyncEngine` to a `PeerNode`'s dispatch bus.
39
+ *
40
+ * Construction wires an `onIncomingData()` subscriber immediately (matching
41
+ * `MeshSignalingChannel`'s "subscribe in the constructor" convention).
42
+ * Outbound sends are explicit (`syncDocWithPeer()`) or driven by `watch()`.
43
+ */
44
+ export class MeshSyncBinding {
45
+ /** @type {import('./peer-node.mjs').PeerNode} */
46
+ #node
47
+
48
+ /** @type {import('@johnhenry/browsermesh-sync').MeshSyncEngine} */
49
+ #engine
50
+
51
+ /** @type {string} */
52
+ #envelopeType
53
+
54
+ /** @type {Function} */
55
+ #onLog
56
+
57
+ /** @type {(() => void)|null} */
58
+ #unsubscribeIncoming = null
59
+
60
+ /** @type {Map<string, () => void>} docId -> unsubscribe from engine.subscribe() */
61
+ #watchers = new Map()
62
+
63
+ /**
64
+ * @param {object} opts
65
+ * @param {import('./peer-node.mjs').PeerNode} opts.node
66
+ * @param {import('@johnhenry/browsermesh-sync').MeshSyncEngine} opts.engine
67
+ * @param {string} [opts.envelopeType='mesh-sync']
68
+ * @param {Function} [opts.onLog]
69
+ */
70
+ constructor({ node, engine, envelopeType, onLog } = {}) {
71
+ if (!node) throw new Error('node is required')
72
+ if (!engine) throw new Error('engine is required')
73
+
74
+ this.#node = node
75
+ this.#engine = engine
76
+ this.#envelopeType = envelopeType || DEFAULT_ENVELOPE_TYPE
77
+ this.#onLog = onLog || (() => {})
78
+
79
+ this.#unsubscribeIncoming = this.#node.onIncomingData((pubKey, data) => {
80
+ this.#handleIncoming(pubKey, data)
81
+ })
82
+ }
83
+
84
+ /** The underlying `MeshSyncEngine`. */
85
+ get engine() {
86
+ return this.#engine
87
+ }
88
+
89
+ /** The `envelope.type` this binding sends/routes on the shared dispatch bus. */
90
+ get envelopeType() {
91
+ return this.#envelopeType
92
+ }
93
+
94
+ // -----------------------------------------------------------------------
95
+ // Outbound
96
+ // -----------------------------------------------------------------------
97
+
98
+ /**
99
+ * Send a document's current full CRDT state to one peer. The remote side
100
+ * merges it in (creating the document locally first if it doesn't have it
101
+ * yet) -- safe to call repeatedly; CRDT merge is idempotent/commutative.
102
+ *
103
+ * @param {string} pubKey - Remote peer's fingerprint / public key hash
104
+ * @param {string} docId
105
+ * @returns {Promise<void>} Resolves once `node.sendTo()` accepts the send.
106
+ */
107
+ async syncDocWithPeer(pubKey, docId) {
108
+ const doc = this.#engine.get(docId)
109
+ if (!doc) {
110
+ throw new Error(`MeshSyncBinding.syncDocWithPeer: unknown document '${docId}'`)
111
+ }
112
+ const payload = this.#engine.prepareSyncPayload(docId)
113
+ await this.#node.sendTo(pubKey, {
114
+ type: this.#envelopeType,
115
+ docId,
116
+ docType: doc.type,
117
+ payload,
118
+ })
119
+ this.#onLog('mesh-sync:sent', { to: pubKey, docId })
120
+ }
121
+
122
+ /**
123
+ * Start auto-broadcasting a document's state to one or more peers
124
+ * whenever it changes locally (`engine.update()` or `engine.merge()`
125
+ * both notify subscribers). Overwrites any existing watch for the same
126
+ * `docId`.
127
+ *
128
+ * @param {string} docId
129
+ * @param {string|string[]} pubKeys - One peer, or several.
130
+ * @returns {() => void} Stops watching this document.
131
+ */
132
+ watch(docId, pubKeys) {
133
+ this.unwatch(docId)
134
+ const targets = Array.isArray(pubKeys) ? pubKeys : [pubKeys]
135
+
136
+ const unsubscribe = this.#engine.subscribe(docId, () => {
137
+ for (const pubKey of targets) {
138
+ this.syncDocWithPeer(pubKey, docId).catch((err) => {
139
+ this.#onLog('mesh-sync:broadcast-failed', {
140
+ to: pubKey,
141
+ docId,
142
+ error: err?.message || String(err),
143
+ })
144
+ })
145
+ }
146
+ })
147
+ this.#watchers.set(docId, unsubscribe)
148
+ return () => this.unwatch(docId)
149
+ }
150
+
151
+ /**
152
+ * Stop auto-broadcasting a document previously passed to `watch()`.
153
+ * @param {string} docId
154
+ */
155
+ unwatch(docId) {
156
+ const unsubscribe = this.#watchers.get(docId)
157
+ if (unsubscribe) {
158
+ unsubscribe()
159
+ this.#watchers.delete(docId)
160
+ }
161
+ }
162
+
163
+ // -----------------------------------------------------------------------
164
+ // Inbound
165
+ // -----------------------------------------------------------------------
166
+
167
+ /**
168
+ * @param {string} pubKey
169
+ * @param {*} data
170
+ */
171
+ #handleIncoming(pubKey, data) {
172
+ if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
173
+ const { docId, docType, payload } = data
174
+ if (!docId || !payload) return
175
+
176
+ try {
177
+ if (!this.#engine.get(docId)) {
178
+ this.#engine.create(docId, docType, { owner: pubKey })
179
+ }
180
+ this.#engine.merge(docId, payload)
181
+ this.#onLog('mesh-sync:merged', { from: pubKey, docId })
182
+ } catch (err) {
183
+ this.#onLog('mesh-sync:merge-failed', { from: pubKey, docId, error: err?.message || String(err) })
184
+ }
185
+ }
186
+
187
+ // -----------------------------------------------------------------------
188
+ // Persistence passthrough
189
+ // -----------------------------------------------------------------------
190
+
191
+ /** Persist all documents through the engine's configured storage adapter. */
192
+ async save() {
193
+ await this.#engine.save()
194
+ }
195
+
196
+ /** Restore documents from the engine's configured storage adapter. */
197
+ async load() {
198
+ await this.#engine.load()
199
+ }
200
+
201
+ // -----------------------------------------------------------------------
202
+ // Teardown
203
+ // -----------------------------------------------------------------------
204
+
205
+ /**
206
+ * Detach from the `PeerNode` dispatch bus and stop all `watch()`es. Does
207
+ * not destroy the engine or its persisted data -- call `engine.destroy()`
208
+ * separately if desired.
209
+ */
210
+ detach() {
211
+ for (const docId of [...this.#watchers.keys()]) this.unwatch(docId)
212
+ if (this.#unsubscribeIncoming) {
213
+ this.#unsubscribeIncoming()
214
+ this.#unsubscribeIncoming = null
215
+ }
216
+ }
217
+ }
218
+
219
+ // ---------------------------------------------------------------------------
220
+ // createMeshSync
221
+ // ---------------------------------------------------------------------------
222
+
223
+ /**
224
+ * Convenience factory: build a `MeshSyncEngine` -- defaulting to durable
225
+ * `IndexedDBSyncStorage`, not the in-memory adapter -- and wire it to
226
+ * `node` via `MeshSyncBinding`.
227
+ *
228
+ * @param {object} opts
229
+ * @param {import('./peer-node.mjs').PeerNode} opts.node
230
+ * @param {object} [opts.storage] - Storage adapter (`save`/`load`/`clear`).
231
+ * Defaults to `new IndexedDBSyncStorage({ dbName })`.
232
+ * @param {string} [opts.nodeId] - CRDT node identity for vector clocks.
233
+ * Defaults to `node.podId`.
234
+ * @param {string} [opts.dbName] - Passed to the default `IndexedDBSyncStorage`.
235
+ * Defaults to `mesh-sync-${node.podId}` so multiple mesh nodes in one
236
+ * process/browser don't collide. Ignored if `storage` is supplied.
237
+ * @param {string} [opts.envelopeType='mesh-sync']
238
+ * @param {Function} [opts.onLog]
239
+ * @returns {MeshSyncBinding}
240
+ */
241
+ export function createMeshSync({ node, storage, nodeId, dbName, envelopeType, onLog } = {}) {
242
+ if (!node) throw new Error('node is required')
243
+
244
+ const engine = new MeshSyncEngine({
245
+ nodeId: nodeId || node.podId,
246
+ storage: storage || new IndexedDBSyncStorage({ dbName: dbName || `mesh-sync-${node.podId}` }),
247
+ onLog,
248
+ })
249
+
250
+ return new MeshSyncBinding({ node, engine, envelopeType, onLog })
251
+ }
252
+
253
+ export { DEFAULT_ENVELOPE_TYPE }
package/src/peer-node.mjs CHANGED
@@ -366,24 +366,110 @@ export class PeerNode {
366
366
 
367
367
  this.#registry.connect(pubKey, connectOpts)
368
368
 
369
- // Create session
369
+ // Create session (and wire its inbound data fan-out) via the same
370
+ // helper `adoptIncomingSession()` uses for the callee side, so both
371
+ // sides of a connection end up with identically-shaped bookkeeping.
372
+ const session = this.#createSession(pubKey, transportType, transport)
373
+
374
+ this.#onLog('peer-node:session:created', {
375
+ sessionId: session.sessionId,
376
+ pubKey,
377
+ transport: transportType,
378
+ })
379
+
380
+ // Log to audit chain
381
+ await this.#audit('peer-node:connect', {
382
+ sessionId: session.sessionId,
383
+ pubKey,
384
+ transport: transportType,
385
+ })
386
+
387
+ return { ...session, transportInstance: undefined }
388
+ }
389
+
390
+ /**
391
+ * Adopt a `PeerNode`-level session for a transport connection this node
392
+ * did not initiate itself -- the callee side of an inbound connection
393
+ * (e.g. a WebRTC peer that only ever answered an offer, and never called
394
+ * `connectToPeer()`).
395
+ *
396
+ * `connectToPeer()` is the only place that used to create session
397
+ * bookkeeping (the entry in `#sessions`, and the inbound-data fan-out
398
+ * `onIncomingData()` subscribers rely on), which meant a peer that was
399
+ * only ever connected *to* had a live, open transport (visible e.g. via
400
+ * `node.meshManager.getConnection(remotePodId)`) but no `PeerNode`-level
401
+ * session -- `sendTo()` would throw "no active session" and its inbound
402
+ * bytes never reached `onIncomingData()` subscribers. This method gives
403
+ * the callee side the same session bookkeeping the caller side already
404
+ * got, so `sendTo()` / `hasActiveSession()` / `onIncomingData()` all work
405
+ * symmetrically regardless of which side dialed.
406
+ *
407
+ * Intended to be called by transport-negotiator adapter factories (see
408
+ * `webrtc-negotiator.mjs`'s `onIncomingConnection` hook), not directly by
409
+ * application code.
410
+ *
411
+ * @param {string} pubKey - Remote peer's fingerprint / public key hash
412
+ * @param {object} transportInstance - An already-open MeshTransport-shaped
413
+ * object: must implement `send(data)`, should implement `onMessage(cb)`.
414
+ * @param {string} transportType - e.g. `'webrtc'`
415
+ * @returns {Promise<object>} Session info (same shape as `connectToPeer()`'s)
416
+ */
417
+ async adoptIncomingSession(pubKey, transportInstance, transportType) {
418
+ this.#ensureRunning('adoptIncomingSession')
419
+ if (!pubKey || typeof pubKey !== 'string') {
420
+ throw new Error('adoptIncomingSession: pubKey is required')
421
+ }
422
+ if (!transportInstance || typeof transportInstance.send !== 'function') {
423
+ throw new Error('adoptIncomingSession: transportInstance must implement send(data)')
424
+ }
425
+
426
+ this.#registry.connect(pubKey, { transport: transportType })
427
+
428
+ const session = this.#createSession(pubKey, transportType, transportInstance)
429
+
430
+ this.#onLog('peer-node:session:adopted', {
431
+ sessionId: session.sessionId,
432
+ pubKey,
433
+ transport: transportType,
434
+ })
435
+
436
+ await this.#audit('peer-node:connect', {
437
+ sessionId: session.sessionId,
438
+ pubKey,
439
+ transport: transportType,
440
+ direction: 'inbound',
441
+ })
442
+
443
+ return { ...session, transportInstance: undefined }
444
+ }
445
+
446
+ /**
447
+ * Shared session-bookkeeping helper for both `connectToPeer()` (caller
448
+ * side) and `adoptIncomingSession()` (callee side): creates the
449
+ * `#sessions` entry and wires inbound data fan-out to `onIncomingData()`
450
+ * subscribers -- this is what backs `ClawserPod.onMessage` so workspace
451
+ * consumers can route incoming sync/deploy envelopes by `envelope.type`.
452
+ *
453
+ * @param {string} pubKey
454
+ * @param {string|null} transportType
455
+ * @param {object|null} transportInstance
456
+ * @returns {object} The new session entry (includes `transportInstance`;
457
+ * callers strip it before returning to their own caller)
458
+ */
459
+ #createSession(pubKey, transportType, transportInstance) {
370
460
  const sessionId = crypto.randomUUID()
371
461
  const session = {
372
462
  sessionId,
373
463
  pubKey,
374
464
  transport: transportType,
375
- transportInstance: transport,
465
+ transportInstance,
376
466
  connectedAt: Date.now(),
377
467
  state: 'active',
378
468
  }
379
469
  this.#sessions.set(sessionId, session)
380
470
 
381
- // Wire inbound data fan-out — every connected transport pushes
382
- // received bytes to subscribers registered via `onIncomingData`.
383
- // This is what backs `ClawserPod.onMessage` so workspace consumers
384
- // can route incoming sync/deploy envelopes by `envelope.type`.
385
- if (transport && typeof transport.onMessage === 'function') {
386
- transport.onMessage((data) => {
471
+ if (transportInstance && typeof transportInstance.onMessage === 'function') {
472
+ transportInstance.onMessage((data) => {
387
473
  for (const cb of this.#dataListeners) {
388
474
  try { cb(pubKey, data, { sessionId, transport: transportType }) }
389
475
  catch (err) { this.#onLog('peer-node:data-listener-error', { error: err?.message || String(err) }) }
@@ -391,16 +477,7 @@ export class PeerNode {
391
477
  })
392
478
  }
393
479
 
394
- this.#onLog('peer-node:session:created', { sessionId, pubKey, transport: transportType })
395
-
396
- // Log to audit chain
397
- await this.#audit('peer-node:connect', {
398
- sessionId,
399
- pubKey,
400
- transport: transportType,
401
- })
402
-
403
- return { ...session, transportInstance: undefined }
480
+ return session
404
481
  }
405
482
 
406
483
  /**