@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,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
+ }