@johnhenry/browsermesh-transport 0.1.3 → 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/package.json +1 -1
- package/src/webrtc.mjs +176 -18
- package/src/websocket.mjs +123 -20
package/package.json
CHANGED
package/src/webrtc.mjs
CHANGED
|
@@ -110,6 +110,48 @@ export function mergeIceServers(userServers, defaults = DEFAULT_ICE_SERVERS) {
|
|
|
110
110
|
*/
|
|
111
111
|
const MAX_PENDING_REMOTE_CANDIDATES = 64
|
|
112
112
|
|
|
113
|
+
// ---------------------------------------------------------------------------
|
|
114
|
+
// Dual data channels: control + bulk
|
|
115
|
+
// ---------------------------------------------------------------------------
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Label of the original, always-present data channel. Ordered and reliable:
|
|
119
|
+
* chat, agent RPC, sync metadata and consensus votes all depend on messages
|
|
120
|
+
* arriving in the order they were sent.
|
|
121
|
+
*/
|
|
122
|
+
const CONTROL_CHANNEL_LABEL = 'mesh'
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Label of the second data channel, added alongside `CONTROL_CHANNEL_LABEL`
|
|
126
|
+
* on the SAME already-negotiated RTCPeerConnection -- a second SCTP stream,
|
|
127
|
+
* not a second ICE/DTLS handshake. Its purpose is to give bulk transfers
|
|
128
|
+
* (file chunks, sync payloads) a lane of their own, so a large chunk queued
|
|
129
|
+
* on it can never sit in front of a latency-sensitive control message the
|
|
130
|
+
* way a single shared channel forced it to.
|
|
131
|
+
*/
|
|
132
|
+
const BULK_CHANNEL_LABEL = 'mesh-bulk'
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* `ordered: false`, deliberately, and nothing else set on the object --
|
|
136
|
+
* still fully *reliable* (SCTP retransmits until every chunk arrives; there
|
|
137
|
+
* is no `maxRetransmits`/`maxPacketLifeTime` bound here), just not ordered.
|
|
138
|
+
*
|
|
139
|
+
* Justified by the consumer, not assumed: clawser's chunk reassembly
|
|
140
|
+
* (`web/clawser-mesh-files.js`) addresses each chunk by content hash (`cid`)
|
|
141
|
+
* plus offset and dedupes into a `Set` keyed by that hash -- there is no
|
|
142
|
+
* array-index/push-order dependency, so a chunk that overtakes an earlier
|
|
143
|
+
* one on the wire reassembles identically to one that didn't. Callers
|
|
144
|
+
* routing other traffic onto this channel must have the same tolerance;
|
|
145
|
+
* `ordered: true` control-style traffic belongs on `CONTROL_CHANNEL_LABEL`.
|
|
146
|
+
*
|
|
147
|
+
* Unordered also matters *within* the bulk channel, not only against the
|
|
148
|
+
* control channel: with `ordered: true`, SCTP itself withholds a later
|
|
149
|
+
* chunk that arrived fine behind an earlier one that was lost and is being
|
|
150
|
+
* retransmitted -- head-of-line blocking inside the one channel that exists
|
|
151
|
+
* specifically to avoid it. `ordered: false` removes that constraint.
|
|
152
|
+
*/
|
|
153
|
+
const BULK_CHANNEL_OPTIONS = Object.freeze({ ordered: false })
|
|
154
|
+
|
|
113
155
|
// ---------------------------------------------------------------------------
|
|
114
156
|
// WebRTCPeerConnection
|
|
115
157
|
// ---------------------------------------------------------------------------
|
|
@@ -129,6 +171,14 @@ export class WebRTCPeerConnection {
|
|
|
129
171
|
#remotePodId
|
|
130
172
|
#pc = null
|
|
131
173
|
#dataChannel = null
|
|
174
|
+
/**
|
|
175
|
+
* The second, `mesh-bulk` data channel. Stays null against a peer that
|
|
176
|
+
* never creates/sends one -- an older build talking to this one, since
|
|
177
|
+
* only the offerer side ever calls `createDataChannel()` (see
|
|
178
|
+
* `createOffer()`/`handleOffer()`) -- and every send that asks for it
|
|
179
|
+
* falls back to `#dataChannel` while it is null. See `send()`.
|
|
180
|
+
*/
|
|
181
|
+
#bulkChannel = null
|
|
132
182
|
#iceServers
|
|
133
183
|
#onLog
|
|
134
184
|
#state = 'new' // new | connecting | connected | failed | closed
|
|
@@ -190,6 +240,16 @@ export class WebRTCPeerConnection {
|
|
|
190
240
|
this.#dataChannel?.readyState === 'open'
|
|
191
241
|
}
|
|
192
242
|
|
|
243
|
+
/**
|
|
244
|
+
* True when the second (`mesh-bulk`) data channel is open and usable.
|
|
245
|
+
* False against a peer that never created/received one -- an older build
|
|
246
|
+
* paired with this one -- in which case `send(data, {channel: 'bulk'})`
|
|
247
|
+
* falls back to the control channel rather than throwing. See `send()`.
|
|
248
|
+
*/
|
|
249
|
+
get isBulkOpen() {
|
|
250
|
+
return this.#bulkChannel?.readyState === 'open'
|
|
251
|
+
}
|
|
252
|
+
|
|
193
253
|
// -- Offer / Answer -------------------------------------------------------
|
|
194
254
|
|
|
195
255
|
/**
|
|
@@ -205,10 +265,20 @@ export class WebRTCPeerConnection {
|
|
|
205
265
|
this.#setupIceHandling()
|
|
206
266
|
this.#setupConnectionStateHandling()
|
|
207
267
|
|
|
208
|
-
this.#dataChannel = this.#pc.createDataChannel(
|
|
268
|
+
this.#dataChannel = this.#pc.createDataChannel(CONTROL_CHANNEL_LABEL, {
|
|
209
269
|
ordered: true,
|
|
210
270
|
})
|
|
211
|
-
this.#setupDataChannel(this.#dataChannel)
|
|
271
|
+
this.#setupDataChannel(this.#dataChannel, 'control')
|
|
272
|
+
|
|
273
|
+
// A second SCTP stream on the SAME RTCPeerConnection -- no additional
|
|
274
|
+
// ICE/DTLS negotiation, just one more createDataChannel() call before the
|
|
275
|
+
// offer is created, so both channels' m-line/stream setup is captured in
|
|
276
|
+
// the single SDP offer below. Only the offerer side creates channels
|
|
277
|
+
// (the answerer only ever listens via `ondatachannel`, see handleOffer());
|
|
278
|
+
// that asymmetry is unchanged, just now applied to two channels instead
|
|
279
|
+
// of one.
|
|
280
|
+
this.#bulkChannel = this.#pc.createDataChannel(BULK_CHANNEL_LABEL, BULK_CHANNEL_OPTIONS)
|
|
281
|
+
this.#setupDataChannel(this.#bulkChannel, 'bulk')
|
|
212
282
|
|
|
213
283
|
const offer = await this.#pc.createOffer()
|
|
214
284
|
await this.#pc.setLocalDescription(offer)
|
|
@@ -281,9 +351,24 @@ export class WebRTCPeerConnection {
|
|
|
281
351
|
this.#setupIceHandling()
|
|
282
352
|
this.#setupConnectionStateHandling()
|
|
283
353
|
|
|
354
|
+
// A fresh offer from a NEW-build peer carries two data channels; one
|
|
355
|
+
// from an OLDER build carries only 'mesh' and this event fires once.
|
|
356
|
+
// Routed by label, not by arrival order -- `ondatachannel` does not
|
|
357
|
+
// promise the channels arrive in the order they were created, and
|
|
358
|
+
// guessing "first event = control" would occasionally hand the control
|
|
359
|
+
// role to the bulk channel and vice versa. Anything not recognised as
|
|
360
|
+
// the bulk label is treated as control, which is also the correct
|
|
361
|
+
// behaviour for a hypothetical future peer that adds yet another
|
|
362
|
+
// channel this build doesn't know about.
|
|
284
363
|
this.#pc.ondatachannel = (event) => {
|
|
285
|
-
|
|
286
|
-
|
|
364
|
+
const chan = event.channel
|
|
365
|
+
if (chan.label === BULK_CHANNEL_LABEL) {
|
|
366
|
+
this.#bulkChannel = chan
|
|
367
|
+
this.#setupDataChannel(chan, 'bulk')
|
|
368
|
+
} else {
|
|
369
|
+
this.#dataChannel = chan
|
|
370
|
+
this.#setupDataChannel(chan, 'control')
|
|
371
|
+
}
|
|
287
372
|
}
|
|
288
373
|
|
|
289
374
|
await this.#pc.setRemoteDescription({ type: 'offer', sdp: offer.sdp })
|
|
@@ -425,18 +510,42 @@ export class WebRTCPeerConnection {
|
|
|
425
510
|
onStateChange(cb) { this.#stateChangeCbs.push(cb) }
|
|
426
511
|
|
|
427
512
|
/**
|
|
428
|
-
* Send data over
|
|
429
|
-
* Objects are JSON-serialized automatically.
|
|
513
|
+
* Send data over a DataChannel. Objects are JSON-serialized automatically.
|
|
430
514
|
*
|
|
431
515
|
* @param {string|object} data
|
|
516
|
+
* @param {object} [opts]
|
|
517
|
+
* @param {'control'|'bulk'} [opts.channel='control'] - Which SCTP stream to
|
|
518
|
+
* send on. `'control'` is the original `mesh` channel (ordered, used for
|
|
519
|
+
* everything by default -- every pre-existing call site that never
|
|
520
|
+
* passes `opts` keeps sending here, unchanged). `'bulk'` is the second
|
|
521
|
+
* `mesh-bulk` channel (unordered, see `BULK_CHANNEL_OPTIONS`), meant for
|
|
522
|
+
* large/chunked payloads that would otherwise sit in front of
|
|
523
|
+
* latency-sensitive control messages queued behind them.
|
|
524
|
+
*
|
|
525
|
+
* Falling back rather than throwing when `'bulk'` is requested but
|
|
526
|
+
* unavailable is the load-bearing part of this option: it is what keeps
|
|
527
|
+
* an old peer (single-channel) and a new peer (dual-channel) compatible
|
|
528
|
+
* with no version negotiation. The bulk channel is unavailable exactly
|
|
529
|
+
* when the remote peer's build never created/sent one (see
|
|
530
|
+
* `handleOffer()`) -- there is no other way for it to be missing on a
|
|
531
|
+
* peer that itself created both -- so the traffic still gets there, just
|
|
532
|
+
* without its own lane, exactly as it did before this channel existed.
|
|
533
|
+
* @throws {Error} If there is no data channel at all, or the channel that
|
|
534
|
+
* was actually selected (after fallback) is not open.
|
|
432
535
|
*/
|
|
433
|
-
send(data) {
|
|
434
|
-
if (
|
|
435
|
-
|
|
536
|
+
send(data, { channel = 'control' } = {}) {
|
|
537
|
+
if (channel !== 'control' && channel !== 'bulk') {
|
|
538
|
+
throw new Error(`Unknown channel: ${channel}`)
|
|
539
|
+
}
|
|
540
|
+
const dc = (channel === 'bulk' && this.#bulkChannel?.readyState === 'open')
|
|
541
|
+
? this.#bulkChannel
|
|
542
|
+
: this.#dataChannel
|
|
543
|
+
if (!dc) throw new Error('No data channel')
|
|
544
|
+
if (dc.readyState !== 'open') {
|
|
436
545
|
throw new Error('Data channel not open')
|
|
437
546
|
}
|
|
438
547
|
const str = typeof data === 'string' ? data : JSON.stringify(data)
|
|
439
|
-
|
|
548
|
+
dc.send(str)
|
|
440
549
|
this.#stats.bytesSent += str.length
|
|
441
550
|
this.#stats.messagesOut += 1
|
|
442
551
|
}
|
|
@@ -586,6 +695,10 @@ export class WebRTCPeerConnection {
|
|
|
586
695
|
try { this.#dataChannel.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'this', e) }
|
|
587
696
|
this.#dataChannel = null
|
|
588
697
|
}
|
|
698
|
+
if (this.#bulkChannel) {
|
|
699
|
+
try { this.#bulkChannel.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'this', e) }
|
|
700
|
+
this.#bulkChannel = null
|
|
701
|
+
}
|
|
589
702
|
if (this.#pc) {
|
|
590
703
|
try { this.#pc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'this', e) }
|
|
591
704
|
this.#pc = null
|
|
@@ -653,13 +766,19 @@ export class WebRTCPeerConnection {
|
|
|
653
766
|
*/
|
|
654
767
|
#releasePeerConnection() {
|
|
655
768
|
const dc = this.#dataChannel
|
|
769
|
+
const bulkDc = this.#bulkChannel
|
|
656
770
|
const pc = this.#pc
|
|
657
771
|
this.#dataChannel = null
|
|
772
|
+
this.#bulkChannel = null
|
|
658
773
|
this.#pc = null
|
|
659
774
|
if (dc) {
|
|
660
775
|
dc.onopen = null; dc.onmessage = null; dc.onclose = null; dc.onerror = null
|
|
661
776
|
try { dc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'release-dc', e) }
|
|
662
777
|
}
|
|
778
|
+
if (bulkDc) {
|
|
779
|
+
bulkDc.onopen = null; bulkDc.onmessage = null; bulkDc.onclose = null; bulkDc.onerror = null
|
|
780
|
+
try { bulkDc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'release-bulk-dc', e) }
|
|
781
|
+
}
|
|
663
782
|
if (pc) {
|
|
664
783
|
pc.onicecandidate = null; pc.ondatachannel = null; pc.onconnectionstatechange = null
|
|
665
784
|
try { pc.close() } catch (e) { silentCatch('clawser-mesh-webrtc', 'release-pc', e) }
|
|
@@ -823,10 +942,31 @@ export class WebRTCPeerConnection {
|
|
|
823
942
|
this.#disconnectedTimer = null
|
|
824
943
|
}
|
|
825
944
|
|
|
826
|
-
|
|
945
|
+
/**
|
|
946
|
+
* Wire up one DataChannel's events. `kind` distinguishes the control
|
|
947
|
+
* channel, whose lifecycle drives this connection's `state`, from the
|
|
948
|
+
* bulk channel, which is treated as auxiliary: losing it (close/error)
|
|
949
|
+
* degrades this connection to control-channel-only via `send()`'s
|
|
950
|
+
* fallback rather than tearing down a connection that is otherwise fine.
|
|
951
|
+
* That degrade is exactly the state a peer running an older,
|
|
952
|
+
* single-channel build looks like to begin with, so the bulk channel
|
|
953
|
+
* failing after connecting is handled by the same path that already
|
|
954
|
+
* handles it never existing.
|
|
955
|
+
*
|
|
956
|
+
* Message delivery is deliberately identical for both kinds: every
|
|
957
|
+
* `onMessage()` callback fires for a message from EITHER channel,
|
|
958
|
+
* regardless of which one is "the" channel for `state`/`isOpen` purposes.
|
|
959
|
+
* This is also what makes an old, single-channel peer talking to this one
|
|
960
|
+
* (as the answerer) work with no extra wiring: `ondatachannel` fires once
|
|
961
|
+
* per channel this side creates, an older `handleOffer`-shaped answerer
|
|
962
|
+
* attaches its own per-channel listeners to each one exactly the way this
|
|
963
|
+
* method does, and only ever overwrites which channel it treats as "the"
|
|
964
|
+
* one to *send* on -- so it still receives from both.
|
|
965
|
+
*/
|
|
966
|
+
#setupDataChannel(dc, kind) {
|
|
827
967
|
dc.onopen = () => {
|
|
828
|
-
this.#setState('connected')
|
|
829
|
-
this.#log(`DataChannel open with ${this.#remotePodId}`)
|
|
968
|
+
if (kind === 'control') this.#setState('connected')
|
|
969
|
+
this.#log(`DataChannel (${kind}) open with ${this.#remotePodId}`)
|
|
830
970
|
}
|
|
831
971
|
dc.onmessage = (event) => {
|
|
832
972
|
const rawLen = event.data?.length || 0
|
|
@@ -839,12 +979,27 @@ export class WebRTCPeerConnection {
|
|
|
839
979
|
}
|
|
840
980
|
}
|
|
841
981
|
dc.onclose = () => {
|
|
842
|
-
|
|
843
|
-
|
|
982
|
+
if (kind === 'bulk') {
|
|
983
|
+
// Auxiliary: drop the reference so send({channel:'bulk'}) falls back
|
|
984
|
+
// to control, but don't tear down a connection that may otherwise be
|
|
985
|
+
// healthy.
|
|
986
|
+
if (this.#bulkChannel === dc) this.#bulkChannel = null
|
|
987
|
+
this.#log(`Bulk DataChannel closed with ${this.#remotePodId}; falling back to control channel`)
|
|
988
|
+
return
|
|
989
|
+
}
|
|
990
|
+
// The remote hung up the control channel. Go through close() rather
|
|
991
|
+
// than just flipping the state, so our own RTCPeerConnection (and any
|
|
992
|
+
// still-open bulk channel) is released too.
|
|
844
993
|
if (this.#state !== 'closed') this.close()
|
|
845
994
|
}
|
|
846
995
|
dc.onerror = (event) => {
|
|
847
|
-
this.#fireError(event?.error || new Error(
|
|
996
|
+
this.#fireError(event?.error || new Error(`DataChannel (${kind}) error`))
|
|
997
|
+
if (kind === 'bulk') {
|
|
998
|
+
// Same reasoning as onclose above: an error on the auxiliary channel
|
|
999
|
+
// alone should not take down a working control channel.
|
|
1000
|
+
if (this.#bulkChannel === dc) this.#bulkChannel = null
|
|
1001
|
+
return
|
|
1002
|
+
}
|
|
848
1003
|
if (this.#state !== 'closed') {
|
|
849
1004
|
this.#setState('closed')
|
|
850
1005
|
this.#fireClose()
|
|
@@ -1284,9 +1439,12 @@ export class WebRTCTransportAdapter extends MeshTransport {
|
|
|
1284
1439
|
* Send data through the underlying WebRTC DataChannel.
|
|
1285
1440
|
*
|
|
1286
1441
|
* @param {string|object} data
|
|
1442
|
+
* @param {object} [opts]
|
|
1443
|
+
* @param {'control'|'bulk'} [opts.channel='control'] - See
|
|
1444
|
+
* `WebRTCPeerConnection.send()`.
|
|
1287
1445
|
*/
|
|
1288
|
-
send(data) {
|
|
1289
|
-
this.#connection.send(data)
|
|
1446
|
+
send(data, opts) {
|
|
1447
|
+
this.#connection.send(data, opts)
|
|
1290
1448
|
}
|
|
1291
1449
|
|
|
1292
1450
|
/**
|
package/src/websocket.mjs
CHANGED
|
@@ -383,6 +383,35 @@ export class WebSocketTransport {
|
|
|
383
383
|
// WebRTCTransport
|
|
384
384
|
// ---------------------------------------------------------------------------
|
|
385
385
|
|
|
386
|
+
/**
|
|
387
|
+
* Label of the original, always-present data channel. Ordered and reliable
|
|
388
|
+
* -- everything defaults here, unchanged from before the bulk channel
|
|
389
|
+
* existed.
|
|
390
|
+
*/
|
|
391
|
+
const CONTROL_CHANNEL_LABEL = 'mesh';
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Label of the second data channel, created alongside `CONTROL_CHANNEL_LABEL`
|
|
395
|
+
* on the SAME already-negotiated RTCPeerConnection (a second SCTP stream,
|
|
396
|
+
* not a second ICE/DTLS handshake), so bulk transfers stop sitting in front
|
|
397
|
+
* of latency-sensitive control messages on the one channel they used to
|
|
398
|
+
* share. See the identical constant and its rationale in `webrtc.mjs`,
|
|
399
|
+
* which this mirrors.
|
|
400
|
+
*/
|
|
401
|
+
const BULK_CHANNEL_LABEL = 'mesh-bulk';
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* `ordered: false`, still fully reliable (no `maxRetransmits`/
|
|
405
|
+
* `maxPacketLifeTime`). Justified by clawser's chunk reassembly
|
|
406
|
+
* (`web/clawser-mesh-files.js`), which addresses each chunk by content hash
|
|
407
|
+
* plus offset and dedupes into a `Set` -- no order dependency -- so an
|
|
408
|
+
* out-of-order chunk on this channel reassembles identically to an in-order
|
|
409
|
+
* one, and unordered delivery also avoids head-of-line blocking *within*
|
|
410
|
+
* this one channel (an ordered channel would withhold a later chunk that
|
|
411
|
+
* arrived fine behind an earlier, lost one being retransmitted).
|
|
412
|
+
*/
|
|
413
|
+
const BULK_CHANNEL_OPTIONS = Object.freeze({ ordered: false });
|
|
414
|
+
|
|
386
415
|
/**
|
|
387
416
|
* WebRTC data channel transport.
|
|
388
417
|
*
|
|
@@ -415,6 +444,16 @@ export class WebRTCTransport {
|
|
|
415
444
|
/** @type {object|null} */
|
|
416
445
|
#dataChannel = null;
|
|
417
446
|
|
|
447
|
+
/**
|
|
448
|
+
* The second, `mesh-bulk` data channel. Stays null against a peer whose
|
|
449
|
+
* build never creates/sends one -- only the offerer side ever calls
|
|
450
|
+
* `createDataChannel()` (see `connect()`/`handleOffer()`) -- and every
|
|
451
|
+
* send that asks for `'bulk'` falls back to `#dataChannel` while it is
|
|
452
|
+
* null. See `send()`.
|
|
453
|
+
* @type {object|null}
|
|
454
|
+
*/
|
|
455
|
+
#bulkChannel = null;
|
|
456
|
+
|
|
418
457
|
/** @type {{ open: Function[], message: Function[], close: Function[], error: Function[], 'ice-candidate': Function[] }} */
|
|
419
458
|
#callbacks = { open: [], message: [], close: [], error: [], 'ice-candidate': [] };
|
|
420
459
|
|
|
@@ -506,9 +545,16 @@ export class WebRTCTransport {
|
|
|
506
545
|
}
|
|
507
546
|
});
|
|
508
547
|
|
|
509
|
-
// Create data
|
|
510
|
-
|
|
511
|
-
|
|
548
|
+
// Create data channels and offer. A second createDataChannel() call on
|
|
549
|
+
// the same RTCPeerConnection is a second SCTP stream, not a second
|
|
550
|
+
// ICE/DTLS negotiation -- both are captured in the single offer created
|
|
551
|
+
// below. Only the offerer side creates channels; the answerer only ever
|
|
552
|
+
// listens via 'datachannel' (see handleOffer()).
|
|
553
|
+
this.#dataChannel = this.#pc.createDataChannel(CONTROL_CHANNEL_LABEL, { ordered: true });
|
|
554
|
+
this._attachDataChannelListeners(this.#dataChannel, 'control');
|
|
555
|
+
|
|
556
|
+
this.#bulkChannel = this.#pc.createDataChannel(BULK_CHANNEL_LABEL, BULK_CHANNEL_OPTIONS);
|
|
557
|
+
this._attachDataChannelListeners(this.#bulkChannel, 'bulk');
|
|
512
558
|
|
|
513
559
|
const offer = await this.#pc.createOffer();
|
|
514
560
|
await this.#pc.setLocalDescription(offer);
|
|
@@ -606,33 +652,65 @@ export class WebRTCTransport {
|
|
|
606
652
|
// connect(), this must not resolve until the data channel is actually
|
|
607
653
|
// open, not merely once it has arrived or once the answer was sent.
|
|
608
654
|
return new Promise((resolve) => {
|
|
655
|
+
// A NEW-build peer offers two channels, routed here by label -- not by
|
|
656
|
+
// arrival order, which 'datachannel' does not promise -- so this event
|
|
657
|
+
// fires twice; an OLDER build offers only 'mesh' and it fires once,
|
|
658
|
+
// and #bulkChannel simply stays null (see #bulkChannel's docs and
|
|
659
|
+
// send()'s fallback). Only the control channel's open gates
|
|
660
|
+
// 'connected': the bulk channel is auxiliary, and gating on it too
|
|
661
|
+
// would mean a peer that never sends 'mesh-bulk' (an older build) can
|
|
662
|
+
// never connect.
|
|
663
|
+
let resolved = false;
|
|
664
|
+
const onControlOpen = () => {
|
|
665
|
+
if (resolved) return;
|
|
666
|
+
resolved = true;
|
|
667
|
+
this.#state = 'connected';
|
|
668
|
+
this._fireEvent('open');
|
|
669
|
+
resolve();
|
|
670
|
+
};
|
|
609
671
|
this.#pc.addEventListener('datachannel', (ev) => {
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
this
|
|
614
|
-
|
|
615
|
-
|
|
672
|
+
const chan = ev.channel;
|
|
673
|
+
if (chan.label === BULK_CHANNEL_LABEL) {
|
|
674
|
+
this.#bulkChannel = chan;
|
|
675
|
+
this._attachDataChannelListeners(chan, 'bulk');
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
this.#dataChannel = chan;
|
|
679
|
+
this._attachDataChannelListeners(chan, 'control');
|
|
680
|
+
if (chan.readyState === 'open') {
|
|
681
|
+
onControlOpen();
|
|
616
682
|
} else {
|
|
617
683
|
const onDCOpen = () => {
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
this._fireEvent('open');
|
|
621
|
-
resolve();
|
|
684
|
+
chan.removeEventListener('open', onDCOpen);
|
|
685
|
+
onControlOpen();
|
|
622
686
|
};
|
|
623
|
-
|
|
687
|
+
chan.addEventListener('open', onDCOpen);
|
|
624
688
|
}
|
|
625
689
|
});
|
|
626
690
|
});
|
|
627
691
|
}
|
|
628
692
|
|
|
629
693
|
/**
|
|
630
|
-
* Send data over
|
|
694
|
+
* Send data over a data channel.
|
|
631
695
|
* @param {*} data
|
|
696
|
+
* @param {object} [opts]
|
|
697
|
+
* @param {'control'|'bulk'} [opts.channel='control'] - `'control'` is the
|
|
698
|
+
* original `mesh` channel (every pre-existing call site that never
|
|
699
|
+
* passes `opts` keeps using it, unchanged). `'bulk'` is the `mesh-bulk`
|
|
700
|
+
* channel, for large/chunked payloads. Falls back to `'control'` when
|
|
701
|
+
* the bulk channel doesn't exist or isn't open -- which is exactly what
|
|
702
|
+
* happens when the remote peer's build never created/sent one -- so
|
|
703
|
+
* traffic still gets there, just without a lane of its own, and no
|
|
704
|
+
* version negotiation is needed for an old peer and a new peer to
|
|
705
|
+
* interoperate.
|
|
632
706
|
*/
|
|
633
|
-
send(data) {
|
|
634
|
-
if (!this.connected
|
|
635
|
-
this.#
|
|
707
|
+
send(data, { channel = 'control' } = {}) {
|
|
708
|
+
if (!this.connected) throw new Error('Not connected');
|
|
709
|
+
const dc = (channel === 'bulk' && this.#bulkChannel?.readyState === 'open')
|
|
710
|
+
? this.#bulkChannel
|
|
711
|
+
: this.#dataChannel;
|
|
712
|
+
if (!dc) throw new Error('Not connected');
|
|
713
|
+
dc.send(data);
|
|
636
714
|
this.#stats.messagesSent++;
|
|
637
715
|
this.#stats.bytesOut += byteLength(data);
|
|
638
716
|
}
|
|
@@ -646,6 +724,9 @@ export class WebRTCTransport {
|
|
|
646
724
|
if (this.#dataChannel) {
|
|
647
725
|
try { this.#dataChannel.close(); } catch (e) { silentCatch('clawser-mesh-websocket', 'this', e) }
|
|
648
726
|
}
|
|
727
|
+
if (this.#bulkChannel) {
|
|
728
|
+
try { this.#bulkChannel.close(); } catch (e) { silentCatch('clawser-mesh-websocket', 'this', e) }
|
|
729
|
+
}
|
|
649
730
|
if (this.#pc) {
|
|
650
731
|
this.#pc.close();
|
|
651
732
|
}
|
|
@@ -689,11 +770,29 @@ export class WebRTCTransport {
|
|
|
689
770
|
|
|
690
771
|
/**
|
|
691
772
|
* Attach event listeners to a data channel.
|
|
773
|
+
*
|
|
774
|
+
* `kind` distinguishes the control channel, whose lifecycle drives this
|
|
775
|
+
* transport's `state`, from the auxiliary bulk channel: losing the bulk
|
|
776
|
+
* channel alone (close) degrades future `send({channel:'bulk'})` calls to
|
|
777
|
+
* the control-channel fallback rather than closing an otherwise-healthy
|
|
778
|
+
* transport -- the same state a peer that never had a bulk channel to
|
|
779
|
+
* begin with looks like.
|
|
780
|
+
*
|
|
781
|
+
* Message delivery is identical for both kinds -- every 'message'
|
|
782
|
+
* listener fires for a message from either channel -- which is also what
|
|
783
|
+
* makes an OLDER, single-channel peer (as the answerer) work against this
|
|
784
|
+
* one with no extra wiring: it attaches its own listener to each incoming
|
|
785
|
+
* channel exactly the way this method does, and only ever changes which
|
|
786
|
+
* one it treats as "the" channel to *send* on, so it still receives from
|
|
787
|
+
* both. See webrtc.mjs's `#setupDataChannel()` for the identical reasoning
|
|
788
|
+
* on the other WebRTC transport class in this package.
|
|
789
|
+
*
|
|
692
790
|
* @param {object} dc
|
|
791
|
+
* @param {'control'|'bulk'} [kind='control']
|
|
693
792
|
*/
|
|
694
|
-
_attachDataChannelListeners(dc) {
|
|
793
|
+
_attachDataChannelListeners(dc, kind = 'control') {
|
|
695
794
|
dc.addEventListener('open', () => {
|
|
696
|
-
if (this.#state === 'connecting') {
|
|
795
|
+
if (kind === 'control' && this.#state === 'connecting') {
|
|
697
796
|
this.#state = 'connected';
|
|
698
797
|
this._fireEvent('open');
|
|
699
798
|
}
|
|
@@ -707,6 +806,10 @@ export class WebRTCTransport {
|
|
|
707
806
|
});
|
|
708
807
|
|
|
709
808
|
dc.addEventListener('close', () => {
|
|
809
|
+
if (kind === 'bulk') {
|
|
810
|
+
if (this.#bulkChannel === dc) this.#bulkChannel = null;
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
710
813
|
if (this.#state !== 'closed' && this.#state !== 'closing') {
|
|
711
814
|
this.#state = 'closed';
|
|
712
815
|
this._fireEvent('close');
|