@johnhenry/browsermesh-apps 0.9.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 +124 -1
- package/package.json +1 -1
- package/src/chunk-replication.mjs +2 -2
- package/src/index.mjs +1 -0
- package/src/internal/torrent-store.mjs +141 -0
- package/src/internal/wire-envelope.mjs +33 -0
- package/src/mesh-bootstrap.mjs +10 -1
- 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-torrent.mjs +476 -166
- package/src/mesh-websocket.mjs +3 -1
- package/src/peer-ipfs.mjs +51 -112
- package/src/peer-node-transport.mjs +114 -0
- package/src/peer-node.mjs +94 -2
- package/src/peer-torrent.mjs +145 -13
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)
|
package/src/peer-ipfs.mjs
CHANGED
|
@@ -10,44 +10,29 @@
|
|
|
10
10
|
* the `MeshService` wrapper.
|
|
11
11
|
*
|
|
12
12
|
* ---------------------------------------------------------------------------
|
|
13
|
-
*
|
|
14
|
-
* name, or the word "IPFS" in this file's own history, implies real public
|
|
15
|
-
* IPFS-network interop):
|
|
13
|
+
* WHAT THIS CLASS IS (and is not):
|
|
16
14
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
* without Helia" test, the only Helia-adjacent behavior anyone has
|
|
27
|
-
* actually verified here.
|
|
28
|
-
* 2. Even setting (1) aside and assuming a real Helia node did load
|
|
29
|
-
* successfully: `add()`, `get()`, `pin()`, `unpin()`, `remove()`,
|
|
30
|
-
* `listCids()`, and `getStats()` below NEVER touch `this.#helia`. Read
|
|
31
|
-
* them -- every one reads/writes `this.#storedCids`, the same in-memory
|
|
32
|
-
* `Map`, unconditionally. The only place `#helia` is referenced again
|
|
33
|
-
* after being set is `close()`, which calls `.stop()` on it. So even a
|
|
34
|
-
* successfully-loaded Helia node is constructed and then never used for
|
|
35
|
-
* a single actual storage operation -- there is no code path in this
|
|
36
|
-
* class, today, that stores or retrieves a byte via Helia/IPFS.
|
|
37
|
-
* 3. The "CID" this class produces is a raw SHA-256 hex digest
|
|
38
|
-
* (`ChunkStore.computeCid()`), NOT a real IPFS CID (a multihash +
|
|
39
|
-
* multibase-encoded identifier, e.g. a `Qm...`/`bafy...` string) -- it's
|
|
40
|
-
* exactly the same format `ChunkStore`/`CloudStorage` already use
|
|
41
|
-
* elsewhere in this repo, not an IPFS-native one.
|
|
15
|
+
* `IPFSStore` is a MESH-LOCAL CONTENT-ADDRESSED STORE. The "CID" it produces
|
|
16
|
+
* is a raw SHA-256 hex digest (`ChunkStore.computeCid()`), the same format
|
|
17
|
+
* `ChunkStore`/`CloudStorage` use elsewhere in this repo. It is NOT an IPFS
|
|
18
|
+
* CID (no multihash/multibase, no `Qm...`/`bafy...`), and nothing here speaks
|
|
19
|
+
* to the public IPFS network: there is no Helia, libp2p, or bitswap code in
|
|
20
|
+
* this package, and `helia`/`@helia/*` is not a dependency of any package in
|
|
21
|
+
* this monorepo. The `IPFSStore` name and the `ipfs_store`/`ipfs_retrieve`
|
|
22
|
+
* agent tools predate this clarification and are kept for compatibility;
|
|
23
|
+
* `MeshLocalCidStore` is exported as an alias that says what the class is.
|
|
42
24
|
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
* `
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
25
|
+
* Earlier revisions carried a hook in `ensureLoaded()` that tried to
|
|
26
|
+
* `import()` a Helia bundle from a CDN when `{ enabled: true }`. It could
|
|
27
|
+
* never activate (the bundle is an IIFE so `globalThis.Helia` was never set,
|
|
28
|
+
* the namespace exports `createHelia` rather than `create`, and the
|
|
29
|
+
* `typeof === 'function'` guard failed for a namespace), and even a loaded
|
|
30
|
+
* node was never used by `add()`/`get()`/`pin()`. It was removed (#197); a
|
|
31
|
+
* library should not fetch a 900 KB third-party bundle on its host's behalf.
|
|
32
|
+
* `enabled` is therefore accepted and reported but has no effect, and
|
|
33
|
+
* `available` is always `false`; both remain so existing callers keep
|
|
34
|
+
* working. A consumer who wants real IPFS should run their own Helia and
|
|
35
|
+
* keep it separate from this class.
|
|
51
36
|
*
|
|
52
37
|
* WHAT THIS ACTUALLY OFFERS OVER `CloudStorage` (`cloud-storage.mjs`), given
|
|
53
38
|
* the above: `CloudStorage` is encrypted, `PeerRegistry`-gated, and
|
|
@@ -59,11 +44,9 @@
|
|
|
59
44
|
* `IPFSStore` (there is no wire protocol here at all; each `IPFSStore`
|
|
60
45
|
* instance is a private, local cache, and `createIpfsService()` below does
|
|
61
46
|
* not add one -- see its own "NO WIRE PROTOCOL" note). Its genuinely
|
|
62
|
-
* distinct value
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
* require someone to actually add `helia` as a dependency and rewire the
|
|
66
|
-
* storage operations to call through to it, neither of which has happened.
|
|
47
|
+
* distinct value is a lightweight, dependency-light local scratch cache
|
|
48
|
+
* with pin/unpin/storage-cap bookkeeping and an `ensureLoaded()`/`close()`
|
|
49
|
+
* lifecycle -- not an IPFS-network-interop story.
|
|
67
50
|
*
|
|
68
51
|
* ---------------------------------------------------------------------------
|
|
69
52
|
* No browser-only imports at module level.
|
|
@@ -88,25 +71,15 @@ export const IPFS_DEFAULTS = Object.freeze({
|
|
|
88
71
|
// ---------------------------------------------------------------------------
|
|
89
72
|
|
|
90
73
|
/**
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
* `add`/`get`/`pin`/`unpin`/`remove`/`listCids`/`getStats` always read and
|
|
96
|
-
* write the in-memory `#storedCids` map, keyed by SHA-256 CID (same format
|
|
97
|
-
* used by `ChunkStore` in `browsermesh-sync`), regardless of whether
|
|
98
|
-
* `ensureLoaded()` happened to load a Helia instance.
|
|
74
|
+
* Mesh-local content-addressed store. CIDs are SHA-256 hex digests (the
|
|
75
|
+
* `ChunkStore` format), not IPFS CIDs, and nothing here talks to the public
|
|
76
|
+
* IPFS network -- see the module doc comment. Also exported as
|
|
77
|
+
* `MeshLocalCidStore`.
|
|
99
78
|
*/
|
|
100
79
|
export class IPFSStore {
|
|
101
|
-
/** @type {object|null} Helia node instance (lazy-loaded) */
|
|
102
|
-
#helia = null
|
|
103
|
-
|
|
104
80
|
/** @type {boolean} */
|
|
105
81
|
#loaded = false
|
|
106
82
|
|
|
107
|
-
/** @type {boolean} */
|
|
108
|
-
#heliaAvailable = false
|
|
109
|
-
|
|
110
83
|
/** @type {boolean} */
|
|
111
84
|
#enabled
|
|
112
85
|
|
|
@@ -124,7 +97,9 @@ export class IPFSStore {
|
|
|
124
97
|
|
|
125
98
|
/**
|
|
126
99
|
* @param {object} [opts]
|
|
127
|
-
* @param {boolean} [opts.enabled=false] -
|
|
100
|
+
* @param {boolean} [opts.enabled=false] - Accepted and reported by
|
|
101
|
+
* `enabled`/`toJSON()` for compatibility; it has no effect on behaviour
|
|
102
|
+
* (there is no IPFS backend to enable).
|
|
128
103
|
* @param {number} [opts.maxStorageMb=100] - Maximum storage in MB
|
|
129
104
|
* @param {Function} [opts.onLog] - Logging callback
|
|
130
105
|
*/
|
|
@@ -134,43 +109,14 @@ export class IPFSStore {
|
|
|
134
109
|
this.#onLog = opts.onLog || (() => {})
|
|
135
110
|
}
|
|
136
111
|
|
|
137
|
-
// ──
|
|
112
|
+
// ── Lifecycle ────────────────────────────────────────────────────────
|
|
138
113
|
|
|
139
114
|
/**
|
|
140
|
-
*
|
|
141
|
-
*
|
|
115
|
+
* Mark the store as loaded. Kept for lifecycle compatibility; there is
|
|
116
|
+
* nothing to load (the CDN Helia hook was removed, see the module doc
|
|
117
|
+
* comment). Idempotent.
|
|
142
118
|
*/
|
|
143
119
|
async ensureLoaded() {
|
|
144
|
-
if (this.#loaded) return
|
|
145
|
-
if (!this.#enabled) {
|
|
146
|
-
this.#loaded = true
|
|
147
|
-
return
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
try {
|
|
151
|
-
if (typeof globalThis.Helia === 'function') {
|
|
152
|
-
this.#helia = await globalThis.Helia.create()
|
|
153
|
-
this.#heliaAvailable = true
|
|
154
|
-
this.#onLog(2, 'Helia node initialized from globalThis')
|
|
155
|
-
} else {
|
|
156
|
-
try {
|
|
157
|
-
// CDN URL verified current 2026-05-03 against npm registry latest (helia@6.1.4).
|
|
158
|
-
await import('https://cdn.jsdelivr.net/npm/helia@6.1.4/dist/index.min.js')
|
|
159
|
-
if (typeof globalThis.Helia === 'function') {
|
|
160
|
-
this.#helia = await globalThis.Helia.create()
|
|
161
|
-
this.#heliaAvailable = true
|
|
162
|
-
this.#onLog(2, 'Helia loaded from CDN')
|
|
163
|
-
}
|
|
164
|
-
} catch {
|
|
165
|
-
this.#heliaAvailable = false
|
|
166
|
-
this.#onLog(1, 'Helia CDN load failed -- using memory-backed CID store')
|
|
167
|
-
}
|
|
168
|
-
}
|
|
169
|
-
} catch (err) {
|
|
170
|
-
this.#heliaAvailable = false
|
|
171
|
-
this.#onLog(1, `Helia initialization failed: ${err.message}`)
|
|
172
|
-
}
|
|
173
|
-
|
|
174
120
|
this.#loaded = true
|
|
175
121
|
}
|
|
176
122
|
|
|
@@ -181,12 +127,16 @@ export class IPFSStore {
|
|
|
181
127
|
return this.#loaded
|
|
182
128
|
}
|
|
183
129
|
|
|
184
|
-
/**
|
|
130
|
+
/**
|
|
131
|
+
* Always `false`: there is no IPFS/Helia backend. Retained so callers that
|
|
132
|
+
* checked it keep working.
|
|
133
|
+
* @deprecated
|
|
134
|
+
*/
|
|
185
135
|
get available() {
|
|
186
|
-
return
|
|
136
|
+
return false
|
|
187
137
|
}
|
|
188
138
|
|
|
189
|
-
/**
|
|
139
|
+
/** The `enabled` option as passed in (informational only; see constructor). */
|
|
190
140
|
get enabled() {
|
|
191
141
|
return this.#enabled
|
|
192
142
|
}
|
|
@@ -402,23 +352,12 @@ export class IPFSStore {
|
|
|
402
352
|
// ── Lifecycle ────────────────────────────────────────────────────────
|
|
403
353
|
|
|
404
354
|
/**
|
|
405
|
-
* Close the
|
|
355
|
+
* Close the store. Clears all stored data and listeners.
|
|
406
356
|
*/
|
|
407
357
|
async close() {
|
|
408
358
|
this.#storedCids.clear()
|
|
409
359
|
this.#listeners.clear()
|
|
410
|
-
|
|
411
|
-
if (this.#helia) {
|
|
412
|
-
try {
|
|
413
|
-
await this.#helia.stop()
|
|
414
|
-
} catch {
|
|
415
|
-
// best effort
|
|
416
|
-
}
|
|
417
|
-
this.#helia = null
|
|
418
|
-
}
|
|
419
|
-
|
|
420
360
|
this.#loaded = false
|
|
421
|
-
this.#heliaAvailable = false
|
|
422
361
|
}
|
|
423
362
|
|
|
424
363
|
// ── Serialization ────────────────────────────────────────────────────
|
|
@@ -431,7 +370,7 @@ export class IPFSStore {
|
|
|
431
370
|
return {
|
|
432
371
|
enabled: this.#enabled,
|
|
433
372
|
loaded: this.#loaded,
|
|
434
|
-
available:
|
|
373
|
+
available: false,
|
|
435
374
|
maxStorageMb: this.#maxStorageMb,
|
|
436
375
|
stats: this.getStats(),
|
|
437
376
|
cids: this.listCids().map(c => ({ cid: c.cid, size: c.size, pinned: c.pinned })),
|
|
@@ -439,6 +378,9 @@ export class IPFSStore {
|
|
|
439
378
|
}
|
|
440
379
|
}
|
|
441
380
|
|
|
381
|
+
/** Accurate name for `IPFSStore`: a mesh-local content-addressed store. */
|
|
382
|
+
export { IPFSStore as MeshLocalCidStore }
|
|
383
|
+
|
|
442
384
|
// ---------------------------------------------------------------------------
|
|
443
385
|
// createIpfsService -- MeshService wiring (Phase 6 consumer, issue #123)
|
|
444
386
|
// ---------------------------------------------------------------------------
|
|
@@ -458,8 +400,7 @@ export class IPFSStore {
|
|
|
458
400
|
* network in the first place -- every one of its methods
|
|
459
401
|
* (`add`/`get`/`pin`/`unpin`/`remove`/`listCids`/`getStats`) is a purely
|
|
460
402
|
* local operation on its own in-memory `#storedCids` map (see this file's
|
|
461
|
-
* "
|
|
462
|
-
* why that's true even when Helia loads). Attaching this service to two
|
|
403
|
+
* "WHAT THIS CLASS IS" header comment). Attaching this service to two
|
|
463
404
|
* different `PeerNode`s therefore produces two entirely independent stores:
|
|
464
405
|
* content `add()`ed through peer A's `api.add()` is never visible via peer
|
|
465
406
|
* B's `api.get()`, with no `ctx.sendTo()` call anywhere in this file able to
|
|
@@ -489,7 +430,7 @@ export class IPFSStore {
|
|
|
489
430
|
* listening to.
|
|
490
431
|
*
|
|
491
432
|
* `teardown()` calls `store.close()` -- clearing all locally-stored content
|
|
492
|
-
*
|
|
433
|
+
* -- since the
|
|
493
434
|
* store is entirely owned by this `attach()` call (a fresh `IPFSStore` is
|
|
494
435
|
* constructed every time `createIpfsService()`'s descriptor is attached; see
|
|
495
436
|
* `mesh-service.mjs`'s own "teardown() only reverses what attach() itself
|
|
@@ -501,10 +442,8 @@ export class IPFSStore {
|
|
|
501
442
|
/**
|
|
502
443
|
* @param {object} [opts]
|
|
503
444
|
* @param {boolean} [opts.enabled] - Forwarded to `new IPFSStore()` (default
|
|
504
|
-
* `false` -- see `IPFS_DEFAULTS`).
|
|
505
|
-
*
|
|
506
|
-
* `ensureLoaded()` attempts (and, per the module doc comment, still never
|
|
507
|
-
* actually uses) a CDN-loaded Helia instance.
|
|
445
|
+
* `false` -- see `IPFS_DEFAULTS`). Informational only: it does not enable
|
|
446
|
+
* any IPFS behaviour (see the module doc comment).
|
|
508
447
|
* @param {number} [opts.maxStorageMb] - Forwarded to `new IPFSStore()`
|
|
509
448
|
* (default 100).
|
|
510
449
|
* @param {Function} [opts.onLog] - `(event: string, data: object) => void`,
|
|
@@ -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
|
*
|