@johnhenry/browsermesh-apps 0.10.0 → 0.11.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/README.md +72 -0
- package/package.json +1 -1
- package/src/chunk-replication.mjs +2 -2
- package/src/index.mjs +1 -0
- package/src/internal/wire-envelope.mjs +33 -0
- package/src/mesh-relay-backend.mjs +2 -0
- package/src/mesh-relay-host.mjs +3 -0
- package/src/mesh-service.mjs +28 -6
- package/src/mesh-sync.mjs +2 -0
- package/src/mesh-websocket.mjs +3 -1
- package/src/peer-node-transport.mjs +114 -0
- package/src/peer-node.mjs +94 -2
package/README.md
CHANGED
|
@@ -19,6 +19,7 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
|
|
|
19
19
|
- [CloudStorage: the ergonomic SDK](#cloudstorage-the-ergonomic-sdk)
|
|
20
20
|
- [Torrent service: durable stores, authorization and serve limits](#torrent-service-durable-stores-authorization-and-serve-limits)
|
|
21
21
|
- [Putting it all together: sync + kernel-gated mesh + relay on one connection](#putting-it-all-together-sync--kernel-gated-mesh--relay-on-one-connection)
|
|
22
|
+
- [Sending to peers: wire format, the bulk lane and `broadcast()`](#sending-to-peers-wire-format-the-bulk-lane-and-broadcast)
|
|
22
23
|
- [`fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`](#fetchwebsocket-shaped-mesh-access-browsermeshfetch-and-browsermeshwebsocket)
|
|
23
24
|
- [`browserMeshFetch`](#browsermeshfetch)
|
|
24
25
|
- [`BrowserMeshWebSocket`](#browsermeshwebsocket)
|
|
@@ -62,6 +63,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
62
63
|
| peer-health | `HealthMonitor`, `AutoMigrator` |
|
|
63
64
|
| peer-ipfs | `IPFSStore` (also exported as `MeshLocalCidStore`): a mesh-local content-addressed store. CIDs are SHA-256 hex digests, not IPFS CIDs, and nothing talks to the IPFS network |
|
|
64
65
|
| peer-node | `PeerNode` |
|
|
66
|
+
| peer-node-transport | `createPeerNodeTransport` |
|
|
65
67
|
| peer-payments | `CreditLedger`, `WebLNProvider` |
|
|
66
68
|
| peer-registry | `PeerRegistry` |
|
|
67
69
|
| peer-routing | `MeshRouter`, `ServerSharing` |
|
|
@@ -420,6 +422,76 @@ it (harmless -- those envelopes are just plain objects with a `.type` field
|
|
|
420
422
|
tenant code can filter on itself if it cares, but worth knowing rather than
|
|
421
423
|
assuming the view is pre-filtered).
|
|
422
424
|
|
|
425
|
+
## Sending to peers: wire format, the bulk lane and `broadcast()`
|
|
426
|
+
|
|
427
|
+
**What goes on the wire.** A real transport (`RTCDataChannel`, `WebSocket`)
|
|
428
|
+
carries only strings and binary. `PeerNode.sendTo(pubKey, envelopeObject)` and
|
|
429
|
+
`ctx.sendTo()` hand the transport an object; the transports in
|
|
430
|
+
`@johnhenry/browsermesh-transport` encode it as JSON text (strings and binary
|
|
431
|
+
go out unchanged -- see `encodeWireData()` there), and a service receives it
|
|
432
|
+
back as the parsed object through `ctx.onIncomingData()`. That parse accepts
|
|
433
|
+
either form, so it works for transports that deliver text and for in-process
|
|
434
|
+
nodes that pass objects. `PeerNode.onIncomingData()` is the raw bus: it hands
|
|
435
|
+
subscribers exactly what the transport delivered, so a direct subscriber that
|
|
436
|
+
wants objects should parse JSON-object text itself. If you write your own
|
|
437
|
+
transport, make `send()` follow the same rule -- forwarding an object to
|
|
438
|
+
`RTCDataChannel.send()` turns it into the text `"[object Object]"` with no
|
|
439
|
+
error.
|
|
440
|
+
|
|
441
|
+
**The bulk lane.** The WebRTC transport opens a second, unordered `mesh-bulk`
|
|
442
|
+
data channel so a large payload does not sit in front of control traffic.
|
|
443
|
+
Select it per send:
|
|
444
|
+
|
|
445
|
+
```js
|
|
446
|
+
await peerNode.sendTo(pubKey, envelope, { channel: 'bulk' }) // PeerNode
|
|
447
|
+
await ctx.sendTo(pubKey, 'chunk-response', payload, { channel: 'bulk' }) // MeshService ctx
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
`channel` is `'control'` (the default; the transport is then called exactly as
|
|
451
|
+
before) or `'bulk'`; anything else throws a `TypeError`. It reaches the
|
|
452
|
+
transport as `send(data, { channel })`. A transport with no bulk lane ignores
|
|
453
|
+
the option, and the WebRTC transport falls back to its control channel when the
|
|
454
|
+
bulk channel is not open, so the same code works against an older peer. The
|
|
455
|
+
chunk-carrying services -- chunk replication (`chunk-push`,
|
|
456
|
+
`chunk-fetch-response`) and the torrent service (`chunk-response`) -- already
|
|
457
|
+
send on the bulk lane; requests and acknowledgements stay on control. Use it in
|
|
458
|
+
your own service for any payload that is large or arrives in a burst.
|
|
459
|
+
|
|
460
|
+
**Sending to everyone.** `PeerNode.broadcast(data, { channel, exclude, concurrency })`
|
|
461
|
+
sends to every connected peer -- one send per peer, at most `concurrency` (default
|
|
462
|
+
8) in flight. A peer whose send fails does not stop the others: errors are
|
|
463
|
+
collected, never thrown.
|
|
464
|
+
|
|
465
|
+
```js
|
|
466
|
+
const { sent, failed } = await peerNode.broadcast({ type: 'hello' }, { exclude: [somePubKey] })
|
|
467
|
+
// sent: ['pk1', 'pk2'], failed: [{ pubKey: 'pk3', error: 'Data channel not open' }]
|
|
468
|
+
peerNode.on('broadcast', ({ sent, failed }) => { /* fires after each fan-out */ })
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
`exclude` is an array, a `Set` or a `(pubKey) => boolean` predicate.
|
|
472
|
+
|
|
473
|
+
**Wiring payments, consensus, migration and group keys.** `PaymentRouter`,
|
|
474
|
+
`ConsensusManager`, `MigrationEngine` (`@johnhenry/browsermesh-sync`) and
|
|
475
|
+
`GroupKeyManager` (`@johnhenry/browsermesh-core`) each take a host-supplied
|
|
476
|
+
`wireTransport(broadcastFn, subscribeFn)`. `createPeerNodeTransport(peerNode)`
|
|
477
|
+
builds that pair from a `PeerNode`:
|
|
478
|
+
|
|
479
|
+
```js
|
|
480
|
+
import { createPeerNodeTransport } from '@johnhenry/browsermesh-apps'
|
|
481
|
+
|
|
482
|
+
const { broadcastFn, subscribeFn } = createPeerNodeTransport(peerNode)
|
|
483
|
+
paymentRouter.wireTransport(broadcastFn, subscribeFn)
|
|
484
|
+
consensus.wireTransport(broadcastFn, subscribeFn)
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
Messages travel as `{ type: <wire type>, payload, from }`. The `fromPodId` a
|
|
488
|
+
handler receives is the peer the message actually arrived from, not the
|
|
489
|
+
envelope's own `from` field, which a remote peer could set to anything.
|
|
490
|
+
`broadcastFn` never rejects, so it is safe to call fire-and-forget.
|
|
491
|
+
|
|
492
|
+
`test/real-peer/wire-envelope.test.mjs` runs all three over a real
|
|
493
|
+
`RTCPeerConnection` pair (`npm run test:real-peer`).
|
|
494
|
+
|
|
423
495
|
## `fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`
|
|
424
496
|
|
|
425
497
|
Two web-standard-API-shaped wrappers over a mesh connection, so existing
|
package/package.json
CHANGED
|
@@ -467,7 +467,7 @@ export function createChunkReplicationService({
|
|
|
467
467
|
return
|
|
468
468
|
}
|
|
469
469
|
|
|
470
|
-
await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'chunk-fetch-response', requestId: msg.requestId, cid: msg.cid, data: toBase64(bytes) }).catch((err) => {
|
|
470
|
+
await ctx.sendTo(fromPubKey, envelopeType, { bucketId, kind: 'chunk-fetch-response', requestId: msg.requestId, cid: msg.cid, data: toBase64(bytes) }, { channel: 'bulk' }).catch((err) => {
|
|
471
471
|
log('chunk-replication:fetch-response-send-failed', { bucketId, to: fromPubKey, cid: msg.cid, error: err?.message || String(err) })
|
|
472
472
|
})
|
|
473
473
|
}
|
|
@@ -530,7 +530,7 @@ export function createChunkReplicationService({
|
|
|
530
530
|
const bytes = chunkBytesByCid.get(cid)
|
|
531
531
|
if (!bytes) continue // we don't hold this chunk ourselves -- nothing to push
|
|
532
532
|
sends.push(
|
|
533
|
-
ctx.sendTo(target, envelopeType, { bucketId, kind: 'chunk-push', requestId, cid, data: toBase64(bytes) }).catch((err) => {
|
|
533
|
+
ctx.sendTo(target, envelopeType, { bucketId, kind: 'chunk-push', requestId, cid, data: toBase64(bytes) }, { channel: 'bulk' }).catch((err) => {
|
|
534
534
|
log('chunk-replication:push-send-failed', { bucketId, to: target, cid, error: err?.message || String(err) })
|
|
535
535
|
}),
|
|
536
536
|
)
|
package/src/index.mjs
CHANGED
|
@@ -23,6 +23,7 @@ export * from './peer-files.mjs';
|
|
|
23
23
|
export * from './peer-health.mjs';
|
|
24
24
|
export * from './peer-ipfs.mjs';
|
|
25
25
|
export * from './peer-node.mjs';
|
|
26
|
+
export * from './peer-node-transport.mjs';
|
|
26
27
|
export * from './signaling.mjs';
|
|
27
28
|
export * from './webrtc-negotiator.mjs';
|
|
28
29
|
export * from './mesh-bootstrap.mjs';
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Inbound half of the mesh wire-envelope contract.
|
|
3
|
+
*
|
|
4
|
+
* A real transport (`RTCDataChannel`, `WebSocket`) can only carry strings and
|
|
5
|
+
* binary, so a MeshService envelope (`{ type, ...payload }`) crosses it as
|
|
6
|
+
* JSON text -- see `@johnhenry/browsermesh-transport`'s `encodeWireData()`
|
|
7
|
+
* for the outbound half. Some transports parse that text back before they
|
|
8
|
+
* hand it up (`WebRTCPeerConnection` does); others hand `PeerNode` the raw
|
|
9
|
+
* string. A consumer that wants envelope objects therefore has to accept
|
|
10
|
+
* both, which is what this does.
|
|
11
|
+
*
|
|
12
|
+
* Only strings that look like a JSON object or array are parsed, so a plain
|
|
13
|
+
* text payload that merely happens to be valid JSON (`"42"`, `"true"`) is
|
|
14
|
+
* left exactly as the sender wrote it. A string that looks like JSON but
|
|
15
|
+
* does not parse is returned unchanged rather than thrown on -- one corrupt
|
|
16
|
+
* frame must never take down the shared dispatch loop.
|
|
17
|
+
*
|
|
18
|
+
* Browser-safe: no imports.
|
|
19
|
+
*
|
|
20
|
+
* @param {*} data - Whatever `PeerNode.onIncomingData()` delivered.
|
|
21
|
+
* @returns {*} The parsed object/array when `data` was a JSON object/array
|
|
22
|
+
* string; `data` itself otherwise.
|
|
23
|
+
*/
|
|
24
|
+
export function decodeWireData(data) {
|
|
25
|
+
if (typeof data !== 'string') return data
|
|
26
|
+
const first = data.trimStart()[0]
|
|
27
|
+
if (first !== '{' && first !== '[') return data
|
|
28
|
+
try {
|
|
29
|
+
return JSON.parse(data)
|
|
30
|
+
} catch {
|
|
31
|
+
return data
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -51,6 +51,7 @@
|
|
|
51
51
|
*/
|
|
52
52
|
|
|
53
53
|
import { createLazyRequire } from './internal/lazy-node-require.mjs'
|
|
54
|
+
import { decodeWireData } from './internal/wire-envelope.mjs'
|
|
54
55
|
|
|
55
56
|
/** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
|
|
56
57
|
const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
|
|
@@ -222,6 +223,7 @@ function resolveMeshRelayBackendClass() {
|
|
|
222
223
|
|
|
223
224
|
/** @param {*} data */
|
|
224
225
|
async #handleIncoming(data) {
|
|
226
|
+
data = decodeWireData(data)
|
|
225
227
|
if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
|
|
226
228
|
const { op, connId } = data
|
|
227
229
|
if (!connId || typeof connId !== 'string') return
|
package/src/mesh-relay-host.mjs
CHANGED
|
@@ -44,6 +44,8 @@
|
|
|
44
44
|
*/
|
|
45
45
|
|
|
46
46
|
/** Default `envelope.type` used to route relay payloads on the shared `onIncomingData()` bus. */
|
|
47
|
+
import { decodeWireData } from './internal/wire-envelope.mjs'
|
|
48
|
+
|
|
47
49
|
const DEFAULT_ENVELOPE_TYPE = 'mesh-relay'
|
|
48
50
|
|
|
49
51
|
// ---------------------------------------------------------------------------
|
|
@@ -193,6 +195,7 @@ export class MeshRelayHost {
|
|
|
193
195
|
* @param {*} data
|
|
194
196
|
*/
|
|
195
197
|
async #handleIncoming(fromPubKey, data) {
|
|
198
|
+
data = decodeWireData(data)
|
|
196
199
|
if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
|
|
197
200
|
const { op, connId } = data
|
|
198
201
|
if (!connId || typeof connId !== 'string') return
|
package/src/mesh-service.mjs
CHANGED
|
@@ -27,10 +27,17 @@
|
|
|
27
27
|
* invoking `callback(pubKey, envelope)` only for envelopes whose `.type`
|
|
28
28
|
* matches `types` (a single string or an array of strings). Returns an
|
|
29
29
|
* unsubscribe function, exactly like the underlying `onIncomingData()`.
|
|
30
|
-
*
|
|
30
|
+
* A real transport carries an envelope as JSON text, so a string that
|
|
31
|
+
* is a JSON object/array is parsed before the `type` check -- `callback`
|
|
32
|
+
* always receives the parsed envelope object.
|
|
33
|
+
* - `ctx.sendTo(pubKey, type, payload, { channel })` -- wraps `peerNode.sendTo()`,
|
|
31
34
|
* merging `{ type, ...payload }` into the envelope sent, matching the
|
|
32
35
|
* `{ type: envelopeType, ...payload }` shape both `mesh-sync.mjs` and
|
|
33
|
-
* `mesh-relay-host.mjs` already send.
|
|
36
|
+
* `mesh-relay-host.mjs` already send. The optional fourth argument
|
|
37
|
+
* `{ channel: 'control'|'bulk' }` picks the transport's data channel
|
|
38
|
+
* (default `'control'`); use `'bulk'` for large payloads such as file
|
|
39
|
+
* chunks so they cannot queue in front of control traffic. Transports
|
|
40
|
+
* without a bulk lane ignore it.
|
|
34
41
|
* - `ctx.registry` -- the node's `PeerRegistry`, for `checkAccess()`.
|
|
35
42
|
* - `ctx.peerNode` -- the raw `PeerNode`, for anything not covered above.
|
|
36
43
|
* - `ctx.network` -- the `VirtualNetwork` passed to `attachService()`, if
|
|
@@ -126,6 +133,8 @@
|
|
|
126
133
|
* No browser-only imports at module level.
|
|
127
134
|
*/
|
|
128
135
|
|
|
136
|
+
import { decodeWireData } from './internal/wire-envelope.mjs'
|
|
137
|
+
|
|
129
138
|
/** Default scheme a descriptor's `createBackend` backend is registered under, if `backendScheme` is omitted. */
|
|
130
139
|
const DEFAULT_BACKEND_SCHEME = 'svc'
|
|
131
140
|
|
|
@@ -226,8 +235,12 @@ function createEventBus() {
|
|
|
226
235
|
* @property {(types: string|string[], callback: (pubKey: string, envelope: object) => void) => (() => void)} onIncomingData
|
|
227
236
|
* Envelope-type-filtered subscription. `callback` only fires for envelopes
|
|
228
237
|
* whose `.type` is in `types`. Returns an unsubscribe function.
|
|
229
|
-
* @property {(pubKey: string, type: string, payload?: object) => Promise<void>} sendTo
|
|
238
|
+
* @property {(pubKey: string, type: string, payload?: object, opts?: { channel?: 'control'|'bulk' }) => Promise<void>} sendTo
|
|
230
239
|
* Sends `{ type, ...payload }` to `pubKey` via `peerNode.sendTo()`.
|
|
240
|
+
* `opts.channel` picks the transport's data channel: `'control'` (the
|
|
241
|
+
* default) or `'bulk'` (the second, unordered channel meant for large
|
|
242
|
+
* payloads such as file chunks, so they cannot queue in front of control
|
|
243
|
+
* traffic). A transport with no bulk lane ignores it. See `PeerNode.sendTo()`.
|
|
231
244
|
* @property {(event: string, data?: object) => void} emit
|
|
232
245
|
* Publishes a curated, meaningful state-transition event for anything
|
|
233
246
|
* subscribed via `attachService()`'s returned handle (`handle.on()`/
|
|
@@ -286,7 +299,12 @@ function createServiceContext({ peerNode, network, eventBus }) {
|
|
|
286
299
|
|
|
287
300
|
onIncomingData(types, callback) {
|
|
288
301
|
const typeSet = new Set(Array.isArray(types) ? types : [types])
|
|
289
|
-
return peerNode.onIncomingData((pubKey,
|
|
302
|
+
return peerNode.onIncomingData((pubKey, rawData) => {
|
|
303
|
+
// A real transport (RTCDataChannel, WebSocket) can only carry
|
|
304
|
+
// strings/binary, so an envelope may arrive as its JSON text --
|
|
305
|
+
// parse it before the `type` check. Already-parsed objects (every
|
|
306
|
+
// in-process node, and transports that parse for us) pass through.
|
|
307
|
+
const data = decodeWireData(rawData)
|
|
290
308
|
if (!data || typeof data !== 'object' || !typeSet.has(data.type)) return
|
|
291
309
|
// `peerNode.onIncomingData()`'s own dispatch loop only catches a
|
|
292
310
|
// SYNCHRONOUS throw from this callback. Every real handler in this
|
|
@@ -308,8 +326,12 @@ function createServiceContext({ peerNode, network, eventBus }) {
|
|
|
308
326
|
})
|
|
309
327
|
},
|
|
310
328
|
|
|
311
|
-
async sendTo(pubKey, type, payload = {}) {
|
|
312
|
-
|
|
329
|
+
async sendTo(pubKey, type, payload = {}, { channel } = {}) {
|
|
330
|
+
// `channel` is forwarded only when the caller picked one, so a node
|
|
331
|
+
// (or duck-typed test double) that predates the option sees exactly
|
|
332
|
+
// the two-argument call it always did.
|
|
333
|
+
if (channel === undefined) await peerNode.sendTo(pubKey, { type, ...payload })
|
|
334
|
+
else await peerNode.sendTo(pubKey, { type, ...payload }, { channel })
|
|
313
335
|
},
|
|
314
336
|
|
|
315
337
|
emit(event, data) {
|
package/src/mesh-sync.mjs
CHANGED
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
*/
|
|
27
27
|
|
|
28
28
|
import { MeshSyncEngine, IndexedDBSyncStorage } from '@johnhenry/browsermesh-sync'
|
|
29
|
+
import { decodeWireData } from './internal/wire-envelope.mjs'
|
|
29
30
|
|
|
30
31
|
/** Default `envelope.type` used to route sync payloads on the shared `onIncomingData()` bus. */
|
|
31
32
|
const DEFAULT_ENVELOPE_TYPE = 'mesh-sync'
|
|
@@ -169,6 +170,7 @@ export class MeshSyncBinding {
|
|
|
169
170
|
* @param {*} data
|
|
170
171
|
*/
|
|
171
172
|
#handleIncoming(pubKey, data) {
|
|
173
|
+
data = decodeWireData(data)
|
|
172
174
|
if (!data || typeof data !== 'object' || data.type !== this.#envelopeType) return
|
|
173
175
|
const { docId, docType, payload } = data
|
|
174
176
|
if (!docId || !payload) return
|
package/src/mesh-websocket.mjs
CHANGED
|
@@ -229,6 +229,7 @@
|
|
|
229
229
|
*/
|
|
230
230
|
|
|
231
231
|
import { createLazyRequire } from './internal/lazy-node-require.mjs'
|
|
232
|
+
import { decodeWireData } from './internal/wire-envelope.mjs'
|
|
232
233
|
|
|
233
234
|
/** Default `envelope.type` used to route mesh-websocket payloads on the shared `onIncomingData()` bus. */
|
|
234
235
|
const DEFAULT_ENVELOPE_TYPE = 'mesh-websocket'
|
|
@@ -434,7 +435,8 @@ export class BrowserMeshWebSocket {
|
|
|
434
435
|
// -----------------------------------------------------------------------
|
|
435
436
|
|
|
436
437
|
#subscribe() {
|
|
437
|
-
this.#unsubscribe = this.#peerNode.onIncomingData((fromPubKey,
|
|
438
|
+
this.#unsubscribe = this.#peerNode.onIncomingData((fromPubKey, rawData) => {
|
|
439
|
+
const data = decodeWireData(rawData)
|
|
438
440
|
if (!data || typeof data !== 'object') return
|
|
439
441
|
if (data.type !== this.#envelopeType || data.connectionId !== this.#connectionId) return
|
|
440
442
|
this.#handleEnvelope(fromPubKey, data)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* peer-node-transport.mjs -- the host half of `wireTransport(broadcastFn,
|
|
3
|
+
* subscribeFn)`.
|
|
4
|
+
*
|
|
5
|
+
* `PaymentRouter`, `ConsensusManager` (both in this package),
|
|
6
|
+
* `MigrationEngine` (`@johnhenry/browsermesh-sync`) and `GroupKeyManager`
|
|
7
|
+
* (`@johnhenry/browsermesh-core`) each expose
|
|
8
|
+
* `wireTransport(broadcastFn, subscribeFn)` and leave the host to supply the
|
|
9
|
+
* one-to-all send and the typed subscription. This builds both from a
|
|
10
|
+
* `PeerNode`, so wiring all four is one call each:
|
|
11
|
+
*
|
|
12
|
+
* const { broadcastFn, subscribeFn } = createPeerNodeTransport(peerNode)
|
|
13
|
+
* paymentRouter.wireTransport(broadcastFn, subscribeFn)
|
|
14
|
+
* consensus.wireTransport(broadcastFn, subscribeFn)
|
|
15
|
+
* migration.wireTransport(broadcastFn, subscribeFn)
|
|
16
|
+
* groupKeys.wireTransport(broadcastFn, subscribeFn)
|
|
17
|
+
*
|
|
18
|
+
* Wire shape: `peerNode.broadcast({ type: <wireType>, payload, from })`,
|
|
19
|
+
* where `<wireType>` is the module's numeric message constant
|
|
20
|
+
* (`PAYMENT_OPEN`, `CONSENSUS_VOTE`, ...). `subscribeFn(wireType, handler)`
|
|
21
|
+
* calls `handler(payload, fromPodId)` for matching inbound envelopes.
|
|
22
|
+
* `fromPodId` is the pubKey of the session the message arrived on -- the
|
|
23
|
+
* transport-authenticated sender -- never the envelope's own `from` field,
|
|
24
|
+
* which a remote peer could set to anything.
|
|
25
|
+
*
|
|
26
|
+
* Inbound envelopes are accepted as parsed objects or as JSON text, like
|
|
27
|
+
* `ctx.onIncomingData()`.
|
|
28
|
+
*
|
|
29
|
+
* Browser-safe: no imports beyond a sibling internal helper.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
import { decodeWireData } from './internal/wire-envelope.mjs'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {import('./peer-node.mjs').PeerNode} peerNode
|
|
36
|
+
* @param {object} [opts]
|
|
37
|
+
* @param {string} [opts.podId] - Value for the envelope's informational
|
|
38
|
+
* `from` field. Defaults to `peerNode.podId`.
|
|
39
|
+
* @param {'control'|'bulk'} [opts.channel] - Data channel for outbound
|
|
40
|
+
* broadcasts. Defaults to the control lane.
|
|
41
|
+
* @param {(event: string, data: object) => void} [opts.onLog]
|
|
42
|
+
* @returns {{
|
|
43
|
+
* broadcastFn: (wireType: number, payload: object) => Promise<{sent: string[], failed: {pubKey: string, error: string}[]}>,
|
|
44
|
+
* subscribeFn: (wireType: number, handler: (payload: object, fromPodId: string) => void) => (() => void),
|
|
45
|
+
* dispose: () => void,
|
|
46
|
+
* }}
|
|
47
|
+
* `broadcastFn` never rejects (a stopped node or a dead peer is reported
|
|
48
|
+
* through `onLog`, not thrown at a fire-and-forget caller). `subscribeFn`
|
|
49
|
+
* returns an unsubscribe function; `dispose()` drops every subscription.
|
|
50
|
+
*/
|
|
51
|
+
export function createPeerNodeTransport(peerNode, { podId, channel, onLog } = {}) {
|
|
52
|
+
if (!peerNode || typeof peerNode.broadcast !== 'function' || typeof peerNode.onIncomingData !== 'function') {
|
|
53
|
+
throw new Error('createPeerNodeTransport: peerNode with broadcast() and onIncomingData() is required')
|
|
54
|
+
}
|
|
55
|
+
const log = typeof onLog === 'function' ? onLog : () => {}
|
|
56
|
+
|
|
57
|
+
/** @type {Map<*, Set<Function>>} */
|
|
58
|
+
const handlers = new Map()
|
|
59
|
+
let unsubscribeIncoming = null
|
|
60
|
+
|
|
61
|
+
function ensureListening() {
|
|
62
|
+
if (unsubscribeIncoming) return
|
|
63
|
+
unsubscribeIncoming = peerNode.onIncomingData((fromPubKey, rawData) => {
|
|
64
|
+
const env = decodeWireData(rawData)
|
|
65
|
+
if (!env || typeof env !== 'object' || !('payload' in env)) return
|
|
66
|
+
const set = handlers.get(env.type)
|
|
67
|
+
if (!set) return
|
|
68
|
+
for (const handler of [...set]) {
|
|
69
|
+
try {
|
|
70
|
+
const result = handler(env.payload, fromPubKey)
|
|
71
|
+
if (result && typeof result.catch === 'function') {
|
|
72
|
+
result.catch((err) => log('peer-node-transport:handler-error', { type: env.type, error: err?.message || String(err) }))
|
|
73
|
+
}
|
|
74
|
+
} catch (err) {
|
|
75
|
+
log('peer-node-transport:handler-error', { type: env.type, error: err?.message || String(err) })
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function broadcastFn(wireType, payload) {
|
|
82
|
+
const localPodId = podId ?? peerNode.podId
|
|
83
|
+
return peerNode
|
|
84
|
+
.broadcast({ type: wireType, payload, from: localPodId }, channel === undefined ? undefined : { channel })
|
|
85
|
+
.then((result) => {
|
|
86
|
+
for (const f of result.failed) log('peer-node-transport:broadcast-send-failed', { type: wireType, to: f.pubKey, error: f.error })
|
|
87
|
+
return result
|
|
88
|
+
})
|
|
89
|
+
.catch((err) => {
|
|
90
|
+
log('peer-node-transport:broadcast-failed', { type: wireType, error: err?.message || String(err) })
|
|
91
|
+
return { sent: [], failed: [] }
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function subscribeFn(wireType, handler) {
|
|
96
|
+
if (typeof handler !== 'function') return () => {}
|
|
97
|
+
let set = handlers.get(wireType)
|
|
98
|
+
if (!set) {
|
|
99
|
+
set = new Set()
|
|
100
|
+
handlers.set(wireType, set)
|
|
101
|
+
}
|
|
102
|
+
set.add(handler)
|
|
103
|
+
ensureListening()
|
|
104
|
+
return () => { set.delete(handler) }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function dispose() {
|
|
108
|
+
handlers.clear()
|
|
109
|
+
if (unsubscribeIncoming) unsubscribeIncoming()
|
|
110
|
+
unsubscribeIncoming = null
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return { broadcastFn, subscribeFn, dispose }
|
|
114
|
+
}
|
package/src/peer-node.mjs
CHANGED
|
@@ -553,6 +553,14 @@ export class PeerNode {
|
|
|
553
553
|
* @param {object} [opts]
|
|
554
554
|
* @param {string} [opts.connectionId] - Target this specific connection's
|
|
555
555
|
* session (issue #116) rather than "most recently created".
|
|
556
|
+
* @param {'control'|'bulk'} [opts.channel] - Which of the transport's data
|
|
557
|
+
* channels to send on. Omit (or pass `'control'`) for the ordered control
|
|
558
|
+
* lane; `'bulk'` selects the second, unordered `mesh-bulk` channel, so
|
|
559
|
+
* large payloads (file/torrent chunks) cannot queue in front of control
|
|
560
|
+
* traffic. Passed through as `transport.send(data, { channel })` only
|
|
561
|
+
* when given; a transport with no bulk lane ignores it (the WebRTC
|
|
562
|
+
* transport falls back to its control channel when the bulk channel is
|
|
563
|
+
* not open). Any other value throws a `TypeError`.
|
|
556
564
|
* @returns {Promise<void>} Resolves when the underlying transport
|
|
557
565
|
* has accepted the send (transport-defined; some are fire-and-
|
|
558
566
|
* forget, others await an ack).
|
|
@@ -560,8 +568,11 @@ export class PeerNode {
|
|
|
560
568
|
* @example
|
|
561
569
|
* await peerNode.sendTo('podid_abc', JSON.stringify({ type: 'ping' }));
|
|
562
570
|
*/
|
|
563
|
-
async sendTo(pubKey, data, { connectionId } = {}) {
|
|
571
|
+
async sendTo(pubKey, data, { connectionId, channel } = {}) {
|
|
564
572
|
this.#ensureRunning('sendTo');
|
|
573
|
+
if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
|
|
574
|
+
throw new TypeError(`PeerNode.sendTo: unknown channel ${JSON.stringify(channel)} (expected 'control' or 'bulk')`);
|
|
575
|
+
}
|
|
565
576
|
let session = null;
|
|
566
577
|
for (const [, s] of this.#sessions) {
|
|
567
578
|
if (s.pubKey !== pubKey || s.state !== 'active') continue;
|
|
@@ -575,7 +586,86 @@ export class PeerNode {
|
|
|
575
586
|
if (!session.transportInstance || typeof session.transportInstance.send !== 'function') {
|
|
576
587
|
throw new Error(`PeerNode.sendTo: session for ${pubKey} has no transport.send`);
|
|
577
588
|
}
|
|
578
|
-
return
|
|
589
|
+
return channel === undefined
|
|
590
|
+
? session.transportInstance.send(data)
|
|
591
|
+
: session.transportInstance.send(data, { channel });
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Send `data` to every connected peer (one active session per peer, the
|
|
596
|
+
* most recently created one -- the same session `sendTo(pubKey, data)`
|
|
597
|
+
* would pick), fanning out through `sendTo()` so each send gets the same
|
|
598
|
+
* session selection, `channel` handling and error behaviour as a direct
|
|
599
|
+
* one.
|
|
600
|
+
*
|
|
601
|
+
* Errors are collected, never thrown: one dead peer must not stop the
|
|
602
|
+
* message reaching the others. A peer whose send throws or rejects is
|
|
603
|
+
* reported in `failed` and the rest carry on.
|
|
604
|
+
*
|
|
605
|
+
* Emits a `'broadcast'` event (payload: the result object) after the
|
|
606
|
+
* fan-out settles.
|
|
607
|
+
*
|
|
608
|
+
* @param {*} data - Wire payload, exactly as for `sendTo()`.
|
|
609
|
+
* @param {object} [opts]
|
|
610
|
+
* @param {'control'|'bulk'} [opts.channel] - As for `sendTo()`.
|
|
611
|
+
* @param {string[]|Set<string>|((pubKey: string) => boolean)} [opts.exclude]
|
|
612
|
+
* Peers to skip: a list/Set of pubKeys, or a predicate returning true to
|
|
613
|
+
* skip. (A node never has a session with itself, so there is no need to
|
|
614
|
+
* exclude yourself.)
|
|
615
|
+
* @param {number} [opts.concurrency=8] - Max sends in flight at once.
|
|
616
|
+
* `1` sends strictly one after another.
|
|
617
|
+
* @returns {Promise<{ sent: string[], failed: { pubKey: string, error: string }[] }>}
|
|
618
|
+
* `sent` lists the pubKeys whose send resolved, `failed` those whose send
|
|
619
|
+
* threw or rejected. Both are in session order. With no connected peers
|
|
620
|
+
* both are empty (not an error).
|
|
621
|
+
*
|
|
622
|
+
* @example
|
|
623
|
+
* const { sent, failed } = await peerNode.broadcast({ type: 'hello' })
|
|
624
|
+
*/
|
|
625
|
+
async broadcast(data, { channel, exclude, concurrency = 8 } = {}) {
|
|
626
|
+
this.#ensureRunning('broadcast');
|
|
627
|
+
if (channel !== undefined && channel !== 'control' && channel !== 'bulk') {
|
|
628
|
+
throw new TypeError(`PeerNode.broadcast: unknown channel ${JSON.stringify(channel)} (expected 'control' or 'bulk')`);
|
|
629
|
+
}
|
|
630
|
+
const skip = typeof exclude === 'function'
|
|
631
|
+
? exclude
|
|
632
|
+
: (() => { const set = new Set(exclude || []); return (pk) => set.has(pk); })();
|
|
633
|
+
|
|
634
|
+
// One target per peer, in first-session order, however many sessions it has.
|
|
635
|
+
const targets = [];
|
|
636
|
+
const seen = new Set();
|
|
637
|
+
for (const s of this.#sessions.values()) {
|
|
638
|
+
if (s.state !== 'active' || seen.has(s.pubKey)) continue;
|
|
639
|
+
if (!s.transportInstance || typeof s.transportInstance.send !== 'function') continue;
|
|
640
|
+
seen.add(s.pubKey);
|
|
641
|
+
if (skip(s.pubKey)) continue;
|
|
642
|
+
targets.push(s.pubKey);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
const outcome = new Map();
|
|
646
|
+
const limit = Math.max(1, Math.floor(Number(concurrency)) || 1);
|
|
647
|
+
let next = 0;
|
|
648
|
+
const worker = async () => {
|
|
649
|
+
while (next < targets.length) {
|
|
650
|
+
const pubKey = targets[next++];
|
|
651
|
+
try {
|
|
652
|
+
await this.sendTo(pubKey, data, channel === undefined ? undefined : { channel });
|
|
653
|
+
outcome.set(pubKey, null);
|
|
654
|
+
} catch (err) {
|
|
655
|
+
outcome.set(pubKey, err?.message || String(err));
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
await Promise.all(Array.from({ length: Math.min(limit, targets.length) }, worker));
|
|
660
|
+
|
|
661
|
+
const result = { sent: [], failed: [] };
|
|
662
|
+
for (const pubKey of targets) {
|
|
663
|
+
const error = outcome.get(pubKey);
|
|
664
|
+
if (error === null) result.sent.push(pubKey);
|
|
665
|
+
else result.failed.push({ pubKey, error });
|
|
666
|
+
}
|
|
667
|
+
this.#emit('broadcast', result);
|
|
668
|
+
return result;
|
|
579
669
|
}
|
|
580
670
|
|
|
581
671
|
/**
|
|
@@ -771,6 +861,8 @@ export class PeerNode {
|
|
|
771
861
|
* those that don't. See issue #110.
|
|
772
862
|
* - 'peer:transport-error' — same, for onError(). Payload:
|
|
773
863
|
* `{pubKey, sessionId, transport, error}`.
|
|
864
|
+
* - 'broadcast' — fired after a `broadcast()` fan-out settles.
|
|
865
|
+
* Payload: `{sent, failed}` (see `broadcast()`).
|
|
774
866
|
* - 'boot' — fired after successful boot
|
|
775
867
|
* - 'shutdown' — fired after shutdown
|
|
776
868
|
*
|