@dimchansky/meshpost 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +355 -2
- package/dist/blob.d.ts +45 -0
- package/dist/blob.js +364 -0
- package/dist/channel.d.ts +26 -0
- package/dist/channel.js +51 -0
- package/dist/combine.d.ts +7 -0
- package/dist/combine.js +249 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +9 -0
- package/dist/manual.d.ts +13 -0
- package/dist/manual.js +109 -0
- package/dist/mqtt.d.ts +20 -0
- package/dist/mqtt.js +610 -0
- package/dist/room.d.ts +99 -0
- package/dist/room.js +1130 -0
- package/dist/signaling.d.ts +70 -0
- package/dist/signaling.js +118 -0
- package/dist/tabs.d.ts +3 -0
- package/dist/tabs.js +94 -0
- package/dist/ws.d.ts +14 -0
- package/dist/ws.js +272 -0
- package/docs/behavior.md +237 -0
- package/package.json +65 -4
package/dist/room.js
ADDED
|
@@ -0,0 +1,1130 @@
|
|
|
1
|
+
import { isSignal, randomUuid, withLoopbackFallback } from './signaling.js';
|
|
2
|
+
/** Built-in Cloudflare and Google public STUN servers used by default. */
|
|
3
|
+
export const defaultIceServers = Object.freeze([
|
|
4
|
+
Object.freeze({ urls: 'stun:stun.cloudflare.com:3478' }),
|
|
5
|
+
Object.freeze({ urls: 'stun:stun.l.google.com:19302' }),
|
|
6
|
+
Object.freeze({ urls: 'stun:stun1.l.google.com:19302' })
|
|
7
|
+
]);
|
|
8
|
+
function listeners() {
|
|
9
|
+
const entries = new Set();
|
|
10
|
+
let closed = false;
|
|
11
|
+
return {
|
|
12
|
+
add(fn, options) {
|
|
13
|
+
const signal = options?.signal;
|
|
14
|
+
if (closed || signal?.aborted)
|
|
15
|
+
return () => { };
|
|
16
|
+
const entry = {
|
|
17
|
+
fn,
|
|
18
|
+
once: Boolean(options?.once),
|
|
19
|
+
off() {
|
|
20
|
+
if (!entries.delete(entry))
|
|
21
|
+
return;
|
|
22
|
+
signal?.removeEventListener('abort', entry.off);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
entries.add(entry);
|
|
26
|
+
signal?.addEventListener('abort', entry.off, { once: true });
|
|
27
|
+
return entry.off;
|
|
28
|
+
},
|
|
29
|
+
fire(...args) {
|
|
30
|
+
for (const entry of [...entries]) {
|
|
31
|
+
if (!entries.has(entry))
|
|
32
|
+
continue;
|
|
33
|
+
if (entry.once)
|
|
34
|
+
entry.off();
|
|
35
|
+
try {
|
|
36
|
+
entry.fn(...args);
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
globalThis.reportError?.(error);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
clear() {
|
|
44
|
+
closed = true;
|
|
45
|
+
for (const entry of [...entries])
|
|
46
|
+
entry.off();
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
const maxPacket = 16 * 1024;
|
|
51
|
+
function asStat(value) {
|
|
52
|
+
return value && typeof value === 'object' ? value : undefined;
|
|
53
|
+
}
|
|
54
|
+
function nonNegativeNumber(value) {
|
|
55
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
|
|
56
|
+
}
|
|
57
|
+
function parsePeerStats(report, bufferedUnreliable, bufferedReliable) {
|
|
58
|
+
const byId = new Map();
|
|
59
|
+
let bytesSent = 0;
|
|
60
|
+
let bytesReceived = 0;
|
|
61
|
+
let selectedId;
|
|
62
|
+
let selectedPair;
|
|
63
|
+
let nominatedPair;
|
|
64
|
+
let succeededPair;
|
|
65
|
+
report.forEach((raw, id) => {
|
|
66
|
+
const stat = asStat(raw);
|
|
67
|
+
if (!stat)
|
|
68
|
+
return;
|
|
69
|
+
byId.set(id, stat);
|
|
70
|
+
if (stat.type === 'data-channel') {
|
|
71
|
+
bytesSent += nonNegativeNumber(stat.bytesSent) ?? 0;
|
|
72
|
+
bytesReceived += nonNegativeNumber(stat.bytesReceived) ?? 0;
|
|
73
|
+
}
|
|
74
|
+
else if (stat.type === 'transport' && typeof stat.selectedCandidatePairId === 'string') {
|
|
75
|
+
selectedId = stat.selectedCandidatePairId;
|
|
76
|
+
}
|
|
77
|
+
else if (stat.type === 'candidate-pair') {
|
|
78
|
+
if (stat.selected === true && !selectedPair)
|
|
79
|
+
selectedPair = stat;
|
|
80
|
+
if (stat.state === 'succeeded') {
|
|
81
|
+
if (stat.nominated === true && !nominatedPair)
|
|
82
|
+
nominatedPair = stat;
|
|
83
|
+
if (!succeededPair)
|
|
84
|
+
succeededPair = stat;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
let activePair;
|
|
89
|
+
if (selectedId) {
|
|
90
|
+
const pair = byId.get(selectedId);
|
|
91
|
+
if (pair?.type === 'candidate-pair')
|
|
92
|
+
activePair = pair;
|
|
93
|
+
}
|
|
94
|
+
activePair ??= selectedPair ?? nominatedPair ?? succeededPair;
|
|
95
|
+
const rttSec = activePair ? nonNegativeNumber(activePair.currentRoundTripTime) : null;
|
|
96
|
+
const rttMs = rttSec !== null ? Math.round(rttSec * 1000) : null;
|
|
97
|
+
let route = 'unknown';
|
|
98
|
+
if (activePair) {
|
|
99
|
+
const local = typeof activePair.localCandidateId === 'string'
|
|
100
|
+
? byId.get(activePair.localCandidateId)
|
|
101
|
+
: undefined;
|
|
102
|
+
const remote = typeof activePair.remoteCandidateId === 'string'
|
|
103
|
+
? byId.get(activePair.remoteCandidateId)
|
|
104
|
+
: undefined;
|
|
105
|
+
const localType = local?.type === 'local-candidate' && typeof local.candidateType === 'string'
|
|
106
|
+
? local.candidateType
|
|
107
|
+
: undefined;
|
|
108
|
+
const remoteType = remote?.type === 'remote-candidate' && typeof remote.candidateType === 'string'
|
|
109
|
+
? remote.candidateType
|
|
110
|
+
: undefined;
|
|
111
|
+
if (localType === 'relay' || remoteType === 'relay')
|
|
112
|
+
route = 'relay';
|
|
113
|
+
else if (localType && remoteType)
|
|
114
|
+
route = 'direct';
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
rttMs,
|
|
118
|
+
route,
|
|
119
|
+
bytesSent,
|
|
120
|
+
bytesReceived,
|
|
121
|
+
bufferedUnreliable,
|
|
122
|
+
bufferedReliable
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const bufferLimit = { unreliable: 64 * 1024, reliable: 256 * 1024 };
|
|
126
|
+
const establishTimeout = 35_000;
|
|
127
|
+
const gatherTimeoutDefault = 2_500;
|
|
128
|
+
const maxPeersDefault = 32;
|
|
129
|
+
const disconnectGrace = 8_000;
|
|
130
|
+
const leaveNotice = 'meshpost/1/leave';
|
|
131
|
+
const rtcControlPrefix = 'meshpost/1/rtc:';
|
|
132
|
+
const maxRtcControlBytes = 64 * 1024;
|
|
133
|
+
const maxRtcQueueDepth = 16;
|
|
134
|
+
const maxRemoteStreamsPerPeer = 32;
|
|
135
|
+
const trickleBatchMs = 50;
|
|
136
|
+
const trickleBatchSize = 16;
|
|
137
|
+
const maxTrickleCandidates = 64;
|
|
138
|
+
/** Start discovery immediately. Membership becomes observable as peer links open. */
|
|
139
|
+
export function joinRoom(name, options) {
|
|
140
|
+
if (typeof name !== 'string' || !/^[a-zA-Z0-9_-]{1,64}$/.test(name))
|
|
141
|
+
throw new TypeError('Invalid room name');
|
|
142
|
+
const appId = options.appId ?? 'meshpost';
|
|
143
|
+
if (typeof appId !== 'string' || !/^[a-zA-Z0-9._-]{1,64}$/.test(appId))
|
|
144
|
+
throw new TypeError('Invalid appId');
|
|
145
|
+
const password = options.password;
|
|
146
|
+
if (password !== undefined && (typeof password !== 'string' || password.length === 0))
|
|
147
|
+
throw new TypeError('Invalid password');
|
|
148
|
+
const timeout = options.handshakeTimeoutMs ?? establishTimeout;
|
|
149
|
+
if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 2_147_483_647)
|
|
150
|
+
throw new RangeError('Invalid handshake timeout');
|
|
151
|
+
const gatherTimeout = options.iceGatheringTimeoutMs ??
|
|
152
|
+
Math.min(gatherTimeoutDefault, Math.max(1, Math.floor(timeout / 2)));
|
|
153
|
+
if (!Number.isSafeInteger(gatherTimeout) || gatherTimeout <= 0 || gatherTimeout > 2_147_483_647)
|
|
154
|
+
throw new RangeError('Invalid ICE gathering timeout');
|
|
155
|
+
const maxPeers = options.maxPeers ?? maxPeersDefault;
|
|
156
|
+
if (!Number.isSafeInteger(maxPeers) || maxPeers <= 0)
|
|
157
|
+
throw new RangeError('Invalid maxPeers limit');
|
|
158
|
+
const baseIceServers = options.rtcConfig?.iceServers ?? defaultIceServers;
|
|
159
|
+
const rtcConfig = {
|
|
160
|
+
...options.rtcConfig,
|
|
161
|
+
iceServers: [...baseIceServers, ...(options.turnConfig ?? [])]
|
|
162
|
+
};
|
|
163
|
+
// Fail fast on malformed browser RTC configuration instead of retrying silently.
|
|
164
|
+
new RTCPeerConnection(rtcConfig).close();
|
|
165
|
+
const needsRelay = rtcConfig.iceTransportPolicy === 'relay';
|
|
166
|
+
const hasTurn = rtcConfig.iceServers?.some((server) => {
|
|
167
|
+
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
|
|
168
|
+
return urls.some((u) => /^turns?:/i.test(u));
|
|
169
|
+
}) ?? false;
|
|
170
|
+
const self = randomUuid();
|
|
171
|
+
const peers = new Map();
|
|
172
|
+
const rejectedFull = new Set();
|
|
173
|
+
const broadcastStreams = new Set();
|
|
174
|
+
const peerStreams = new Map();
|
|
175
|
+
const joins = listeners();
|
|
176
|
+
const leaves = listeners();
|
|
177
|
+
const packets = listeners();
|
|
178
|
+
const drains = listeners();
|
|
179
|
+
const status = listeners();
|
|
180
|
+
const errors = listeners();
|
|
181
|
+
const peerStreamListeners = listeners();
|
|
182
|
+
const peerStreamEndListeners = listeners();
|
|
183
|
+
let state = 'connecting';
|
|
184
|
+
// Start attempt numbers from an unpredictable positive offset so observers cannot guess them.
|
|
185
|
+
let nextAttempt = (crypto.getRandomValues(new Uint32Array(1))[0] & 0x0fffffff) + 1;
|
|
186
|
+
let stopped = false;
|
|
187
|
+
let signaling;
|
|
188
|
+
let useTrickle = false;
|
|
189
|
+
const prepareRemoteSdp = (signal) => rtcConfig.iceTransportPolicy === 'relay' ? signal.sdp : withLoopbackFallback(signal).sdp;
|
|
190
|
+
const prepareRemoteCandidates = (signal) => rtcConfig.iceTransportPolicy === 'relay'
|
|
191
|
+
? signal.candidates
|
|
192
|
+
: withLoopbackFallback(signal).candidates;
|
|
193
|
+
const applyRemoteCandidates = (peer, link, candidates) => {
|
|
194
|
+
for (const item of candidates) {
|
|
195
|
+
if (stopped || peer.link !== link)
|
|
196
|
+
return;
|
|
197
|
+
void link.pc.addIceCandidate(item).catch(() => { });
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
const desiredStreamsFor = (peerId) => {
|
|
201
|
+
const set = new Set(broadcastStreams);
|
|
202
|
+
const targeted = peerStreams.get(peerId);
|
|
203
|
+
if (targeted) {
|
|
204
|
+
for (const s of targeted)
|
|
205
|
+
set.add(s);
|
|
206
|
+
}
|
|
207
|
+
return set;
|
|
208
|
+
};
|
|
209
|
+
const sendRtcControl = (link, payload) => {
|
|
210
|
+
const reliable = link.channels.reliable;
|
|
211
|
+
if (reliable.readyState !== 'open')
|
|
212
|
+
return false;
|
|
213
|
+
try {
|
|
214
|
+
reliable.send(rtcControlPrefix + JSON.stringify(payload));
|
|
215
|
+
return true;
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
};
|
|
221
|
+
const attachStreamToLink = (link, stream) => {
|
|
222
|
+
if (link.senders.has(stream))
|
|
223
|
+
return false;
|
|
224
|
+
const tracks = stream.getTracks();
|
|
225
|
+
if (tracks.length === 0)
|
|
226
|
+
return false;
|
|
227
|
+
const added = [];
|
|
228
|
+
for (const track of tracks) {
|
|
229
|
+
added.push(link.pc.addTrack(track, stream));
|
|
230
|
+
}
|
|
231
|
+
link.senders.set(stream, added);
|
|
232
|
+
link.pendingStreamEnds.delete(stream.id);
|
|
233
|
+
return true;
|
|
234
|
+
};
|
|
235
|
+
const detachStreamFromLink = (link, stream) => {
|
|
236
|
+
const added = link.senders.get(stream);
|
|
237
|
+
if (!added)
|
|
238
|
+
return false;
|
|
239
|
+
link.senders.delete(stream);
|
|
240
|
+
for (const sender of added) {
|
|
241
|
+
try {
|
|
242
|
+
link.pc.removeTrack(sender);
|
|
243
|
+
}
|
|
244
|
+
catch {
|
|
245
|
+
// Ignore if connection is closing.
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
link.pendingStreamEnds.add(stream.id);
|
|
249
|
+
return true;
|
|
250
|
+
};
|
|
251
|
+
const enqueueRenegotiate = (peer, link) => {
|
|
252
|
+
link.renegotiateQueued = true;
|
|
253
|
+
link.rtcQueue = link.rtcQueue.then(async () => {
|
|
254
|
+
if (stopped ||
|
|
255
|
+
peer.link !== link ||
|
|
256
|
+
!link.ready ||
|
|
257
|
+
!link.renegotiateQueued ||
|
|
258
|
+
link.channels.reliable.readyState !== 'open')
|
|
259
|
+
return;
|
|
260
|
+
if (link.pc.signalingState !== 'stable')
|
|
261
|
+
return;
|
|
262
|
+
link.renegotiateQueued = false;
|
|
263
|
+
try {
|
|
264
|
+
const offer = await link.pc.createOffer();
|
|
265
|
+
if (stopped || peer.link !== link)
|
|
266
|
+
return;
|
|
267
|
+
await link.pc.setLocalDescription(offer);
|
|
268
|
+
if (stopped || peer.link !== link || !link.pc.localDescription)
|
|
269
|
+
return;
|
|
270
|
+
if (sendRtcControl(link, { kind: 'offer', sdp: link.pc.localDescription.sdp })) {
|
|
271
|
+
for (const id of link.pendingStreamEnds) {
|
|
272
|
+
sendRtcControl(link, { kind: 'stream-end', id });
|
|
273
|
+
}
|
|
274
|
+
link.pendingStreamEnds.clear();
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
if (!stopped && peer.link === link) {
|
|
279
|
+
errors.fire({
|
|
280
|
+
code: 'media-error',
|
|
281
|
+
peerId: peer.id,
|
|
282
|
+
message: 'Failed to negotiate media tracks'
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
};
|
|
288
|
+
const handleRtcControl = (peer, link, raw) => {
|
|
289
|
+
if (raw.length > maxRtcControlBytes || link.rtcPending >= maxRtcQueueDepth)
|
|
290
|
+
return;
|
|
291
|
+
let msg;
|
|
292
|
+
try {
|
|
293
|
+
const parsed = JSON.parse(raw.slice(rtcControlPrefix.length));
|
|
294
|
+
msg = parsed && typeof parsed === 'object' ? parsed : null;
|
|
295
|
+
}
|
|
296
|
+
catch {
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
if (!msg || typeof msg.kind !== 'string')
|
|
300
|
+
return;
|
|
301
|
+
if (msg.kind === 'stream-end' && typeof msg.id === 'string') {
|
|
302
|
+
const streamId = msg.id;
|
|
303
|
+
link.rtcPending++;
|
|
304
|
+
link.rtcQueue = link.rtcQueue.then(() => {
|
|
305
|
+
link.rtcPending--;
|
|
306
|
+
if (stopped || peer.link !== link || !link.ready)
|
|
307
|
+
return;
|
|
308
|
+
const stream = link.remoteStreams.get(streamId);
|
|
309
|
+
if (stream) {
|
|
310
|
+
link.remoteStreams.delete(streamId);
|
|
311
|
+
peerStreamEndListeners.fire(peer.id, stream);
|
|
312
|
+
}
|
|
313
|
+
});
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if ((msg.kind !== 'offer' && msg.kind !== 'answer') || typeof msg.sdp !== 'string')
|
|
317
|
+
return;
|
|
318
|
+
const kind = msg.kind;
|
|
319
|
+
const sdp = msg.sdp;
|
|
320
|
+
const polite = self > peer.id;
|
|
321
|
+
link.rtcPending++;
|
|
322
|
+
link.rtcQueue = link.rtcQueue.then(async () => {
|
|
323
|
+
try {
|
|
324
|
+
if (stopped || peer.link !== link || !link.ready)
|
|
325
|
+
return;
|
|
326
|
+
if (kind === 'offer') {
|
|
327
|
+
const collision = link.pc.signalingState !== 'stable';
|
|
328
|
+
if (!polite && collision)
|
|
329
|
+
return;
|
|
330
|
+
try {
|
|
331
|
+
if (polite && collision) {
|
|
332
|
+
await link.pc.setLocalDescription({ type: 'rollback' });
|
|
333
|
+
link.renegotiateQueued = true;
|
|
334
|
+
}
|
|
335
|
+
await link.pc.setRemoteDescription({ type: 'offer', sdp });
|
|
336
|
+
if (stopped || peer.link !== link)
|
|
337
|
+
return;
|
|
338
|
+
const answer = await link.pc.createAnswer();
|
|
339
|
+
if (stopped || peer.link !== link)
|
|
340
|
+
return;
|
|
341
|
+
await link.pc.setLocalDescription(answer);
|
|
342
|
+
if (stopped || peer.link !== link || !link.pc.localDescription)
|
|
343
|
+
return;
|
|
344
|
+
sendRtcControl(link, { kind: 'answer', sdp: link.pc.localDescription.sdp });
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
if (!stopped && peer.link === link) {
|
|
348
|
+
errors.fire({
|
|
349
|
+
code: 'media-error',
|
|
350
|
+
peerId: peer.id,
|
|
351
|
+
message: 'Failed to apply media offer'
|
|
352
|
+
});
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
if (!stopped && peer.link === link && link.renegotiateQueued) {
|
|
356
|
+
enqueueRenegotiate(peer, link);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
else {
|
|
360
|
+
if (link.pc.signalingState !== 'have-local-offer')
|
|
361
|
+
return;
|
|
362
|
+
try {
|
|
363
|
+
await link.pc.setRemoteDescription({ type: 'answer', sdp });
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
if (!stopped && peer.link === link) {
|
|
367
|
+
errors.fire({
|
|
368
|
+
code: 'media-error',
|
|
369
|
+
peerId: peer.id,
|
|
370
|
+
message: 'Failed to apply media answer'
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
if (!stopped && peer.link === link && link.renegotiateQueued) {
|
|
375
|
+
enqueueRenegotiate(peer, link);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
link.rtcPending--;
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
};
|
|
384
|
+
function retry(peer) {
|
|
385
|
+
if (stopped || state !== 'online' || !peer.advertised || peer.retry || peer.link)
|
|
386
|
+
return;
|
|
387
|
+
const base = Math.min(8000, 350 * 2 ** Math.min(peer.failures++, 5));
|
|
388
|
+
const delay = Math.round(base * (0.75 + Math.random() * 0.5));
|
|
389
|
+
peer.retry = setTimeout(() => {
|
|
390
|
+
delete peer.retry;
|
|
391
|
+
discover(peer);
|
|
392
|
+
}, delay);
|
|
393
|
+
}
|
|
394
|
+
function drop(peer, link, flushLeave = false, shouldRetry = true) {
|
|
395
|
+
if (peer.link !== link)
|
|
396
|
+
return;
|
|
397
|
+
delete peer.link;
|
|
398
|
+
if (link.accepted)
|
|
399
|
+
peer.previous = link.attempt;
|
|
400
|
+
if (peer.earlyIce?.attempt === link.attempt)
|
|
401
|
+
delete peer.earlyIce;
|
|
402
|
+
clearTimeout(link.deadline);
|
|
403
|
+
clearTimeout(link.gather);
|
|
404
|
+
clearTimeout(link.iceFlush);
|
|
405
|
+
clearTimeout(link.grace);
|
|
406
|
+
const reliable = link.channels.reliable;
|
|
407
|
+
if (flushLeave && reliable.readyState === 'open') {
|
|
408
|
+
// Give SCTP a bounded opportunity to deliver the departure before closing DTLS.
|
|
409
|
+
const closeTimer = setTimeout(() => link.pc.close(), 750);
|
|
410
|
+
reliable.addEventListener('close', () => {
|
|
411
|
+
clearTimeout(closeTimer);
|
|
412
|
+
link.pc.close();
|
|
413
|
+
}, { once: true });
|
|
414
|
+
try {
|
|
415
|
+
reliable.send(leaveNotice);
|
|
416
|
+
reliable.close();
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
clearTimeout(closeTimer);
|
|
420
|
+
link.pc.close();
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
else
|
|
424
|
+
link.pc.close();
|
|
425
|
+
if (!peer.advertised)
|
|
426
|
+
peers.delete(peer.id);
|
|
427
|
+
if (link.ready) {
|
|
428
|
+
for (const stream of [...link.remoteStreams.values()]) {
|
|
429
|
+
peerStreamEndListeners.fire(peer.id, stream);
|
|
430
|
+
}
|
|
431
|
+
link.remoteStreams.clear();
|
|
432
|
+
link.senders.clear();
|
|
433
|
+
link.pendingStreamEnds.clear();
|
|
434
|
+
leaves.fire(peer.id);
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
link.remoteStreams.clear();
|
|
438
|
+
link.senders.clear();
|
|
439
|
+
link.pendingStreamEnds.clear();
|
|
440
|
+
}
|
|
441
|
+
if (shouldRetry)
|
|
442
|
+
retry(peer);
|
|
443
|
+
}
|
|
444
|
+
function createLink(peer, attempt) {
|
|
445
|
+
clearTimeout(peer.retry);
|
|
446
|
+
delete peer.retry;
|
|
447
|
+
const pc = new RTCPeerConnection(rtcConfig);
|
|
448
|
+
// Fixed stream IDs let both endpoints create identical channels without glare.
|
|
449
|
+
let channels;
|
|
450
|
+
try {
|
|
451
|
+
channels = {
|
|
452
|
+
unreliable: pc.createDataChannel('meshpost/1/unreliable', {
|
|
453
|
+
negotiated: true,
|
|
454
|
+
id: 0,
|
|
455
|
+
ordered: false,
|
|
456
|
+
maxRetransmits: 0,
|
|
457
|
+
protocol: appId
|
|
458
|
+
}),
|
|
459
|
+
reliable: pc.createDataChannel('meshpost/1/reliable', {
|
|
460
|
+
negotiated: true,
|
|
461
|
+
id: 1,
|
|
462
|
+
ordered: true,
|
|
463
|
+
protocol: appId
|
|
464
|
+
})
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
catch (error) {
|
|
468
|
+
pc.close();
|
|
469
|
+
throw error;
|
|
470
|
+
}
|
|
471
|
+
const link = {
|
|
472
|
+
pc,
|
|
473
|
+
channels,
|
|
474
|
+
attempt,
|
|
475
|
+
ready: false,
|
|
476
|
+
accepted: false,
|
|
477
|
+
published: false,
|
|
478
|
+
answerApplied: false,
|
|
479
|
+
remoteDescApplied: false,
|
|
480
|
+
pendingCandidates: [],
|
|
481
|
+
rtcQueue: Promise.resolve(),
|
|
482
|
+
rtcPending: 0,
|
|
483
|
+
renegotiateQueued: false,
|
|
484
|
+
pendingStreamEnds: new Set(),
|
|
485
|
+
senders: new Map(),
|
|
486
|
+
remoteStreams: new Map()
|
|
487
|
+
};
|
|
488
|
+
// Attach active local streams before initial createOffer() on the offerer for 0-RTT media setup.
|
|
489
|
+
if (self < peer.id) {
|
|
490
|
+
for (const stream of desiredStreamsFor(peer.id)) {
|
|
491
|
+
attachStreamToLink(link, stream);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
const earlyStreams = [];
|
|
495
|
+
pc.ontrack = (event) => {
|
|
496
|
+
if (stopped || peer.link !== link)
|
|
497
|
+
return;
|
|
498
|
+
const stream = event.streams[0] ?? new MediaStream([event.track]);
|
|
499
|
+
if (link.remoteStreams.has(stream.id) || link.remoteStreams.size >= maxRemoteStreamsPerPeer)
|
|
500
|
+
return;
|
|
501
|
+
link.remoteStreams.set(stream.id, stream);
|
|
502
|
+
if (link.ready)
|
|
503
|
+
peerStreamListeners.fire(peer.id, stream);
|
|
504
|
+
else
|
|
505
|
+
earlyStreams.push(stream);
|
|
506
|
+
};
|
|
507
|
+
const reportIceFailed = (message) => {
|
|
508
|
+
const wasReady = link.ready;
|
|
509
|
+
drop(peer, link);
|
|
510
|
+
if (!stopped && !wasReady && !peer.iceFailedReported) {
|
|
511
|
+
peer.iceFailedReported = true;
|
|
512
|
+
errors.fire({ code: 'ice-failed', peerId: peer.id, message });
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
peer.link = link;
|
|
516
|
+
link.deadline = setTimeout(() => reportIceFailed('Connection handshake timed out'), timeout);
|
|
517
|
+
pc.onconnectionstatechange = () => {
|
|
518
|
+
if (peer.link !== link)
|
|
519
|
+
return;
|
|
520
|
+
if (pc.connectionState === 'failed')
|
|
521
|
+
reportIceFailed('Peer connection failed');
|
|
522
|
+
else if (pc.connectionState === 'closed')
|
|
523
|
+
drop(peer, link);
|
|
524
|
+
else if (pc.connectionState === 'disconnected') {
|
|
525
|
+
link.grace ??= setTimeout(() => drop(peer, link), disconnectGrace);
|
|
526
|
+
}
|
|
527
|
+
else {
|
|
528
|
+
clearTimeout(link.grace);
|
|
529
|
+
delete link.grace;
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
const early = [];
|
|
533
|
+
const earlyRtc = [];
|
|
534
|
+
let earlyBytes = 0;
|
|
535
|
+
for (const delivery of ['unreliable', 'reliable']) {
|
|
536
|
+
const channel = channels[delivery];
|
|
537
|
+
channel.binaryType = 'arraybuffer';
|
|
538
|
+
channel.bufferedAmountLowThreshold = Math.floor(bufferLimit[delivery] / 2);
|
|
539
|
+
channel.onbufferedamountlow = () => {
|
|
540
|
+
if (!stopped && peer.link === link && link.ready)
|
|
541
|
+
drains.fire(peer.id, delivery);
|
|
542
|
+
};
|
|
543
|
+
channel.onclose = () => drop(peer, link);
|
|
544
|
+
channel.onerror = () => drop(peer, link);
|
|
545
|
+
channel.onopen = () => {
|
|
546
|
+
if (stopped || peer.link !== link || link.ready)
|
|
547
|
+
return;
|
|
548
|
+
if (Object.values(channels).every((c) => c.readyState === 'open')) {
|
|
549
|
+
clearTimeout(link.deadline);
|
|
550
|
+
clearTimeout(link.iceFlush);
|
|
551
|
+
delete link.iceFlush;
|
|
552
|
+
link.ready = true;
|
|
553
|
+
peer.failures = 0;
|
|
554
|
+
peer.iceFailedReported = false;
|
|
555
|
+
joins.fire(peer.id);
|
|
556
|
+
for (const stream of earlyStreams) {
|
|
557
|
+
if (peer.link !== link || stopped)
|
|
558
|
+
break;
|
|
559
|
+
peerStreamListeners.fire(peer.id, stream);
|
|
560
|
+
}
|
|
561
|
+
earlyStreams.length = 0;
|
|
562
|
+
for (const raw of earlyRtc) {
|
|
563
|
+
if (peer.link !== link || stopped)
|
|
564
|
+
break;
|
|
565
|
+
handleRtcControl(peer, link, raw);
|
|
566
|
+
}
|
|
567
|
+
earlyRtc.length = 0;
|
|
568
|
+
for (const [bytes, mode] of early) {
|
|
569
|
+
if (peer.link !== link || stopped)
|
|
570
|
+
break;
|
|
571
|
+
packets.fire(peer.id, bytes, mode);
|
|
572
|
+
}
|
|
573
|
+
early.length = 0;
|
|
574
|
+
// Reconcile local streams (attach newly desired ones, detach any removed mid-handshake).
|
|
575
|
+
if (!stopped && peer.link === link) {
|
|
576
|
+
const desired = desiredStreamsFor(peer.id);
|
|
577
|
+
let needsRenegotiate = false;
|
|
578
|
+
for (const stream of desired) {
|
|
579
|
+
if (attachStreamToLink(link, stream))
|
|
580
|
+
needsRenegotiate = true;
|
|
581
|
+
}
|
|
582
|
+
for (const stream of [...link.senders.keys()]) {
|
|
583
|
+
if (!desired.has(stream) && detachStreamFromLink(link, stream)) {
|
|
584
|
+
needsRenegotiate = true;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
if (needsRenegotiate)
|
|
588
|
+
enqueueRenegotiate(peer, link);
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
channel.onmessage = ({ data }) => {
|
|
593
|
+
if (stopped || peer.link !== link)
|
|
594
|
+
return;
|
|
595
|
+
if (data === leaveNotice && delivery === 'reliable') {
|
|
596
|
+
peer.advertised = false;
|
|
597
|
+
drop(peer, link);
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
600
|
+
if (typeof data === 'string' &&
|
|
601
|
+
delivery === 'reliable' &&
|
|
602
|
+
data.startsWith(rtcControlPrefix)) {
|
|
603
|
+
if (link.ready)
|
|
604
|
+
handleRtcControl(peer, link, data);
|
|
605
|
+
else if (earlyRtc.length < 16 && data.length <= maxRtcControlBytes)
|
|
606
|
+
earlyRtc.push(data);
|
|
607
|
+
return;
|
|
608
|
+
}
|
|
609
|
+
if (!(data instanceof ArrayBuffer))
|
|
610
|
+
return;
|
|
611
|
+
if (data.byteLength > maxPacket) {
|
|
612
|
+
if (delivery === 'reliable')
|
|
613
|
+
drop(peer, link);
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const bytes = new Uint8Array(data);
|
|
617
|
+
if (link.ready)
|
|
618
|
+
packets.fire(peer.id, bytes, delivery);
|
|
619
|
+
else if (early.length >= 64 || earlyBytes + bytes.byteLength > 256 * 1024) {
|
|
620
|
+
if (delivery === 'reliable')
|
|
621
|
+
drop(peer, link);
|
|
622
|
+
}
|
|
623
|
+
else {
|
|
624
|
+
early.push([bytes, delivery]);
|
|
625
|
+
earlyBytes += bytes.byteLength;
|
|
626
|
+
}
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
return link;
|
|
630
|
+
}
|
|
631
|
+
async function negotiate(peer, attempt, remoteOffer) {
|
|
632
|
+
if (stopped || !peer.advertised || !signaling)
|
|
633
|
+
return;
|
|
634
|
+
let link;
|
|
635
|
+
try {
|
|
636
|
+
link = createLink(peer, attempt);
|
|
637
|
+
const { pc } = link;
|
|
638
|
+
if (remoteOffer !== undefined) {
|
|
639
|
+
await pc.setRemoteDescription({ type: 'offer', sdp: remoteOffer });
|
|
640
|
+
if (peer.link !== link)
|
|
641
|
+
return;
|
|
642
|
+
link.remoteDescApplied = true;
|
|
643
|
+
if (peer.earlyIce?.attempt === attempt) {
|
|
644
|
+
const earlyCandidates = peer.earlyIce.candidates;
|
|
645
|
+
delete peer.earlyIce;
|
|
646
|
+
applyRemoteCandidates(peer, link, earlyCandidates);
|
|
647
|
+
}
|
|
648
|
+
if (link.pendingCandidates.length > 0) {
|
|
649
|
+
const queued = link.pendingCandidates.splice(0);
|
|
650
|
+
applyRemoteCandidates(peer, link, queued);
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
link.accepted = true;
|
|
654
|
+
const description = remoteOffer === undefined ? await pc.createOffer() : await pc.createAnswer();
|
|
655
|
+
if (peer.link !== link)
|
|
656
|
+
return;
|
|
657
|
+
const current = link;
|
|
658
|
+
const publish = (force = false) => {
|
|
659
|
+
if (current.published || peer.link !== current)
|
|
660
|
+
return;
|
|
661
|
+
if (!force && pc.iceGatheringState !== 'complete')
|
|
662
|
+
return;
|
|
663
|
+
const local = pc.localDescription;
|
|
664
|
+
if (!local || (local.type !== 'offer' && local.type !== 'answer'))
|
|
665
|
+
return;
|
|
666
|
+
clearTimeout(current.gather);
|
|
667
|
+
delete current.gather;
|
|
668
|
+
current.published = true;
|
|
669
|
+
if (!signaling?.send(peer.id, { kind: local.type, attempt, sdp: local.sdp }))
|
|
670
|
+
drop(peer, current);
|
|
671
|
+
};
|
|
672
|
+
if (useTrickle) {
|
|
673
|
+
const outgoing = [];
|
|
674
|
+
let totalQueued = 0;
|
|
675
|
+
let gatheringDone = false;
|
|
676
|
+
const flushIce = () => {
|
|
677
|
+
clearTimeout(current.iceFlush);
|
|
678
|
+
delete current.iceFlush;
|
|
679
|
+
if (!current.published || peer.link !== current || current.ready || stopped)
|
|
680
|
+
return;
|
|
681
|
+
while (outgoing.length > 0) {
|
|
682
|
+
const batch = outgoing.splice(0, trickleBatchSize);
|
|
683
|
+
signaling?.send(peer.id, { kind: 'ice', attempt, candidates: batch });
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
const scheduleFlush = (immediate = false) => {
|
|
687
|
+
if (!current.published || peer.link !== current || current.ready || stopped)
|
|
688
|
+
return;
|
|
689
|
+
if (immediate || outgoing.length >= trickleBatchSize) {
|
|
690
|
+
flushIce();
|
|
691
|
+
}
|
|
692
|
+
else if (!current.iceFlush) {
|
|
693
|
+
current.iceFlush = setTimeout(flushIce, trickleBatchMs);
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
pc.onicecandidate = (event) => {
|
|
697
|
+
if (peer.link !== current || current.ready || stopped)
|
|
698
|
+
return;
|
|
699
|
+
if (!event.candidate) {
|
|
700
|
+
gatheringDone = true;
|
|
701
|
+
if (totalQueued < maxTrickleCandidates) {
|
|
702
|
+
outgoing.push({ candidate: '' });
|
|
703
|
+
totalQueued++;
|
|
704
|
+
}
|
|
705
|
+
scheduleFlush(true);
|
|
706
|
+
return;
|
|
707
|
+
}
|
|
708
|
+
if (totalQueued >= maxTrickleCandidates)
|
|
709
|
+
return;
|
|
710
|
+
outgoing.push({
|
|
711
|
+
candidate: event.candidate.candidate,
|
|
712
|
+
...(event.candidate.sdpMid !== null ? { sdpMid: event.candidate.sdpMid } : {}),
|
|
713
|
+
...(event.candidate.sdpMLineIndex !== null
|
|
714
|
+
? { sdpMLineIndex: event.candidate.sdpMLineIndex }
|
|
715
|
+
: {})
|
|
716
|
+
});
|
|
717
|
+
totalQueued++;
|
|
718
|
+
scheduleFlush(false);
|
|
719
|
+
};
|
|
720
|
+
await pc.setLocalDescription(description);
|
|
721
|
+
if (peer.link !== current)
|
|
722
|
+
return;
|
|
723
|
+
publish(true);
|
|
724
|
+
if (outgoing.length > 0)
|
|
725
|
+
scheduleFlush(gatheringDone);
|
|
726
|
+
}
|
|
727
|
+
else {
|
|
728
|
+
// Send one complete SDP. Publish early after gatherTimeout so unreachable STUN never stalls,
|
|
729
|
+
// while allowing extra time when relay/TURN candidates are required or configured.
|
|
730
|
+
let hasRelay = false;
|
|
731
|
+
let hasSrflx = false;
|
|
732
|
+
let softExpired = false;
|
|
733
|
+
pc.onicecandidate = (event) => {
|
|
734
|
+
if (peer.link !== current || current.published)
|
|
735
|
+
return;
|
|
736
|
+
if (!event.candidate) {
|
|
737
|
+
publish(true);
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
const type = event.candidate.type;
|
|
741
|
+
if (type === 'relay')
|
|
742
|
+
hasRelay = true;
|
|
743
|
+
else if (type === 'srflx')
|
|
744
|
+
hasSrflx = true;
|
|
745
|
+
if (softExpired && (hasRelay || (!needsRelay && hasSrflx))) {
|
|
746
|
+
publish(true);
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
pc.onicegatheringstatechange = () => publish(false);
|
|
750
|
+
await pc.setLocalDescription(description);
|
|
751
|
+
if (peer.link !== current)
|
|
752
|
+
return;
|
|
753
|
+
publish(false);
|
|
754
|
+
if (!current.published) {
|
|
755
|
+
const extendedGather = options.iceGatheringTimeoutMs === undefined
|
|
756
|
+
? Math.min(10_000, Math.floor(timeout / 2))
|
|
757
|
+
: gatherTimeout;
|
|
758
|
+
current.gather = setTimeout(() => {
|
|
759
|
+
softExpired = true;
|
|
760
|
+
const waitingForRelay = (needsRelay && !hasRelay) || (hasTurn && !hasRelay && !hasSrflx);
|
|
761
|
+
if (waitingForRelay && extendedGather > gatherTimeout) {
|
|
762
|
+
current.gather = setTimeout(() => publish(true), extendedGather - gatherTimeout);
|
|
763
|
+
}
|
|
764
|
+
else {
|
|
765
|
+
publish(true);
|
|
766
|
+
}
|
|
767
|
+
}, gatherTimeout);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
catch {
|
|
772
|
+
if (link)
|
|
773
|
+
drop(peer, link);
|
|
774
|
+
else
|
|
775
|
+
retry(peer);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
function discover(peer) {
|
|
779
|
+
if (stopped || !signaling || !peer.advertised || state !== 'online' || peer.link || peer.retry)
|
|
780
|
+
return;
|
|
781
|
+
if (self < peer.id)
|
|
782
|
+
void negotiate(peer, ++nextAttempt);
|
|
783
|
+
else {
|
|
784
|
+
signaling.send(peer.id, { kind: 'need', previous: peer.previous });
|
|
785
|
+
retry(peer);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
function receive(id, signal) {
|
|
789
|
+
if (!isSignal(signal))
|
|
790
|
+
return;
|
|
791
|
+
const peer = peers.get(id);
|
|
792
|
+
if (stopped || !peer?.advertised)
|
|
793
|
+
return;
|
|
794
|
+
const link = peer.link;
|
|
795
|
+
if (signal.kind === 'need') {
|
|
796
|
+
if (self >= id)
|
|
797
|
+
return;
|
|
798
|
+
if (link) {
|
|
799
|
+
if (signal.previous === link.attempt) {
|
|
800
|
+
drop(peer, link, false, false);
|
|
801
|
+
discover(peer);
|
|
802
|
+
}
|
|
803
|
+
else if (!link.ready &&
|
|
804
|
+
!link.answerApplied &&
|
|
805
|
+
link.published &&
|
|
806
|
+
link.pc.signalingState === 'have-local-offer' &&
|
|
807
|
+
link.pc.localDescription?.type === 'offer') {
|
|
808
|
+
if (!signaling?.send(peer.id, {
|
|
809
|
+
kind: 'offer',
|
|
810
|
+
attempt: link.attempt,
|
|
811
|
+
sdp: link.pc.localDescription.sdp
|
|
812
|
+
}))
|
|
813
|
+
drop(peer, link);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
else {
|
|
817
|
+
clearTimeout(peer.retry);
|
|
818
|
+
delete peer.retry;
|
|
819
|
+
discover(peer);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
else if (signal.kind === 'offer') {
|
|
823
|
+
const baseline = link?.attempt ?? peer.previous ?? 0;
|
|
824
|
+
if (self <= id || signal.attempt <= baseline)
|
|
825
|
+
return;
|
|
826
|
+
// Reject extreme attempt jumps once a baseline exists to prevent attempt-space exhaustion DoS.
|
|
827
|
+
if (baseline > 0 && signal.attempt - baseline > 1024)
|
|
828
|
+
return;
|
|
829
|
+
if (link)
|
|
830
|
+
drop(peer, link, false, false);
|
|
831
|
+
void negotiate(peer, signal.attempt, prepareRemoteSdp(signal));
|
|
832
|
+
}
|
|
833
|
+
else if (signal.kind === 'ice') {
|
|
834
|
+
if (link && signal.attempt === link.attempt) {
|
|
835
|
+
const candidates = prepareRemoteCandidates(signal);
|
|
836
|
+
if (link.remoteDescApplied) {
|
|
837
|
+
applyRemoteCandidates(peer, link, candidates);
|
|
838
|
+
}
|
|
839
|
+
else {
|
|
840
|
+
for (const item of candidates) {
|
|
841
|
+
if (link.pendingCandidates.length >= maxTrickleCandidates)
|
|
842
|
+
break;
|
|
843
|
+
link.pendingCandidates.push(item);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
else {
|
|
848
|
+
const baseline = link?.attempt ?? peer.previous ?? 0;
|
|
849
|
+
if (self > id &&
|
|
850
|
+
signal.attempt > baseline &&
|
|
851
|
+
(baseline === 0 || signal.attempt - baseline <= 1024)) {
|
|
852
|
+
if (!peer.earlyIce || signal.attempt > peer.earlyIce.attempt) {
|
|
853
|
+
peer.earlyIce = { attempt: signal.attempt, candidates: [] };
|
|
854
|
+
}
|
|
855
|
+
if (peer.earlyIce.attempt === signal.attempt) {
|
|
856
|
+
for (const item of prepareRemoteCandidates(signal)) {
|
|
857
|
+
if (peer.earlyIce.candidates.length >= maxTrickleCandidates)
|
|
858
|
+
break;
|
|
859
|
+
peer.earlyIce.candidates.push(item);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
else if (signal.kind === 'answer' &&
|
|
866
|
+
self < id &&
|
|
867
|
+
link &&
|
|
868
|
+
!link.answerApplied &&
|
|
869
|
+
link.attempt === signal.attempt &&
|
|
870
|
+
link.pc.signalingState === 'have-local-offer') {
|
|
871
|
+
link.answerApplied = true;
|
|
872
|
+
void link.pc
|
|
873
|
+
.setRemoteDescription({ type: 'answer', sdp: prepareRemoteSdp(signal) })
|
|
874
|
+
.then(() => {
|
|
875
|
+
if (stopped || peer.link !== link)
|
|
876
|
+
return;
|
|
877
|
+
link.remoteDescApplied = true;
|
|
878
|
+
if (link.pendingCandidates.length > 0) {
|
|
879
|
+
const queued = link.pendingCandidates.splice(0);
|
|
880
|
+
applyRemoteCandidates(peer, link, queued);
|
|
881
|
+
}
|
|
882
|
+
})
|
|
883
|
+
.catch(() => drop(peer, link));
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
signaling = options.signaling({
|
|
887
|
+
appId,
|
|
888
|
+
room: name,
|
|
889
|
+
self,
|
|
890
|
+
...(password !== undefined ? { password } : {}),
|
|
891
|
+
receive,
|
|
892
|
+
status(next, reason) {
|
|
893
|
+
if (stopped || next === state)
|
|
894
|
+
return;
|
|
895
|
+
state = next;
|
|
896
|
+
if (next !== 'online') {
|
|
897
|
+
for (const peer of peers.values()) {
|
|
898
|
+
clearTimeout(peer.retry);
|
|
899
|
+
delete peer.retry;
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
status.fire(next, reason);
|
|
903
|
+
if (!stopped && state === 'online') {
|
|
904
|
+
for (const peer of peers.values()) {
|
|
905
|
+
if (peer.advertised && !peer.link) {
|
|
906
|
+
peer.failures = 0;
|
|
907
|
+
discover(peer);
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
},
|
|
912
|
+
error(code, message) {
|
|
913
|
+
if (stopped || (code !== 'decrypt-failed' && code !== 'signaling-error'))
|
|
914
|
+
return;
|
|
915
|
+
errors.fire({
|
|
916
|
+
code,
|
|
917
|
+
message: message ??
|
|
918
|
+
(code === 'decrypt-failed'
|
|
919
|
+
? 'Failed to decrypt signaling message'
|
|
920
|
+
: 'Signaling adapter error')
|
|
921
|
+
});
|
|
922
|
+
},
|
|
923
|
+
roster(ids) {
|
|
924
|
+
if (stopped)
|
|
925
|
+
return;
|
|
926
|
+
const present = new Set(ids);
|
|
927
|
+
for (const id of [...rejectedFull]) {
|
|
928
|
+
if (!present.has(id) || peers.has(id))
|
|
929
|
+
rejectedFull.delete(id);
|
|
930
|
+
}
|
|
931
|
+
for (const peer of peers.values()) {
|
|
932
|
+
peer.advertised = present.has(peer.id);
|
|
933
|
+
if (!peer.advertised) {
|
|
934
|
+
clearTimeout(peer.retry);
|
|
935
|
+
delete peer.retry;
|
|
936
|
+
if (!peer.link)
|
|
937
|
+
peers.delete(peer.id);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
const newlyRejected = [];
|
|
941
|
+
for (const id of present) {
|
|
942
|
+
if (id === self)
|
|
943
|
+
continue;
|
|
944
|
+
let peer = peers.get(id);
|
|
945
|
+
if (!peer) {
|
|
946
|
+
if (peers.size >= maxPeers) {
|
|
947
|
+
if (!rejectedFull.has(id)) {
|
|
948
|
+
rejectedFull.add(id);
|
|
949
|
+
newlyRejected.push(id);
|
|
950
|
+
}
|
|
951
|
+
continue;
|
|
952
|
+
}
|
|
953
|
+
peer = { id, advertised: true, previous: null, failures: 0 };
|
|
954
|
+
peers.set(id, peer);
|
|
955
|
+
}
|
|
956
|
+
discover(peer);
|
|
957
|
+
}
|
|
958
|
+
for (const id of newlyRejected) {
|
|
959
|
+
if (stopped)
|
|
960
|
+
return;
|
|
961
|
+
errors.fire({ code: 'room-full', peerId: id, message: 'Room reached maxPeers limit' });
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
});
|
|
965
|
+
useTrickle = signaling.trickle === true;
|
|
966
|
+
for (const peer of peers.values())
|
|
967
|
+
discover(peer);
|
|
968
|
+
const connected = () => [...peers.values()].filter((p) => p.link?.ready).map((p) => p.id);
|
|
969
|
+
return {
|
|
970
|
+
id: self,
|
|
971
|
+
get peers() {
|
|
972
|
+
return connected();
|
|
973
|
+
},
|
|
974
|
+
get signalingState() {
|
|
975
|
+
return state;
|
|
976
|
+
},
|
|
977
|
+
onPacket: packets.add,
|
|
978
|
+
onDrain: drains.add,
|
|
979
|
+
onPeerJoin: joins.add,
|
|
980
|
+
onPeerLeave: leaves.add,
|
|
981
|
+
onSignalingChange: status.add,
|
|
982
|
+
onError: errors.add,
|
|
983
|
+
onPeerStream: peerStreamListeners.add,
|
|
984
|
+
onPeerStreamEnd: peerStreamEndListeners.add,
|
|
985
|
+
addStream(stream, to) {
|
|
986
|
+
if (stopped)
|
|
987
|
+
throw new Error('Room is closed');
|
|
988
|
+
if (!stream || typeof stream.getTracks !== 'function')
|
|
989
|
+
throw new TypeError('Expected a MediaStream');
|
|
990
|
+
if (to === undefined) {
|
|
991
|
+
broadcastStreams.add(stream);
|
|
992
|
+
for (const peer of peers.values()) {
|
|
993
|
+
const link = peer.link;
|
|
994
|
+
if (link?.ready && attachStreamToLink(link, stream)) {
|
|
995
|
+
enqueueRenegotiate(peer, link);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
else {
|
|
1000
|
+
if (to === self)
|
|
1001
|
+
return;
|
|
1002
|
+
let set = peerStreams.get(to);
|
|
1003
|
+
if (!set) {
|
|
1004
|
+
set = new Set();
|
|
1005
|
+
peerStreams.set(to, set);
|
|
1006
|
+
}
|
|
1007
|
+
set.add(stream);
|
|
1008
|
+
const peer = peers.get(to);
|
|
1009
|
+
const link = peer?.link;
|
|
1010
|
+
if (peer && link?.ready && attachStreamToLink(link, stream)) {
|
|
1011
|
+
enqueueRenegotiate(peer, link);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
},
|
|
1015
|
+
removeStream(stream, to) {
|
|
1016
|
+
if (stopped || !stream)
|
|
1017
|
+
return;
|
|
1018
|
+
if (to === undefined) {
|
|
1019
|
+
if (!broadcastStreams.delete(stream))
|
|
1020
|
+
return;
|
|
1021
|
+
for (const peer of peers.values()) {
|
|
1022
|
+
if (peerStreams.get(peer.id)?.has(stream))
|
|
1023
|
+
continue;
|
|
1024
|
+
const link = peer.link;
|
|
1025
|
+
if (link?.ready && detachStreamFromLink(link, stream)) {
|
|
1026
|
+
enqueueRenegotiate(peer, link);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
else {
|
|
1031
|
+
const set = peerStreams.get(to);
|
|
1032
|
+
if (!set?.delete(stream))
|
|
1033
|
+
return;
|
|
1034
|
+
if (set.size === 0)
|
|
1035
|
+
peerStreams.delete(to);
|
|
1036
|
+
if (broadcastStreams.has(stream))
|
|
1037
|
+
return;
|
|
1038
|
+
const peer = peers.get(to);
|
|
1039
|
+
const link = peer?.link;
|
|
1040
|
+
if (peer && link?.ready && detachStreamFromLink(link, stream)) {
|
|
1041
|
+
enqueueRenegotiate(peer, link);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
},
|
|
1045
|
+
async getStats(peerId) {
|
|
1046
|
+
if (stopped || peerId === self)
|
|
1047
|
+
return null;
|
|
1048
|
+
const peer = peers.get(peerId);
|
|
1049
|
+
const link = peer?.link;
|
|
1050
|
+
if (!peer || !link?.ready)
|
|
1051
|
+
return null;
|
|
1052
|
+
try {
|
|
1053
|
+
const report = await link.pc.getStats();
|
|
1054
|
+
if (stopped || peer.link !== link || !link.ready)
|
|
1055
|
+
return null;
|
|
1056
|
+
return parsePeerStats(report, link.channels.unreliable.bufferedAmount, link.channels.reliable.bufferedAmount);
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
return null;
|
|
1060
|
+
}
|
|
1061
|
+
},
|
|
1062
|
+
send(bytes, { to, delivery = 'unreliable' } = {}) {
|
|
1063
|
+
if (stopped)
|
|
1064
|
+
throw new Error('Room is closed');
|
|
1065
|
+
if (!(bytes instanceof Uint8Array))
|
|
1066
|
+
throw new TypeError('Expected a Uint8Array');
|
|
1067
|
+
if (delivery !== 'unreliable' && delivery !== 'reliable')
|
|
1068
|
+
throw new TypeError('Invalid delivery mode');
|
|
1069
|
+
const result = new Map();
|
|
1070
|
+
const targets = to === undefined ? connected() : [to];
|
|
1071
|
+
for (const id of targets) {
|
|
1072
|
+
const link = peers.get(id)?.link;
|
|
1073
|
+
const channel = link?.channels[delivery];
|
|
1074
|
+
if (!link?.ready || channel?.readyState !== 'open')
|
|
1075
|
+
result.set(id, 'unavailable');
|
|
1076
|
+
else if (bytes.byteLength > Math.min(maxPacket, link.pc.sctp?.maxMessageSize || Infinity))
|
|
1077
|
+
result.set(id, 'too-large');
|
|
1078
|
+
else if (channel.bufferedAmount + bytes.byteLength > bufferLimit[delivery])
|
|
1079
|
+
result.set(id, 'busy');
|
|
1080
|
+
else {
|
|
1081
|
+
try {
|
|
1082
|
+
// Copy shared memory views to a browser-supported non-shared buffer.
|
|
1083
|
+
channel.send(bytes.buffer instanceof ArrayBuffer
|
|
1084
|
+
? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
1085
|
+
: Uint8Array.from(bytes));
|
|
1086
|
+
result.set(id, 'accepted');
|
|
1087
|
+
}
|
|
1088
|
+
catch (error) {
|
|
1089
|
+
result.set(id, error instanceof DOMException && error.name === 'OperationError'
|
|
1090
|
+
? 'busy'
|
|
1091
|
+
: 'unavailable');
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
return result;
|
|
1096
|
+
},
|
|
1097
|
+
leave() {
|
|
1098
|
+
if (stopped)
|
|
1099
|
+
return;
|
|
1100
|
+
stopped = true;
|
|
1101
|
+
const wasClosed = state === 'closed';
|
|
1102
|
+
state = 'closed';
|
|
1103
|
+
signaling?.close();
|
|
1104
|
+
for (const peer of peers.values()) {
|
|
1105
|
+
peer.advertised = false;
|
|
1106
|
+
clearTimeout(peer.retry);
|
|
1107
|
+
delete peer.retry;
|
|
1108
|
+
if (peer.link)
|
|
1109
|
+
drop(peer, peer.link, true, false);
|
|
1110
|
+
}
|
|
1111
|
+
peers.clear();
|
|
1112
|
+
rejectedFull.clear();
|
|
1113
|
+
broadcastStreams.clear();
|
|
1114
|
+
peerStreams.clear();
|
|
1115
|
+
if (!wasClosed)
|
|
1116
|
+
status.fire('closed');
|
|
1117
|
+
for (const group of [
|
|
1118
|
+
joins,
|
|
1119
|
+
leaves,
|
|
1120
|
+
packets,
|
|
1121
|
+
drains,
|
|
1122
|
+
status,
|
|
1123
|
+
errors,
|
|
1124
|
+
peerStreamListeners,
|
|
1125
|
+
peerStreamEndListeners
|
|
1126
|
+
])
|
|
1127
|
+
group.clear();
|
|
1128
|
+
}
|
|
1129
|
+
};
|
|
1130
|
+
}
|