@johnhenry/browsermesh-apps 0.1.1 → 0.3.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 +443 -1
- package/package.json +18 -3
- package/src/agent-runtime.mjs +342 -0
- package/src/chunk-replication.mjs +751 -0
- package/src/cloud-storage-backend.mjs +932 -0
- package/src/cloud-storage.mjs +799 -0
- package/src/compat.mjs +98 -0
- package/src/gpu-kernel.mjs +242 -0
- package/src/gpu.mjs +101 -7
- package/src/grant-log.mjs +840 -0
- package/src/index.mjs +32 -2
- package/src/kernel-mesh.mjs +56 -0
- package/src/key-distribution.mjs +525 -0
- package/src/manifest-sync.mjs +363 -0
- package/src/mesh-agent-swarm.mjs +376 -0
- package/src/mesh-bootstrap.mjs +1481 -0
- package/src/mesh-compute.mjs +397 -0
- package/src/mesh-dht.mjs +182 -0
- package/src/mesh-fetch.mjs +246 -0
- package/src/mesh-hardening.mjs +226 -0
- package/src/mesh-health.mjs +282 -0
- package/src/mesh-keepalive.mjs +353 -0
- package/src/mesh-kv.mjs +673 -0
- package/src/mesh-orchestrator-tools.mjs +251 -0
- package/src/mesh-orchestrator.mjs +343 -0
- package/src/mesh-relay-backend.mjs +289 -0
- package/src/mesh-relay-host.mjs +362 -0
- package/src/mesh-rpc.mjs +300 -0
- package/src/mesh-service.mjs +403 -0
- package/src/mesh-swarm.mjs +677 -0
- package/src/mesh-sync.mjs +253 -0
- package/src/mesh-timestamp.mjs +265 -0
- package/src/mesh-torrent.mjs +683 -0
- package/src/mesh-verification.mjs +367 -0
- package/src/mesh-websocket.mjs +722 -0
- package/src/observability-bridge.mjs +453 -0
- package/src/orchestrator.mjs +18 -5
- package/src/peer-agent-swarm.mjs +12 -1
- package/src/peer-chat.mjs +230 -61
- package/src/peer-compute.mjs +66 -3
- package/src/peer-escrow.mjs +350 -1
- package/src/peer-files.mjs +362 -168
- package/src/peer-ipfs.mjs +205 -10
- package/src/peer-node.mjs +127 -19
- package/src/peer-registry.mjs +242 -18
- package/src/peer-routing.mjs +369 -5
- package/src/peer-terminal.mjs +400 -130
- package/src/signaling.mjs +231 -0
- package/src/webrtc-negotiator.mjs +209 -0
- package/src/peer-session.mjs +0 -937
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* signaling.mjs -- MeshSignalingChannel: WebRTC offer/answer/ICE relay.
|
|
3
|
+
*
|
|
4
|
+
* `webrtc-negotiator.mjs`'s adapter factory needs some way to hand an SDP
|
|
5
|
+
* offer to a remote peer and get an SDP answer (and ICE candidates) back,
|
|
6
|
+
* before the WebRTC connection itself exists to carry that traffic. That
|
|
7
|
+
* bootstrap channel is "signaling", and WebRTC deliberately doesn't specify
|
|
8
|
+
* one -- it's left to the application.
|
|
9
|
+
*
|
|
10
|
+
* Rather than adopting `browsermesh-core`'s `SignalingClient` (needs an
|
|
11
|
+
* external WebSocket signaling server that isn't implemented anywhere in
|
|
12
|
+
* this repo) or `browsermesh-transport/websocket.mjs`'s separate
|
|
13
|
+
* `WebRTCTransport`/`TransportFactory` pair (same requirement, and not the
|
|
14
|
+
* implementation the real `test/real-peer/` suite exercises), this is a
|
|
15
|
+
* small, new, transport-agnostic relay: it wraps whatever bidirectional bus
|
|
16
|
+
* is already in hand and speaks exactly three message shapes over it --
|
|
17
|
+
* `{type: 'webrtc-offer'|'webrtc-answer'|'webrtc-ice', from, to, payload}`.
|
|
18
|
+
*
|
|
19
|
+
* The injected `transport` only needs to implement `send(msg)` and
|
|
20
|
+
* `onMessage(cb)` (optionally `open()`/`close()`) -- the same minimal shape
|
|
21
|
+
* `browsermesh-pod`'s `EventEmitterTransport` already exposes, and the shape
|
|
22
|
+
* `createBroadcastChannelSignalingTransport()` below adapts a real
|
|
23
|
+
* `BroadcastChannel` to. Messages not addressed to this channel's
|
|
24
|
+
* `localPodId` (or echoed from itself) are ignored, so many peers can safely
|
|
25
|
+
* share one broadcast-style bus -- exactly how BroadcastChannel and the
|
|
26
|
+
* existing Pod example's `EventEmitterTransport` bus already work in this
|
|
27
|
+
* repo.
|
|
28
|
+
*
|
|
29
|
+
* No browser-only imports at module level.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/** @type {readonly string[]} */
|
|
33
|
+
const SIGNAL_TYPES = Object.freeze(['webrtc-offer', 'webrtc-answer', 'webrtc-ice'])
|
|
34
|
+
|
|
35
|
+
// ---------------------------------------------------------------------------
|
|
36
|
+
// MeshSignalingChannel
|
|
37
|
+
// ---------------------------------------------------------------------------
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Relays WebRTC offer/answer/ICE-candidate messages between peers over an
|
|
41
|
+
* injectable transport.
|
|
42
|
+
*/
|
|
43
|
+
export class MeshSignalingChannel {
|
|
44
|
+
/** @type {string} */
|
|
45
|
+
#localPodId
|
|
46
|
+
|
|
47
|
+
/** @type {{send: Function, onMessage: Function, open?: Function, close?: Function}} */
|
|
48
|
+
#transport
|
|
49
|
+
|
|
50
|
+
/** @type {Function} */
|
|
51
|
+
#onLog
|
|
52
|
+
|
|
53
|
+
/** @type {Record<string, Set<Function>>} */
|
|
54
|
+
#listeners
|
|
55
|
+
|
|
56
|
+
/** @type {boolean} */
|
|
57
|
+
#opened = false
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* @param {object} opts
|
|
61
|
+
* @param {string} opts.localPodId - This node's pod identifier; messages
|
|
62
|
+
* not addressed to this id (`msg.to !== localPodId`) are ignored.
|
|
63
|
+
* @param {{send: Function, onMessage: Function, open?: Function, close?: Function}} opts.transport
|
|
64
|
+
* Injectable bidirectional bus. Must implement `send(msg)` and
|
|
65
|
+
* `onMessage(cb)`. `open()`/`close()` are called if present.
|
|
66
|
+
* @param {Function} [opts.onLog]
|
|
67
|
+
*/
|
|
68
|
+
constructor({ localPodId, transport, onLog } = {}) {
|
|
69
|
+
if (!localPodId || typeof localPodId !== 'string') {
|
|
70
|
+
throw new Error('localPodId is required and must be a non-empty string')
|
|
71
|
+
}
|
|
72
|
+
if (!transport || typeof transport.send !== 'function') {
|
|
73
|
+
throw new Error('transport is required and must implement send(msg)')
|
|
74
|
+
}
|
|
75
|
+
if (typeof transport.onMessage !== 'function') {
|
|
76
|
+
throw new Error('transport is required and must implement onMessage(cb)')
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
this.#localPodId = localPodId
|
|
80
|
+
this.#transport = transport
|
|
81
|
+
this.#onLog = onLog || (() => {})
|
|
82
|
+
this.#listeners = {
|
|
83
|
+
'webrtc-offer': new Set(),
|
|
84
|
+
'webrtc-answer': new Set(),
|
|
85
|
+
'webrtc-ice': new Set(),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
this.#transport.onMessage((msg) => this.#handleMessage(msg))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** This channel's local pod identifier. */
|
|
92
|
+
get localPodId() {
|
|
93
|
+
return this.#localPodId
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Open the underlying transport (no-op if it has no `open()`).
|
|
98
|
+
* @returns {Promise<void>}
|
|
99
|
+
*/
|
|
100
|
+
async open() {
|
|
101
|
+
if (this.#opened) return
|
|
102
|
+
if (typeof this.#transport.open === 'function') {
|
|
103
|
+
await this.#transport.open()
|
|
104
|
+
}
|
|
105
|
+
this.#opened = true
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Close the underlying transport (no-op if it has no `close()`).
|
|
110
|
+
* @returns {Promise<void>}
|
|
111
|
+
*/
|
|
112
|
+
async close() {
|
|
113
|
+
if (!this.#opened) return
|
|
114
|
+
if (typeof this.#transport.close === 'function') {
|
|
115
|
+
await this.#transport.close()
|
|
116
|
+
}
|
|
117
|
+
this.#opened = false
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Send a signaling message to a specific peer.
|
|
122
|
+
*
|
|
123
|
+
* @param {'webrtc-offer'|'webrtc-answer'|'webrtc-ice'} type
|
|
124
|
+
* @param {string} to - Target pod identifier
|
|
125
|
+
* @param {*} payload - The offer/answer/candidate object
|
|
126
|
+
*/
|
|
127
|
+
send(type, to, payload) {
|
|
128
|
+
if (!SIGNAL_TYPES.includes(type)) {
|
|
129
|
+
throw new Error(`Unknown signal type: ${type}`)
|
|
130
|
+
}
|
|
131
|
+
if (!to || typeof to !== 'string') {
|
|
132
|
+
throw new Error('to is required and must be a non-empty string')
|
|
133
|
+
}
|
|
134
|
+
this.#transport.send({ type, from: this.#localPodId, to, payload })
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Subscribe to incoming offers. Callback receives `(fromPodId, offer)`.
|
|
139
|
+
* @param {(fromPodId: string, offer: object) => void} cb
|
|
140
|
+
* @returns {() => void} Unsubscribe function.
|
|
141
|
+
*/
|
|
142
|
+
onOffer(cb) {
|
|
143
|
+
return this.#on('webrtc-offer', cb)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Subscribe to incoming answers. Callback receives `(fromPodId, answer)`.
|
|
148
|
+
* @param {(fromPodId: string, answer: object) => void} cb
|
|
149
|
+
* @returns {() => void} Unsubscribe function.
|
|
150
|
+
*/
|
|
151
|
+
onAnswer(cb) {
|
|
152
|
+
return this.#on('webrtc-answer', cb)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Subscribe to incoming ICE candidates. Callback receives `(fromPodId, candidate)`.
|
|
157
|
+
* @param {(fromPodId: string, candidate: object) => void} cb
|
|
158
|
+
* @returns {() => void} Unsubscribe function.
|
|
159
|
+
*/
|
|
160
|
+
onIce(cb) {
|
|
161
|
+
return this.#on('webrtc-ice', cb)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// -- Internal -------------------------------------------------------------
|
|
165
|
+
|
|
166
|
+
#on(type, cb) {
|
|
167
|
+
if (typeof cb !== 'function') {
|
|
168
|
+
throw new Error('callback must be a function')
|
|
169
|
+
}
|
|
170
|
+
this.#listeners[type].add(cb)
|
|
171
|
+
return () => this.#listeners[type].delete(cb)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
#handleMessage(msg) {
|
|
175
|
+
if (!msg || typeof msg !== 'object') return
|
|
176
|
+
if (!SIGNAL_TYPES.includes(msg.type)) return
|
|
177
|
+
if (msg.to !== this.#localPodId) return // not addressed to us
|
|
178
|
+
if (msg.from === this.#localPodId) return // ignore our own broadcast echo
|
|
179
|
+
|
|
180
|
+
for (const cb of [...this.#listeners[msg.type]]) {
|
|
181
|
+
try {
|
|
182
|
+
cb(msg.from, msg.payload)
|
|
183
|
+
} catch (err) {
|
|
184
|
+
this.#onLog('signaling:listener-error', {
|
|
185
|
+
type: msg.type,
|
|
186
|
+
error: err?.message || String(err),
|
|
187
|
+
})
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ---------------------------------------------------------------------------
|
|
194
|
+
// BroadcastChannel adapter
|
|
195
|
+
// ---------------------------------------------------------------------------
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Wrap a real `BroadcastChannel` as a `{send, onMessage, close}` transport
|
|
199
|
+
* suitable for `MeshSignalingChannel`. Browser-only (throws if
|
|
200
|
+
* `BroadcastChannel` is not on the global scope) -- for Node, supply a
|
|
201
|
+
* different transport (e.g. an `EventEmitterTransport`-shaped bus) instead.
|
|
202
|
+
*
|
|
203
|
+
* @param {string} [channelName='mesh-signaling']
|
|
204
|
+
* @returns {{send: Function, onMessage: Function, close: Function}}
|
|
205
|
+
*/
|
|
206
|
+
export function createBroadcastChannelSignalingTransport(channelName = 'mesh-signaling') {
|
|
207
|
+
if (typeof BroadcastChannel === 'undefined') {
|
|
208
|
+
throw new Error(
|
|
209
|
+
'createBroadcastChannelSignalingTransport() requires a global BroadcastChannel ' +
|
|
210
|
+
'(browser-only). Supply a Node-safe transport instead.',
|
|
211
|
+
)
|
|
212
|
+
}
|
|
213
|
+
const channel = new BroadcastChannel(channelName)
|
|
214
|
+
let handler = null
|
|
215
|
+
channel.onmessage = (event) => {
|
|
216
|
+
if (handler) handler(event.data)
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
send(msg) {
|
|
220
|
+
channel.postMessage(msg)
|
|
221
|
+
},
|
|
222
|
+
onMessage(cb) {
|
|
223
|
+
handler = cb
|
|
224
|
+
},
|
|
225
|
+
close() {
|
|
226
|
+
channel.close()
|
|
227
|
+
},
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export { SIGNAL_TYPES }
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* webrtc-negotiator.mjs -- wires a WebRTCMeshManager + MeshSignalingChannel
|
|
3
|
+
* into the adapter-factory shape `MeshTransportNegotiator.registerAdapter()`
|
|
4
|
+
* expects.
|
|
5
|
+
*
|
|
6
|
+
* `MeshTransportNegotiator` (browsermesh-transport/src/transport.mjs) tries
|
|
7
|
+
* adapters in preference order and calls the registered factory as
|
|
8
|
+
* `factory(endpoint, auth) => Promise<MeshTransport>`. `PeerNode.connectToPeer()`
|
|
9
|
+
* already calls `negotiator.negotiate(endpoints, auth)` where `endpoints` is
|
|
10
|
+
* a map of transport type -> endpoint string -- for `'webrtc'` there is no
|
|
11
|
+
* URL-shaped endpoint (WebRTC is point-to-point and negotiated out of band),
|
|
12
|
+
* so by convention here `endpoints.webrtc` is simply the remote peer's podId,
|
|
13
|
+
* the identifier `WebRTCMeshManager`/`WebRTCPeerConnection` already key on.
|
|
14
|
+
*
|
|
15
|
+
* This module owns both directions of the offer/answer/ICE dance:
|
|
16
|
+
* - Caller side: `createWebRTCTransportFactory()`'s returned factory
|
|
17
|
+
* creates an offer, sends it over the signaling channel, and resolves
|
|
18
|
+
* once the DataChannel opens.
|
|
19
|
+
* - Callee side: the same call also wires a standing `signaling.onOffer()`
|
|
20
|
+
* listener that auto-answers any inbound offer, so a peer that never
|
|
21
|
+
* calls `negotiate()` itself can still be connected *to*. Once that
|
|
22
|
+
* inbound DataChannel actually opens, the optional `onIncomingConnection`
|
|
23
|
+
* callback hands the caller a ready `WebRTCTransportAdapter` for it --
|
|
24
|
+
* `mesh-bootstrap.mjs` wires this straight into
|
|
25
|
+
* `PeerNode.adoptIncomingSession()` so the callee side ends up with the
|
|
26
|
+
* same `PeerNode`-level session bookkeeping (`sendTo()`,
|
|
27
|
+
* `onIncomingData()`) the caller side already gets from
|
|
28
|
+
* `connectToPeer()`.
|
|
29
|
+
* ICE candidates are relayed in both directions for every connection,
|
|
30
|
+
* regardless of which side initiated it.
|
|
31
|
+
*
|
|
32
|
+
* No browser-only imports at module level.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import { WebRTCTransportAdapter } from '@johnhenry/browsermesh-transport'
|
|
36
|
+
|
|
37
|
+
/** Default time to wait for an SDP answer before giving up. */
|
|
38
|
+
const DEFAULT_ANSWER_TIMEOUT_MS = 15_000
|
|
39
|
+
|
|
40
|
+
/** Default time to wait for the DataChannel to open after an answer lands. */
|
|
41
|
+
const DEFAULT_OPEN_TIMEOUT_MS = 15_000
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Build a `'webrtc'` adapter factory for `MeshTransportNegotiator`, backed by
|
|
45
|
+
* a real `WebRTCMeshManager` and a `MeshSignalingChannel`.
|
|
46
|
+
*
|
|
47
|
+
* @param {object} opts
|
|
48
|
+
* @param {string} opts.localPodId
|
|
49
|
+
* @param {import('@johnhenry/browsermesh-transport').WebRTCMeshManager} opts.meshManager
|
|
50
|
+
* @param {import('./signaling.mjs').MeshSignalingChannel} opts.signaling
|
|
51
|
+
* @param {Function} [opts.onLog]
|
|
52
|
+
* @param {(remotePodId: string, adapter: import('@johnhenry/browsermesh-transport').WebRTCTransportAdapter) => void} [opts.onIncomingConnection]
|
|
53
|
+
* Called once the DataChannel for a *callee-side* (auto-answered) inbound
|
|
54
|
+
* offer actually opens, with a ready `WebRTCTransportAdapter` wrapping it.
|
|
55
|
+
* Optional: without it, inbound-only connections still come up at the
|
|
56
|
+
* `WebRTCMeshManager`/`WebRTCPeerConnection` level, just without the
|
|
57
|
+
* `PeerNode`-level session `mesh-bootstrap.mjs` wires this into.
|
|
58
|
+
* @param {number} [opts.openTimeoutMs] - How long to wait for the callee-side
|
|
59
|
+
* DataChannel to open before giving up on firing `onIncomingConnection`
|
|
60
|
+
* (the offer/answer exchange itself already succeeded either way).
|
|
61
|
+
* @returns {(endpoint: string, auth?: object) => Promise<import('@johnhenry/browsermesh-transport').WebRTCTransportAdapter>}
|
|
62
|
+
* Factory suitable for `negotiator.registerAdapter('webrtc', factory)`.
|
|
63
|
+
* `endpoint` is the remote peer's podId; `auth` may carry
|
|
64
|
+
* `{ answerTimeoutMs, openTimeoutMs }` overrides.
|
|
65
|
+
*/
|
|
66
|
+
export function createWebRTCTransportFactory({
|
|
67
|
+
localPodId, meshManager, signaling, onLog, onIncomingConnection, openTimeoutMs: defaultOpenTimeoutMs,
|
|
68
|
+
}) {
|
|
69
|
+
if (!localPodId) throw new Error('localPodId is required')
|
|
70
|
+
if (!meshManager) throw new Error('meshManager is required')
|
|
71
|
+
if (!signaling) throw new Error('signaling is required')
|
|
72
|
+
const log = onLog || (() => {})
|
|
73
|
+
|
|
74
|
+
/** @type {Set<string>} remotePodIds whose ICE relay is already wired */
|
|
75
|
+
const wiredIce = new Set()
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Get (or create) the WebRTCPeerConnection for a peer, and make sure its
|
|
79
|
+
* locally-gathered ICE candidates get relayed exactly once, no matter
|
|
80
|
+
* which side (offerer or answerer) first touches this remotePodId.
|
|
81
|
+
*/
|
|
82
|
+
async function getWiredConnection(remotePodId) {
|
|
83
|
+
const conn = await meshManager.connectToPeer(remotePodId)
|
|
84
|
+
if (!wiredIce.has(remotePodId)) {
|
|
85
|
+
wiredIce.add(remotePodId)
|
|
86
|
+
conn.onIceCandidate((candidate) => {
|
|
87
|
+
try {
|
|
88
|
+
signaling.send('webrtc-ice', remotePodId, candidate)
|
|
89
|
+
} catch (err) {
|
|
90
|
+
log('webrtc-negotiator:ice-send-failed', { remotePodId, error: err?.message || String(err) })
|
|
91
|
+
}
|
|
92
|
+
})
|
|
93
|
+
conn.onClose(() => wiredIce.delete(remotePodId))
|
|
94
|
+
}
|
|
95
|
+
return conn
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Resolve once `conn`'s DataChannel is open (immediately if it already
|
|
100
|
+
* is), or reject after `timeoutMs`. Shared by the caller-side factory
|
|
101
|
+
* (which already awaited this inline) and the callee-side auto-answer
|
|
102
|
+
* path below (which needs the same wait before it can hand back a ready
|
|
103
|
+
* adapter via `onIncomingConnection`).
|
|
104
|
+
*/
|
|
105
|
+
async function waitForOpen(conn, timeoutMs) {
|
|
106
|
+
if (conn.isOpen) return
|
|
107
|
+
await new Promise((resolve, reject) => {
|
|
108
|
+
const timer = setTimeout(() => {
|
|
109
|
+
reject(new Error('WebRTC DataChannel did not open in time'))
|
|
110
|
+
}, timeoutMs)
|
|
111
|
+
conn.onStateChange((state) => {
|
|
112
|
+
if (state === 'connected' && conn.isOpen) {
|
|
113
|
+
clearTimeout(timer)
|
|
114
|
+
resolve()
|
|
115
|
+
}
|
|
116
|
+
})
|
|
117
|
+
// In case it opened between the isOpen check above and registering
|
|
118
|
+
// the listener.
|
|
119
|
+
if (conn.isOpen) {
|
|
120
|
+
clearTimeout(timer)
|
|
121
|
+
resolve()
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Callee side: answer any inbound offer automatically. Registered once,
|
|
127
|
+
// for the lifetime of this factory, so a peer that only ever receives
|
|
128
|
+
// connections (never calls negotiate() itself) still gets connected.
|
|
129
|
+
signaling.onOffer(async (fromPodId, offer) => {
|
|
130
|
+
try {
|
|
131
|
+
const conn = await getWiredConnection(fromPodId)
|
|
132
|
+
const answer = await conn.handleOffer(offer)
|
|
133
|
+
signaling.send('webrtc-answer', fromPodId, answer)
|
|
134
|
+
log('webrtc-negotiator:answered', { from: fromPodId })
|
|
135
|
+
|
|
136
|
+
// Hand the callee side a ready transport adapter too, once its
|
|
137
|
+
// DataChannel actually opens, so callers (mesh-bootstrap.mjs) can
|
|
138
|
+
// give it the same PeerNode-level session bookkeeping the caller
|
|
139
|
+
// side gets from connectToPeer() -- see PeerNode.adoptIncomingSession().
|
|
140
|
+
if (typeof onIncomingConnection === 'function') {
|
|
141
|
+
await waitForOpen(conn, defaultOpenTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS)
|
|
142
|
+
const adapter = new WebRTCTransportAdapter(conn)
|
|
143
|
+
await adapter.connect()
|
|
144
|
+
onIncomingConnection(fromPodId, adapter)
|
|
145
|
+
}
|
|
146
|
+
} catch (err) {
|
|
147
|
+
log('webrtc-negotiator:offer-failed', { from: fromPodId, error: err?.message || String(err) })
|
|
148
|
+
}
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
// ICE candidates arriving from either side of any connection.
|
|
152
|
+
signaling.onIce((fromPodId, candidate) => {
|
|
153
|
+
const conn = meshManager.getConnection(fromPodId)
|
|
154
|
+
if (!conn) {
|
|
155
|
+
log('webrtc-negotiator:ice-no-connection', { from: fromPodId })
|
|
156
|
+
return
|
|
157
|
+
}
|
|
158
|
+
conn.addIceCandidate(candidate).catch((err) => {
|
|
159
|
+
log('webrtc-negotiator:ice-add-failed', { from: fromPodId, error: err?.message || String(err) })
|
|
160
|
+
})
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Caller-side factory: create an offer, relay it, wait for the answer and
|
|
165
|
+
* for the DataChannel to open, then hand back a MeshTransport.
|
|
166
|
+
*
|
|
167
|
+
* @param {string} endpoint - Remote peer's podId (by convention for 'webrtc').
|
|
168
|
+
* @param {object} [auth]
|
|
169
|
+
* @returns {Promise<import('@johnhenry/browsermesh-transport').WebRTCTransportAdapter>}
|
|
170
|
+
*/
|
|
171
|
+
return async function webrtcTransportFactory(endpoint, auth) {
|
|
172
|
+
const remotePodId = endpoint
|
|
173
|
+
if (!remotePodId) throw new Error('webrtcTransportFactory: endpoint (remote podId) is required')
|
|
174
|
+
|
|
175
|
+
const answerTimeoutMs = auth?.answerTimeoutMs ?? DEFAULT_ANSWER_TIMEOUT_MS
|
|
176
|
+
const openTimeoutMs = auth?.openTimeoutMs ?? DEFAULT_OPEN_TIMEOUT_MS
|
|
177
|
+
|
|
178
|
+
const conn = await getWiredConnection(remotePodId)
|
|
179
|
+
|
|
180
|
+
const answerPromise = new Promise((resolve, reject) => {
|
|
181
|
+
const timer = setTimeout(() => {
|
|
182
|
+
unsubscribe()
|
|
183
|
+
reject(new Error(`WebRTC negotiation with ${remotePodId} timed out waiting for an answer`))
|
|
184
|
+
}, answerTimeoutMs)
|
|
185
|
+
const unsubscribe = signaling.onAnswer((fromPodId, answer) => {
|
|
186
|
+
if (fromPodId !== remotePodId) return
|
|
187
|
+
clearTimeout(timer)
|
|
188
|
+
unsubscribe()
|
|
189
|
+
resolve(answer)
|
|
190
|
+
})
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
const offer = await conn.createOffer()
|
|
194
|
+
signaling.send('webrtc-offer', remotePodId, offer)
|
|
195
|
+
|
|
196
|
+
const answer = await answerPromise
|
|
197
|
+
await conn.handleAnswer(answer)
|
|
198
|
+
|
|
199
|
+
try {
|
|
200
|
+
await waitForOpen(conn, openTimeoutMs)
|
|
201
|
+
} catch {
|
|
202
|
+
throw new Error(`WebRTC DataChannel with ${remotePodId} did not open in time`)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const adapter = new WebRTCTransportAdapter(conn)
|
|
206
|
+
await adapter.connect()
|
|
207
|
+
return adapter
|
|
208
|
+
}
|
|
209
|
+
}
|