@dxos/network-manager 0.3.7 → 0.3.8-main.0ae9c21

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.
@@ -1,13 +1,8 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
- };
11
6
  var __export = (target, all) => {
12
7
  for (var name in all)
13
8
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -20,4253 +15,43 @@ var __copyProps = (to, from, except, desc) => {
20
15
  }
21
16
  return to;
22
17
  };
23
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
- // If the importer is in node compatibility mode or this is not an ESM
25
- // file that has been converted to a CommonJS file using a Babel-
26
- // compatible transform (i.e. "__esModule" has not been set), then set
27
- // "default" to the CommonJS "module.exports" for node compatibility.
28
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
- mod
30
- ));
31
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
-
33
- // packages/core/mesh/network-manager/src/transport/datachannel/rtc-ice-candidate.ts
34
- var IceCandidate;
35
- var init_rtc_ice_candidate = __esm({
36
- "packages/core/mesh/network-manager/src/transport/datachannel/rtc-ice-candidate.ts"() {
37
- "use strict";
38
- IceCandidate = class {
39
- constructor(init) {
40
- if (init.candidate == null) {
41
- throw new DOMException("candidate must be specified");
42
- }
43
- this.candidate = init.candidate;
44
- this.sdpMLineIndex = init.sdpMLineIndex ?? null;
45
- this.sdpMid = init.sdpMid ?? null;
46
- this.usernameFragment = init.usernameFragment ?? null;
47
- this.address = null;
48
- this.component = null;
49
- this.foundation = null;
50
- this.port = null;
51
- this.priority = null;
52
- this.protocol = null;
53
- this.relatedAddress = null;
54
- this.relatedPort = null;
55
- this.tcpType = null;
56
- this.type = null;
57
- }
58
- toJSON() {
59
- return {
60
- candidate: this.candidate,
61
- sdpMLineIndex: this.sdpMLineIndex,
62
- sdpMid: this.sdpMid,
63
- usernameFragment: this.usernameFragment
64
- };
65
- }
66
- };
67
- }
68
- });
69
-
70
- // packages/core/mesh/network-manager/src/transport/datachannel/rtc-data-channel.ts
71
- var DataChannel;
72
- var init_rtc_data_channel = __esm({
73
- "packages/core/mesh/network-manager/src/transport/datachannel/rtc-data-channel.ts"() {
74
- "use strict";
75
- DataChannel = class extends EventTarget {
76
- constructor(dataChannel, dataChannelDict = {}) {
77
- super();
78
- this.#dataChannel = dataChannel;
79
- this.#readyState = "connecting";
80
- this.#bufferedAmountLowThreshold = 0;
81
- this.binaryType = "arraybuffer";
82
- this.#dataChannel.onOpen(() => {
83
- this.#readyState = "open";
84
- this.dispatchEvent(new Event("open"));
85
- });
86
- this.#dataChannel.onClosed(() => {
87
- this.#readyState = "closed";
88
- this.dispatchEvent(new Event("close"));
89
- });
90
- this.#dataChannel.onError((msg) => {
91
- this.#readyState = "closed";
92
- this.dispatchEvent(new RTCErrorEvent("error", {
93
- error: new RTCError({
94
- errorDetail: "data-channel-failure"
95
- }, msg)
96
- }));
97
- });
98
- this.#dataChannel.onBufferedAmountLow(() => {
99
- this.dispatchEvent(new Event("bufferedamountlow"));
100
- });
101
- this.#dataChannel.onMessage((data) => {
102
- if (typeof data === "string") {
103
- data = Buffer.from(data);
104
- }
105
- this.dispatchEvent(new MessageEvent("message", {
106
- data
107
- }));
108
- });
109
- this.addEventListener("message", (event) => {
110
- this.onmessage?.(event);
111
- });
112
- this.addEventListener("bufferedamountlow", (event) => {
113
- this.onbufferedamountlow?.(event);
114
- });
115
- this.addEventListener("error", (event) => {
116
- this.onerror?.(event);
117
- });
118
- this.addEventListener("close", (event) => {
119
- this.onclose?.(event);
120
- });
121
- this.addEventListener("closing", (event) => {
122
- this.onclosing?.(event);
123
- });
124
- this.addEventListener("open", (event) => {
125
- this.onopen?.(event);
126
- });
127
- this.onbufferedamountlow = null;
128
- this.onclose = null;
129
- this.onclosing = null;
130
- this.onerror = null;
131
- this.onmessage = null;
132
- this.onopen = null;
133
- this.maxPacketLifeTime = dataChannelDict.maxPacketLifeTime ?? null;
134
- this.maxRetransmits = dataChannelDict.maxRetransmits ?? null;
135
- this.negotiated = dataChannelDict.negotiated ?? false;
136
- this.ordered = dataChannelDict.ordered ?? true;
137
- }
138
- #dataChannel;
139
- #bufferedAmountLowThreshold;
140
- #readyState;
141
- get id() {
142
- return this.#dataChannel.getId();
143
- }
144
- get label() {
145
- return this.#dataChannel.getLabel();
146
- }
147
- get protocol() {
148
- return this.#dataChannel.getProtocol();
149
- }
150
- get bufferedAmount() {
151
- return this.#dataChannel.bufferedAmount();
152
- }
153
- set bufferedAmountLowThreshold(threshold) {
154
- this.#bufferedAmountLowThreshold = threshold;
155
- this.#dataChannel.setBufferedAmountLowThreshold(threshold);
156
- }
157
- get bufferedAmountLowThreshold() {
158
- return this.#bufferedAmountLowThreshold;
159
- }
160
- get readyState() {
161
- return this.#readyState;
162
- }
163
- close() {
164
- this.#readyState = "closing";
165
- this.dispatchEvent(new Event("closing"));
166
- this.#dataChannel.close();
167
- }
168
- send(data) {
169
- if (typeof data === "string") {
170
- this.#dataChannel.sendMessage(data);
171
- } else {
172
- this.#dataChannel.sendMessageBinary(data);
173
- }
174
- }
175
- };
176
- }
177
- });
178
-
179
- // packages/core/mesh/network-manager/src/transport/datachannel/rtc-events.ts
180
- var PeerConnectionIceEvent, DataChannelEvent;
181
- var init_rtc_events = __esm({
182
- "packages/core/mesh/network-manager/src/transport/datachannel/rtc-events.ts"() {
183
- "use strict";
184
- PeerConnectionIceEvent = class extends Event {
185
- constructor(candidate) {
186
- super("icecandidate");
187
- this.candidate = candidate;
188
- }
189
- };
190
- DataChannelEvent = class extends Event {
191
- constructor(channel) {
192
- super("datachannel");
193
- this.channel = channel;
194
- }
195
- };
196
- }
197
- });
198
-
199
- // packages/core/mesh/network-manager/src/transport/datachannel/rtc-session-description.ts
200
- var SessionDescription;
201
- var init_rtc_session_description = __esm({
202
- "packages/core/mesh/network-manager/src/transport/datachannel/rtc-session-description.ts"() {
203
- "use strict";
204
- SessionDescription = class {
205
- constructor(init) {
206
- this.sdp = init.sdp ?? "";
207
- this.type = init.type;
208
- }
209
- toJSON() {
210
- return {
211
- sdp: this.sdp,
212
- type: this.type
213
- };
214
- }
215
- };
216
- }
217
- });
218
-
219
- // packages/core/mesh/network-manager/src/transport/datachannel/rtc-peer-connection.ts
220
- var import_node_datachannel, import_p_defer, PeerConnection, assertState, toSessionDescription, RTCPeerConnectionStates, RTCSdpTypes, RTCIceConnectionStates, RTCIceGatheringStates, RTCSignalingStates;
221
- var init_rtc_peer_connection = __esm({
222
- "packages/core/mesh/network-manager/src/transport/datachannel/rtc-peer-connection.ts"() {
223
- "use strict";
224
- import_node_datachannel = __toESM(require("node-datachannel"));
225
- import_p_defer = __toESM(require("p-defer"));
226
- init_rtc_data_channel();
227
- init_rtc_events();
228
- init_rtc_ice_candidate();
229
- init_rtc_session_description();
230
- PeerConnection = class extends EventTarget {
231
- constructor(init = {}) {
232
- super();
233
- this.#config = init;
234
- this.#localOffer = (0, import_p_defer.default)();
235
- this.#localAnswer = (0, import_p_defer.default)();
236
- this.#dataChannels = /* @__PURE__ */ new Set();
237
- const iceServers = init.iceServers ?? [];
238
- this.#peerConnection = new import_node_datachannel.default.PeerConnection(`peer-${Math.random()}`, {
239
- iceServers: iceServers.map((server) => {
240
- const urls = (Array.isArray(server.urls) ? server.urls : [
241
- server.urls
242
- ]).map((str) => new URL(str));
243
- return urls.map((url) => {
244
- const iceServer = {
245
- hostname: url.hostname,
246
- port: parseInt(url.port, 10),
247
- username: server.username,
248
- password: server.credential
249
- };
250
- return iceServer;
251
- });
252
- }).flat(),
253
- iceTransportPolicy: init?.iceTransportPolicy
254
- });
255
- this.#peerConnection.onStateChange(() => {
256
- this.dispatchEvent(new Event("connectionstatechange"));
257
- });
258
- this.#peerConnection.onGatheringStateChange(() => {
259
- this.dispatchEvent(new Event("icegatheringstatechange"));
260
- });
261
- this.#peerConnection.onDataChannel((channel) => {
262
- this.dispatchEvent(new DataChannelEvent(new DataChannel(channel)));
263
- });
264
- this.addEventListener("connectionstatechange", (event) => {
265
- this.onconnectionstatechange?.(event);
266
- });
267
- this.addEventListener("signalingstatechange", (event) => {
268
- this.onsignalingstatechange?.(event);
269
- });
270
- this.addEventListener("icegatheringstatechange", (event) => {
271
- this.onicegatheringstatechange?.(event);
272
- });
273
- this.addEventListener("datachannel", (event) => {
274
- this.ondatachannel?.(event);
275
- });
276
- this.#peerConnection.onLocalDescription((sdp, type) => {
277
- if (type === "offer") {
278
- this.#localOffer.resolve({
279
- sdp,
280
- type
281
- });
282
- }
283
- if (type === "answer") {
284
- this.#localAnswer.resolve({
285
- sdp,
286
- type
287
- });
288
- }
289
- });
290
- this.#peerConnection.onLocalCandidate((candidate, mid) => {
291
- if (mid === "unspec") {
292
- this.#localAnswer.reject(new Error(`Invalid description type ${mid}`));
293
- return;
294
- }
295
- const event = new PeerConnectionIceEvent(new IceCandidate({
296
- candidate
297
- }));
298
- this.onicecandidate?.(event);
299
- });
300
- this.canTrickleIceCandidates = null;
301
- this.sctp = null;
302
- this.onconnectionstatechange = null;
303
- this.ondatachannel = null;
304
- this.onicecandidate = null;
305
- this.onicecandidateerror = null;
306
- this.oniceconnectionstatechange = null;
307
- this.onicegatheringstatechange = null;
308
- this.onnegotiationneeded = null;
309
- this.onsignalingstatechange = null;
310
- this.ontrack = null;
311
- }
312
- static async generateCertificate(keygenAlgorithm) {
313
- throw new Error("Not implemented");
314
- }
315
- #peerConnection;
316
- #config;
317
- #localOffer;
318
- #localAnswer;
319
- #dataChannels;
320
- get connectionState() {
321
- return assertState(this.#peerConnection.state(), RTCPeerConnectionStates);
322
- }
323
- get iceConnectionState() {
324
- return assertState(this.#peerConnection.state(), RTCIceConnectionStates);
325
- }
326
- get iceGatheringState() {
327
- return assertState(this.#peerConnection.gatheringState(), RTCIceGatheringStates);
328
- }
329
- get signalingState() {
330
- return assertState(this.#peerConnection.signalingState(), RTCSignalingStates);
331
- }
332
- get currentLocalDescription() {
333
- return toSessionDescription(this.#peerConnection.localDescription());
334
- }
335
- get localDescription() {
336
- return toSessionDescription(this.#peerConnection.localDescription());
337
- }
338
- get pendingLocalDescription() {
339
- return toSessionDescription(this.#peerConnection.localDescription());
340
- }
341
- get currentRemoteDescription() {
342
- console.log("node-datachannel doesn't expose currentRemoteDescription");
343
- return toSessionDescription(null);
344
- }
345
- get pendingRemoteDescription() {
346
- console.log("node-datachannel doesn't expose pendingRemoteDescription");
347
- return toSessionDescription(null);
348
- }
349
- get remoteDescription() {
350
- console.log("node-datachannel doesn't expose remoteDescription");
351
- return toSessionDescription(null);
352
- }
353
- async addIceCandidate(candidate) {
354
- if (candidate == null || candidate.candidate == null) {
355
- throw new Error("Candidate invalid");
356
- }
357
- this.#peerConnection.addRemoteCandidate(candidate.candidate, candidate.sdpMid ?? "0");
358
- }
359
- addTrack(track, ...streams) {
360
- throw new Error("addTrack Not implemented");
361
- }
362
- addTransceiver(trackOrKind, init) {
363
- throw new Error("addTransciever Not implemented");
364
- }
365
- close() {
366
- this.#dataChannels.forEach((channel) => {
367
- channel.close();
368
- });
369
- this.#peerConnection.close();
370
- this.#peerConnection.destroy();
371
- }
372
- createDataChannel(label, dataChannelDict = {}) {
373
- const channel = this.#peerConnection.createDataChannel(label, dataChannelDict);
374
- const dataChannel = new DataChannel(channel, dataChannelDict);
375
- this.#dataChannels.add(dataChannel);
376
- dataChannel.addEventListener("close", () => {
377
- this.#dataChannels.delete(dataChannel);
378
- });
379
- return dataChannel;
380
- }
381
- async createOffer(...args) {
382
- return this.#localOffer.promise;
383
- }
384
- async createAnswer(...args) {
385
- return this.#localAnswer.promise;
386
- }
387
- getConfiguration() {
388
- return this.#config;
389
- }
390
- getReceivers() {
391
- throw new Error("getReceivers Not implemented");
392
- }
393
- getSenders() {
394
- throw new Error("getSenders Not implemented");
395
- }
396
- async getStats(selector) {
397
- throw new Error("getStats Not implemented");
398
- }
399
- getTransceivers() {
400
- throw new Error("getTranscievers Not implemented");
401
- }
402
- removeTrack(sender) {
403
- throw new Error("removeTrack Not implemented");
404
- }
405
- restartIce() {
406
- throw new Error("restartIce Not implemented");
407
- }
408
- setConfiguration(configuration = {}) {
409
- this.#config = configuration;
410
- }
411
- async setLocalDescription(description) {
412
- if (description == null || description.type == null) {
413
- throw new Error("Local description type must be set");
414
- }
415
- if (description.type !== "offer") {
416
- console.log(`node-datachannel: setLocalDescription: only offer is supported, not ${description.type}`);
417
- return;
418
- }
419
- this.#peerConnection.setLocalDescription(description.type);
420
- }
421
- async setRemoteDescription(description) {
422
- if (description.sdp == null) {
423
- throw new Error("Remote SDP must be set");
424
- }
425
- this.#peerConnection.setRemoteDescription(description.sdp, description.type);
426
- }
427
- };
428
- assertState = (state, states) => {
429
- if (state != null && !states.includes(state)) {
430
- throw new Error(`Invalid value encountered - "${state}" must be one of ${states}`);
431
- }
432
- return state;
433
- };
434
- toSessionDescription = (description) => {
435
- if (description == null) {
436
- return null;
437
- }
438
- return new SessionDescription({
439
- sdp: description.sdp,
440
- type: assertState(description.type, RTCSdpTypes)
441
- });
442
- };
443
- RTCPeerConnectionStates = [
444
- "closed",
445
- "connected",
446
- "connecting",
447
- "disconnected",
448
- "failed",
449
- "new"
450
- ];
451
- RTCSdpTypes = [
452
- "answer",
453
- "offer",
454
- "pranswer",
455
- "rollback"
456
- ];
457
- RTCIceConnectionStates = [
458
- "checking",
459
- "closed",
460
- "completed",
461
- "connected",
462
- "disconnected",
463
- "failed",
464
- "new"
465
- ];
466
- RTCIceGatheringStates = [
467
- "complete",
468
- "gathering",
469
- "new"
470
- ];
471
- RTCSignalingStates = [
472
- "closed",
473
- "have-local-offer",
474
- "have-local-pranswer",
475
- "have-remote-offer",
476
- "have-remote-pranswer",
477
- "stable"
478
- ];
479
- }
480
- });
481
-
482
- // packages/core/mesh/network-manager/src/transport/datachannel/index.ts
483
- var datachannel_exports = {};
484
- __export(datachannel_exports, {
485
- RTCIceCandidate: () => IceCandidate,
486
- RTCPeerConnection: () => PeerConnection,
487
- RTCSessionDescription: () => SessionDescription,
488
- cleanup: () => cleanup
19
+ var node_exports = {};
20
+ __export(node_exports, {
21
+ Connection: () => import_chunk_PWHTYBOL.Connection,
22
+ ConnectionLimiter: () => import_chunk_PWHTYBOL.ConnectionLimiter,
23
+ ConnectionLog: () => import_chunk_PWHTYBOL.ConnectionLog,
24
+ ConnectionState: () => import_chunk_PWHTYBOL.ConnectionState,
25
+ EventType: () => import_chunk_PWHTYBOL.EventType,
26
+ FullyConnectedTopology: () => import_chunk_PWHTYBOL.FullyConnectedTopology,
27
+ LibDataChannelTransport: () => import_chunk_PWHTYBOL.LibDataChannelTransport,
28
+ MAX_CONCURRENT_INITIATING_CONNECTIONS: () => import_chunk_PWHTYBOL.MAX_CONCURRENT_INITIATING_CONNECTIONS,
29
+ MMSTTopology: () => import_chunk_PWHTYBOL.MMSTTopology,
30
+ MemoryTransport: () => import_chunk_PWHTYBOL.MemoryTransport,
31
+ MemoryTransportFactory: () => import_chunk_PWHTYBOL.MemoryTransportFactory,
32
+ NetworkManager: () => import_chunk_PWHTYBOL.NetworkManager,
33
+ RTCIceCandidate: () => import_chunk_XE5JOIGD.IceCandidate,
34
+ RTCPeerConnection: () => import_chunk_XE5JOIGD.PeerConnection,
35
+ RTCSessionDescription: () => import_chunk_XE5JOIGD.SessionDescription,
36
+ SimplePeerTransport: () => import_chunk_PWHTYBOL.SimplePeerTransport,
37
+ SimplePeerTransportProxy: () => import_chunk_PWHTYBOL.SimplePeerTransportProxy,
38
+ SimplePeerTransportProxyFactory: () => import_chunk_PWHTYBOL.SimplePeerTransportProxyFactory,
39
+ SimplePeerTransportService: () => import_chunk_PWHTYBOL.SimplePeerTransportService,
40
+ StarTopology: () => import_chunk_PWHTYBOL.StarTopology,
41
+ Swarm: () => import_chunk_PWHTYBOL.Swarm,
42
+ SwarmMapper: () => import_chunk_PWHTYBOL.SwarmMapper,
43
+ SwarmMessenger: () => import_chunk_PWHTYBOL.SwarmMessenger,
44
+ TcpTransport: () => import_chunk_PWHTYBOL.TcpTransport,
45
+ TcpTransportFactory: () => import_chunk_PWHTYBOL.TcpTransportFactory,
46
+ TransportKind: () => import_chunk_PWHTYBOL.TransportKind,
47
+ cleanup: () => import_chunk_XE5JOIGD.cleanup,
48
+ createLibDataChannelTransportFactory: () => import_chunk_PWHTYBOL.createLibDataChannelTransportFactory,
49
+ createSimplePeerTransportFactory: () => import_chunk_PWHTYBOL.createSimplePeerTransportFactory,
50
+ createTeleportProtocolFactory: () => import_chunk_PWHTYBOL.createTeleportProtocolFactory
489
51
  });
490
- var import_node_datachannel2, cleanup;
491
- var init_datachannel = __esm({
492
- "packages/core/mesh/network-manager/src/transport/datachannel/index.ts"() {
493
- "use strict";
494
- import_node_datachannel2 = __toESM(require("node-datachannel"));
495
- init_rtc_ice_candidate();
496
- init_rtc_peer_connection();
497
- init_rtc_session_description();
498
- cleanup = () => {
499
- import_node_datachannel2.default.cleanup();
500
- };
501
- }
502
- });
503
-
504
- // packages/core/mesh/network-manager/src/index.ts
505
- var src_exports = {};
506
- __export(src_exports, {
507
- Connection: () => Connection,
508
- ConnectionLimiter: () => ConnectionLimiter,
509
- ConnectionLog: () => ConnectionLog,
510
- ConnectionState: () => ConnectionState,
511
- EventType: () => EventType,
512
- FullyConnectedTopology: () => FullyConnectedTopology,
513
- LibDataChannelTransport: () => LibDataChannelTransport,
514
- MAX_CONCURRENT_INITIATING_CONNECTIONS: () => MAX_CONCURRENT_INITIATING_CONNECTIONS,
515
- MMSTTopology: () => MMSTTopology,
516
- MemoryTransport: () => MemoryTransport,
517
- MemoryTransportFactory: () => MemoryTransportFactory,
518
- NetworkManager: () => NetworkManager,
519
- RTCIceCandidate: () => IceCandidate,
520
- RTCPeerConnection: () => PeerConnection,
521
- RTCSessionDescription: () => SessionDescription,
522
- SimplePeerTransport: () => SimplePeerTransport,
523
- SimplePeerTransportProxy: () => SimplePeerTransportProxy,
524
- SimplePeerTransportProxyFactory: () => SimplePeerTransportProxyFactory,
525
- SimplePeerTransportService: () => SimplePeerTransportService,
526
- StarTopology: () => StarTopology,
527
- Swarm: () => Swarm,
528
- SwarmMapper: () => SwarmMapper,
529
- SwarmMessenger: () => SwarmMessenger,
530
- TcpTransport: () => TcpTransport,
531
- TcpTransportFactory: () => TcpTransportFactory,
532
- TransportKind: () => TransportKind,
533
- cleanup: () => cleanup,
534
- createLibDataChannelTransportFactory: () => createLibDataChannelTransportFactory,
535
- createSimplePeerTransportFactory: () => createSimplePeerTransportFactory,
536
- createTeleportProtocolFactory: () => createTeleportProtocolFactory
537
- });
538
- module.exports = __toCommonJS(src_exports);
539
-
540
- // packages/core/mesh/network-manager/src/connection-log.ts
541
- var import_async6 = require("@dxos/async");
542
- var import_debug3 = require("@dxos/debug");
543
- var import_keys7 = require("@dxos/keys");
544
- var import_util5 = require("@dxos/util");
545
-
546
- // packages/core/mesh/network-manager/src/swarm/connection.ts
547
- var import_async = require("@dxos/async");
548
- var import_context = require("@dxos/context");
549
- var import_debug = require("@dxos/debug");
550
- var import_invariant = require("@dxos/invariant");
551
- var import_keys = require("@dxos/keys");
552
- var import_log = require("@dxos/log");
553
- var import_protocols = require("@dxos/protocols");
554
- function _ts_decorate(decorators, target, key, desc) {
555
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
556
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
557
- r = Reflect.decorate(decorators, target, key, desc);
558
- else
559
- for (var i = decorators.length - 1; i >= 0; i--)
560
- if (d = decorators[i])
561
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
562
- return c > 3 && r && Object.defineProperty(target, key, r), r;
563
- }
564
- var __dxlog_file = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/swarm/connection.ts";
565
- var STARTING_SIGNALLING_DELAY = 10;
566
- var TRANSPORT_CONNECTION_TIMEOUT = 1e4;
567
- var MAX_SIGNALLING_DELAY = 300;
568
- var ConnectionState;
569
- (function(ConnectionState5) {
570
- ConnectionState5[
571
- /**
572
- * Connection is created, but not yet passed through the connection limiter.
573
- */
574
- "CREATED"
575
- ] = "CREATED";
576
- ConnectionState5[
577
- /**
578
- * Initial state. Connection is registered but no attempt to connect to the remote peer has been performed.
579
- * Might mean that we are waiting for the answer signal from the remote peer.
580
- */
581
- "INITIAL"
582
- ] = "INITIAL";
583
- ConnectionState5[
584
- /**
585
- * Trying to establish connection.
586
- */
587
- "CONNECTING"
588
- ] = "CONNECTING";
589
- ConnectionState5[
590
- /**
591
- * Connection is established.
592
- */
593
- "CONNECTED"
594
- ] = "CONNECTED";
595
- ConnectionState5[
596
- /**
597
- * Connection is being closed.
598
- */
599
- "CLOSING"
600
- ] = "CLOSING";
601
- ConnectionState5[
602
- /**
603
- * Connection closed.
604
- */
605
- "CLOSED"
606
- ] = "CLOSED";
607
- ConnectionState5["ABORTING"] = "ABORTING";
608
- ConnectionState5["ABORTED"] = "ABORTED";
609
- })(ConnectionState || (ConnectionState = {}));
610
- var Connection = class {
611
- constructor(topic, ownId, remoteId, sessionId, initiator, _signalMessaging, _protocol, _transportFactory, _callbacks) {
612
- this.topic = topic;
613
- this.ownId = ownId;
614
- this.remoteId = remoteId;
615
- this.sessionId = sessionId;
616
- this.initiator = initiator;
617
- this._signalMessaging = _signalMessaging;
618
- this._protocol = _protocol;
619
- this._transportFactory = _transportFactory;
620
- this._callbacks = _callbacks;
621
- this._ctx = new import_context.Context();
622
- this.connectedTimeoutContext = new import_context.Context();
623
- this._state = ConnectionState.CREATED;
624
- this._incomingSignalBuffer = [];
625
- this._outgoingSignalBuffer = [];
626
- this.stateChanged = new import_async.Event();
627
- this.errors = new import_debug.ErrorStream();
628
- this._instanceId = import_keys.PublicKey.random().toHex();
629
- this._signalSendTask = new import_async.DeferredTask(this._ctx, async () => {
630
- await this._flushSignalBuffer();
631
- });
632
- this._signallingDelay = STARTING_SIGNALLING_DELAY;
633
- import_log.log.trace("dxos.mesh.connection.construct", {
634
- sessionId: this.sessionId,
635
- topic: this.topic,
636
- localPeerId: this.ownId,
637
- remotePeerId: this.remoteId,
638
- initiator: this.initiator
639
- }, {
640
- F: __dxlog_file,
641
- L: 129,
642
- S: this,
643
- C: (f, a) => f(...a)
644
- });
645
- }
646
- get state() {
647
- return this._state;
648
- }
649
- get transport() {
650
- return this._transport;
651
- }
652
- get protocol() {
653
- return this._protocol;
654
- }
655
- /**
656
- * Create an underlying transport and prepares it for the connection.
657
- */
658
- async openConnection() {
659
- (0, import_invariant.invariant)(this._state === ConnectionState.INITIAL, "Invalid state.", {
660
- F: __dxlog_file,
661
- L: 154,
662
- S: this,
663
- A: [
664
- "this._state === ConnectionState.INITIAL",
665
- "'Invalid state.'"
666
- ]
667
- });
668
- import_log.log.trace("dxos.mesh.connection.open-connection", import_protocols.trace.begin({
669
- id: this._instanceId
670
- }), {
671
- F: __dxlog_file,
672
- L: 155,
673
- S: this,
674
- C: (f, a) => f(...a)
675
- });
676
- import_log.log.trace("dxos.mesh.connection.open", {
677
- sessionId: this.sessionId,
678
- topic: this.topic,
679
- localPeerId: this.ownId,
680
- remotePeerId: this.remoteId,
681
- initiator: this.initiator
682
- }, {
683
- F: __dxlog_file,
684
- L: 156,
685
- S: this,
686
- C: (f, a) => f(...a)
687
- });
688
- this._changeState(ConnectionState.CONNECTING);
689
- this._protocol.open().catch((err) => {
690
- this.errors.raise(err);
691
- });
692
- this._protocol.stream.on("close", () => {
693
- (0, import_log.log)("protocol stream closed", void 0, {
694
- F: __dxlog_file,
695
- L: 173,
696
- S: this,
697
- C: (f, a) => f(...a)
698
- });
699
- this.close(new import_protocols.ProtocolError("protocol stream closed")).catch((err) => this.errors.raise(err));
700
- });
701
- (0, import_async.scheduleTask)(this.connectedTimeoutContext, async () => {
702
- import_log.log.info("timeout waiting for transport to connect, aborting", void 0, {
703
- F: __dxlog_file,
704
- L: 180,
705
- S: this,
706
- C: (f, a) => f(...a)
707
- });
708
- await this.abort().catch((err) => this.errors.raise(err));
709
- }, TRANSPORT_CONNECTION_TIMEOUT);
710
- (0, import_invariant.invariant)(!this._transport, void 0, {
711
- F: __dxlog_file,
712
- L: 186,
713
- S: this,
714
- A: [
715
- "!this._transport",
716
- ""
717
- ]
718
- });
719
- this._transport = this._transportFactory.createTransport({
720
- initiator: this.initiator,
721
- stream: this._protocol.stream,
722
- sendSignal: async (signal) => this._sendSignal(signal)
723
- });
724
- this._transport.connected.once(async () => {
725
- this._changeState(ConnectionState.CONNECTED);
726
- await this.connectedTimeoutContext.dispose();
727
- this._callbacks?.onConnected?.();
728
- });
729
- this._transport.closed.once(() => {
730
- this._transport = void 0;
731
- (0, import_log.log)("abort triggered by transport close", void 0, {
732
- F: __dxlog_file,
733
- L: 201,
734
- S: this,
735
- C: (f, a) => f(...a)
736
- });
737
- this.abort().catch((err) => this.errors.raise(err));
738
- });
739
- this._transport.errors.handle(async (err) => {
740
- (0, import_log.log)("transport error:", {
741
- err
742
- }, {
743
- F: __dxlog_file,
744
- L: 206,
745
- S: this,
746
- C: (f, a) => f(...a)
747
- });
748
- if (!this.closeReason) {
749
- this.closeReason = err?.message;
750
- }
751
- if (err instanceof import_protocols.ConnectionResetError) {
752
- import_log.log.info("aborting due to transport ConnectionResetError", void 0, {
753
- F: __dxlog_file,
754
- L: 213,
755
- S: this,
756
- C: (f, a) => f(...a)
757
- });
758
- this.abort().catch((err2) => this.errors.raise(err2));
759
- } else if (err instanceof import_protocols.ConnectivityError) {
760
- import_log.log.info("aborting due to transport ConnectivityError", void 0, {
761
- F: __dxlog_file,
762
- L: 216,
763
- S: this,
764
- C: (f, a) => f(...a)
765
- });
766
- this.abort().catch((err2) => this.errors.raise(err2));
767
- } else if (err instanceof import_protocols.UnknownProtocolError) {
768
- import_log.log.warn("unsure what to do with UnknownProtocolError, will keep on truckin", {
769
- err
770
- }, {
771
- F: __dxlog_file,
772
- L: 219,
773
- S: this,
774
- C: (f, a) => f(...a)
775
- });
776
- }
777
- if (this._state !== ConnectionState.CLOSED && this._state !== ConnectionState.CLOSING) {
778
- await this.connectedTimeoutContext.dispose();
779
- this.errors.raise(err);
780
- }
781
- });
782
- for (const signal of this._incomingSignalBuffer) {
783
- void this._transport.signal(signal);
784
- }
785
- this._incomingSignalBuffer = [];
786
- import_log.log.trace("dxos.mesh.connection.open-connection", import_protocols.trace.end({
787
- id: this._instanceId
788
- }), {
789
- F: __dxlog_file,
790
- L: 235,
791
- S: this,
792
- C: (f, a) => f(...a)
793
- });
794
- }
795
- async abort(err) {
796
- (0, import_log.log)("aborting...", {
797
- err
798
- }, {
799
- F: __dxlog_file,
800
- L: 242,
801
- S: this,
802
- C: (f, a) => f(...a)
803
- });
804
- if (this._state === ConnectionState.CLOSED || this._state === ConnectionState.ABORTED) {
805
- (0, import_log.log)(`abort ignored: already ${this._state}`, this.closeReason, {
806
- F: __dxlog_file,
807
- L: 244,
808
- S: this,
809
- C: (f, a) => f(...a)
810
- });
811
- return;
812
- }
813
- await this.connectedTimeoutContext.dispose();
814
- this._changeState(ConnectionState.ABORTING);
815
- if (!this.closeReason) {
816
- this.closeReason = err?.message;
817
- }
818
- await this._ctx.dispose();
819
- try {
820
- (0, import_log.log)("aborting protocol... ", void 0, {
821
- F: __dxlog_file,
822
- L: 258,
823
- S: this,
824
- C: (f, a) => f(...a)
825
- });
826
- await this._protocol.abort();
827
- } catch (err2) {
828
- import_log.log.catch(err2, void 0, {
829
- F: __dxlog_file,
830
- L: 261,
831
- S: this,
832
- C: (f, a) => f(...a)
833
- });
834
- }
835
- try {
836
- await this._transport?.destroy();
837
- } catch (err2) {
838
- import_log.log.catch(err2, void 0, {
839
- F: __dxlog_file,
840
- L: 268,
841
- S: this,
842
- C: (f, a) => f(...a)
843
- });
844
- }
845
- try {
846
- this._callbacks?.onClosed?.(err);
847
- } catch (err2) {
848
- import_log.log.catch(err2, void 0, {
849
- F: __dxlog_file,
850
- L: 274,
851
- S: this,
852
- C: (f, a) => f(...a)
853
- });
854
- }
855
- this._changeState(ConnectionState.ABORTED);
856
- }
857
- async close(err) {
858
- if (!this.closeReason) {
859
- this.closeReason = err?.message;
860
- } else {
861
- this.closeReason += `; ${err?.message}`;
862
- }
863
- if (this._state === ConnectionState.CLOSED || this._state === ConnectionState.ABORTING || this._state === ConnectionState.ABORTED) {
864
- return;
865
- }
866
- const lastState = this._state;
867
- this._changeState(ConnectionState.CLOSING);
868
- await this.connectedTimeoutContext.dispose();
869
- await this._ctx.dispose();
870
- (0, import_log.log)("closing...", {
871
- peerId: this.ownId
872
- }, {
873
- F: __dxlog_file,
874
- L: 299,
875
- S: this,
876
- C: (f, a) => f(...a)
877
- });
878
- if (lastState === ConnectionState.CONNECTED) {
879
- try {
880
- await this._protocol.close();
881
- } catch (err2) {
882
- import_log.log.catch(err2, void 0, {
883
- F: __dxlog_file,
884
- L: 306,
885
- S: this,
886
- C: (f, a) => f(...a)
887
- });
888
- }
889
- try {
890
- await this._transport?.destroy();
891
- } catch (err2) {
892
- import_log.log.catch(err2, void 0, {
893
- F: __dxlog_file,
894
- L: 313,
895
- S: this,
896
- C: (f, a) => f(...a)
897
- });
898
- }
899
- }
900
- (0, import_log.log)("closed", {
901
- peerId: this.ownId
902
- }, {
903
- F: __dxlog_file,
904
- L: 317,
905
- S: this,
906
- C: (f, a) => f(...a)
907
- });
908
- this._changeState(ConnectionState.CLOSED);
909
- this._callbacks?.onClosed?.(err);
910
- }
911
- _sendSignal(signal) {
912
- this._outgoingSignalBuffer.push(signal);
913
- this._signalSendTask.schedule();
914
- }
915
- async _flushSignalBuffer() {
916
- if (this._outgoingSignalBuffer.length === 0) {
917
- return;
918
- }
919
- try {
920
- if (process.env.NODE_ENV !== "test") {
921
- await (0, import_context.cancelWithContext)(this._ctx, (0, import_async.sleep)(this._signallingDelay));
922
- this._signallingDelay = Math.min(this._signallingDelay * 2, MAX_SIGNALLING_DELAY);
923
- }
924
- const signals = [
925
- ...this._outgoingSignalBuffer
926
- ];
927
- this._outgoingSignalBuffer.length = 0;
928
- await this._signalMessaging.signal({
929
- author: this.ownId,
930
- recipient: this.remoteId,
931
- sessionId: this.sessionId,
932
- topic: this.topic,
933
- data: {
934
- signalBatch: {
935
- signals
936
- }
937
- }
938
- });
939
- } catch (err) {
940
- if (err instanceof import_protocols.CancelledError || err instanceof Error && err.message?.includes("CANCELLED")) {
941
- return;
942
- }
943
- import_log.log.info("signal message failed to deliver", {
944
- err
945
- }, {
946
- F: __dxlog_file,
947
- L: 355,
948
- S: this,
949
- C: (f, a) => f(...a)
950
- });
951
- await this.close(new import_protocols.ConnectivityError("signal message failed to deliver", err));
952
- }
953
- }
954
- /**
955
- * Receive a signal from the remote peer.
956
- */
957
- async signal(msg) {
958
- (0, import_invariant.invariant)(msg.sessionId, void 0, {
959
- F: __dxlog_file,
960
- L: 364,
961
- S: this,
962
- A: [
963
- "msg.sessionId",
964
- ""
965
- ]
966
- });
967
- if (!msg.sessionId.equals(this.sessionId)) {
968
- (0, import_log.log)("dropping signal for incorrect session id", void 0, {
969
- F: __dxlog_file,
970
- L: 366,
971
- S: this,
972
- C: (f, a) => f(...a)
973
- });
974
- return;
975
- }
976
- (0, import_invariant.invariant)(msg.data.signal || msg.data.signalBatch, void 0, {
977
- F: __dxlog_file,
978
- L: 369,
979
- S: this,
980
- A: [
981
- "msg.data.signal || msg.data.signalBatch",
982
- ""
983
- ]
984
- });
985
- (0, import_invariant.invariant)(msg.author?.equals(this.remoteId), void 0, {
986
- F: __dxlog_file,
987
- L: 370,
988
- S: this,
989
- A: [
990
- "msg.author?.equals(this.remoteId)",
991
- ""
992
- ]
993
- });
994
- (0, import_invariant.invariant)(msg.recipient?.equals(this.ownId), void 0, {
995
- F: __dxlog_file,
996
- L: 371,
997
- S: this,
998
- A: [
999
- "msg.recipient?.equals(this.ownId)",
1000
- ""
1001
- ]
1002
- });
1003
- const signals = msg.data.signalBatch ? msg.data.signalBatch.signals ?? [] : [
1004
- msg.data.signal
1005
- ];
1006
- for (const signal of signals) {
1007
- if (!signal) {
1008
- continue;
1009
- }
1010
- if ([
1011
- ConnectionState.CREATED,
1012
- ConnectionState.INITIAL
1013
- ].includes(this.state)) {
1014
- (0, import_log.log)("buffered signal", {
1015
- peerId: this.ownId,
1016
- remoteId: this.remoteId,
1017
- msg: msg.data
1018
- }, {
1019
- F: __dxlog_file,
1020
- L: 380,
1021
- S: this,
1022
- C: (f, a) => f(...a)
1023
- });
1024
- this._incomingSignalBuffer.push(signal);
1025
- } else {
1026
- (0, import_invariant.invariant)(this._transport, "Connection not ready to accept signals.", {
1027
- F: __dxlog_file,
1028
- L: 383,
1029
- S: this,
1030
- A: [
1031
- "this._transport",
1032
- "'Connection not ready to accept signals.'"
1033
- ]
1034
- });
1035
- (0, import_log.log)("received signal", {
1036
- peerId: this.ownId,
1037
- remoteId: this.remoteId,
1038
- msg: msg.data
1039
- }, {
1040
- F: __dxlog_file,
1041
- L: 384,
1042
- S: this,
1043
- C: (f, a) => f(...a)
1044
- });
1045
- await this._transport.signal(signal);
1046
- }
1047
- }
1048
- }
1049
- initiate() {
1050
- this._changeState(ConnectionState.INITIAL);
1051
- }
1052
- _changeState(state) {
1053
- (0, import_log.log)("stateChanged", {
1054
- from: this._state,
1055
- to: state,
1056
- peerId: this.ownId
1057
- }, {
1058
- F: __dxlog_file,
1059
- L: 395,
1060
- S: this,
1061
- C: (f, a) => f(...a)
1062
- });
1063
- (0, import_invariant.invariant)(state !== this._state, "Already in this state.", {
1064
- F: __dxlog_file,
1065
- L: 396,
1066
- S: this,
1067
- A: [
1068
- "state !== this._state",
1069
- "'Already in this state.'"
1070
- ]
1071
- });
1072
- this._state = state;
1073
- this.stateChanged.emit(state);
1074
- }
1075
- };
1076
- _ts_decorate([
1077
- import_async.synchronized
1078
- ], Connection.prototype, "abort", null);
1079
- _ts_decorate([
1080
- import_async.synchronized
1081
- ], Connection.prototype, "close", null);
1082
-
1083
- // packages/core/mesh/network-manager/src/swarm/swarm.ts
1084
- var import_async3 = require("@dxos/async");
1085
- var import_context4 = require("@dxos/context");
1086
- var import_debug2 = require("@dxos/debug");
1087
- var import_invariant4 = require("@dxos/invariant");
1088
- var import_keys4 = require("@dxos/keys");
1089
- var import_log4 = require("@dxos/log");
1090
- var import_protocols4 = require("@dxos/protocols");
1091
- var import_util2 = require("@dxos/util");
1092
-
1093
- // packages/core/mesh/network-manager/src/swarm/peer.ts
1094
- var import_async2 = require("@dxos/async");
1095
- var import_context2 = require("@dxos/context");
1096
- var import_invariant2 = require("@dxos/invariant");
1097
- var import_keys2 = require("@dxos/keys");
1098
- var import_log2 = require("@dxos/log");
1099
- var import_protocols2 = require("@dxos/protocols");
1100
- function _ts_decorate2(decorators, target, key, desc) {
1101
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1102
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1103
- r = Reflect.decorate(decorators, target, key, desc);
1104
- else
1105
- for (var i = decorators.length - 1; i >= 0; i--)
1106
- if (d = decorators[i])
1107
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1108
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1109
- }
1110
- var __dxlog_file2 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/swarm/peer.ts";
1111
- var ConnectionDisplacedError = class extends import_protocols2.SystemError {
1112
- constructor() {
1113
- super("Connection displaced by remote initiator.");
1114
- }
1115
- };
1116
- var CONNECTION_COUNTS_STABLE_AFTER = 5e3;
1117
- var Peer = class {
1118
- // TODO(burdon): Convert to map?
1119
- constructor(id, topic, localPeerId, _signalMessaging, _protocolProvider, _transportFactory, _connectionLimiter, _callbacks) {
1120
- this.id = id;
1121
- this.topic = topic;
1122
- this.localPeerId = localPeerId;
1123
- this._signalMessaging = _signalMessaging;
1124
- this._protocolProvider = _protocolProvider;
1125
- this._transportFactory = _transportFactory;
1126
- this._connectionLimiter = _connectionLimiter;
1127
- this._callbacks = _callbacks;
1128
- this._availableAfter = 0;
1129
- this.availableToConnect = true;
1130
- this._ctx = new import_context2.Context();
1131
- this.advertizing = false;
1132
- this.initiating = false;
1133
- this.connectionDisplaced = new import_async2.Event();
1134
- }
1135
- /**
1136
- * Respond to remote offer.
1137
- */
1138
- async onOffer(message) {
1139
- const remoteId = message.author;
1140
- if (this.connection && ![
1141
- ConnectionState.CREATED,
1142
- ConnectionState.INITIAL,
1143
- ConnectionState.CONNECTING
1144
- ].includes(this.connection.state)) {
1145
- import_log2.log.info(`received offer when connection already in ${this.connection.state} state`, void 0, {
1146
- F: __dxlog_file2,
1147
- L: 115,
1148
- S: this,
1149
- C: (f, a) => f(...a)
1150
- });
1151
- return {
1152
- accept: false
1153
- };
1154
- }
1155
- if (this.connection || this.initiating) {
1156
- if (remoteId.toHex() < this.localPeerId.toHex()) {
1157
- (0, import_log2.log)("close local connection", {
1158
- localPeerId: this.id,
1159
- topic: this.topic,
1160
- remotePeerId: this.localPeerId,
1161
- sessionId: this.connection?.sessionId
1162
- }, {
1163
- F: __dxlog_file2,
1164
- L: 124,
1165
- S: this,
1166
- C: (f, a) => f(...a)
1167
- });
1168
- if (this.connection) {
1169
- await this.closeConnection(new ConnectionDisplacedError());
1170
- }
1171
- } else {
1172
- return {
1173
- accept: false
1174
- };
1175
- }
1176
- }
1177
- if (await this._callbacks.onOffer(remoteId)) {
1178
- if (!this.connection) {
1179
- (0, import_invariant2.invariant)(message.sessionId, void 0, {
1180
- F: __dxlog_file2,
1181
- L: 144,
1182
- S: this,
1183
- A: [
1184
- "message.sessionId",
1185
- ""
1186
- ]
1187
- });
1188
- const connection = this._createConnection(false, message.sessionId);
1189
- try {
1190
- await this._connectionLimiter.connecting(message.sessionId);
1191
- connection.initiate();
1192
- await connection.openConnection();
1193
- } catch (err) {
1194
- if (!(err instanceof import_protocols2.CancelledError)) {
1195
- import_log2.log.info("connection error", {
1196
- topic: this.topic,
1197
- peerId: this.localPeerId,
1198
- remoteId: this.id,
1199
- err
1200
- }, {
1201
- F: __dxlog_file2,
1202
- L: 154,
1203
- S: this,
1204
- C: (f, a) => f(...a)
1205
- });
1206
- }
1207
- await this.closeConnection(err);
1208
- }
1209
- return {
1210
- accept: true
1211
- };
1212
- }
1213
- }
1214
- return {
1215
- accept: false
1216
- };
1217
- }
1218
- /**
1219
- * Initiate a connection to the remote peer.
1220
- */
1221
- async initiateConnection() {
1222
- (0, import_invariant2.invariant)(!this.initiating, "Initiation in progress.", {
1223
- F: __dxlog_file2,
1224
- L: 171,
1225
- S: this,
1226
- A: [
1227
- "!this.initiating",
1228
- "'Initiation in progress.'"
1229
- ]
1230
- });
1231
- (0, import_invariant2.invariant)(!this.connection, "Already connected.", {
1232
- F: __dxlog_file2,
1233
- L: 172,
1234
- S: this,
1235
- A: [
1236
- "!this.connection",
1237
- "'Already connected.'"
1238
- ]
1239
- });
1240
- const sessionId = import_keys2.PublicKey.random();
1241
- (0, import_log2.log)("initiating...", {
1242
- id: this.id,
1243
- topic: this.topic,
1244
- peerId: this.id,
1245
- sessionId
1246
- }, {
1247
- F: __dxlog_file2,
1248
- L: 174,
1249
- S: this,
1250
- C: (f, a) => f(...a)
1251
- });
1252
- const connection = this._createConnection(true, sessionId);
1253
- this.initiating = true;
1254
- let answer;
1255
- try {
1256
- await this._connectionLimiter.connecting(sessionId);
1257
- connection.initiate();
1258
- answer = await this._signalMessaging.offer({
1259
- author: this.localPeerId,
1260
- recipient: this.id,
1261
- sessionId,
1262
- topic: this.topic,
1263
- data: {
1264
- offer: {}
1265
- }
1266
- });
1267
- (0, import_log2.log)("received", {
1268
- answer,
1269
- topic: this.topic,
1270
- ownId: this.localPeerId,
1271
- remoteId: this.id
1272
- }, {
1273
- F: __dxlog_file2,
1274
- L: 191,
1275
- S: this,
1276
- C: (f, a) => f(...a)
1277
- });
1278
- if (connection.state !== ConnectionState.INITIAL) {
1279
- (0, import_log2.log)("ignoring response", void 0, {
1280
- F: __dxlog_file2,
1281
- L: 193,
1282
- S: this,
1283
- C: (f, a) => f(...a)
1284
- });
1285
- return;
1286
- }
1287
- } catch (err) {
1288
- (0, import_log2.log)("initiation error: send offer", {
1289
- err,
1290
- topic: this.topic,
1291
- peerId: this.localPeerId,
1292
- remoteId: this.id
1293
- }, {
1294
- F: __dxlog_file2,
1295
- L: 197,
1296
- S: this,
1297
- C: (f, a) => f(...a)
1298
- });
1299
- await connection.abort(err);
1300
- throw err;
1301
- } finally {
1302
- this.initiating = false;
1303
- }
1304
- try {
1305
- if (!answer.accept) {
1306
- this._callbacks.onRejected();
1307
- return;
1308
- }
1309
- } catch (err) {
1310
- (0, import_log2.log)("initiation error: accept answer", {
1311
- err,
1312
- topic: this.topic,
1313
- peerId: this.localPeerId,
1314
- remoteId: this.id
1315
- }, {
1316
- F: __dxlog_file2,
1317
- L: 210,
1318
- S: this,
1319
- C: (f, a) => f(...a)
1320
- });
1321
- await connection.abort(err);
1322
- throw err;
1323
- } finally {
1324
- this.initiating = false;
1325
- }
1326
- try {
1327
- (0, import_log2.log)("opening connection as initiator", void 0, {
1328
- F: __dxlog_file2,
1329
- L: 223,
1330
- S: this,
1331
- C: (f, a) => f(...a)
1332
- });
1333
- await connection.openConnection();
1334
- this._callbacks.onAccepted();
1335
- } catch (err) {
1336
- (0, import_log2.log)("initiation error: open connection", {
1337
- err,
1338
- topic: this.topic,
1339
- peerId: this.localPeerId,
1340
- remoteId: this.id
1341
- }, {
1342
- F: __dxlog_file2,
1343
- L: 227,
1344
- S: this,
1345
- C: (f, a) => f(...a)
1346
- });
1347
- import_log2.log.warn("closing connection due to unhandled error on openConnection", {
1348
- err
1349
- }, {
1350
- F: __dxlog_file2,
1351
- L: 234,
1352
- S: this,
1353
- C: (f, a) => f(...a)
1354
- });
1355
- await this.closeConnection(err);
1356
- throw err;
1357
- } finally {
1358
- this.initiating = false;
1359
- }
1360
- }
1361
- /**
1362
- * Create new connection.
1363
- * Either we're initiating a connection or creating one in response to an offer from the other peer.
1364
- */
1365
- _createConnection(initiator, sessionId) {
1366
- (0, import_log2.log)("creating connection", {
1367
- topic: this.topic,
1368
- peerId: this.localPeerId,
1369
- remoteId: this.id,
1370
- initiator,
1371
- sessionId
1372
- }, {
1373
- F: __dxlog_file2,
1374
- L: 248,
1375
- S: this,
1376
- C: (f, a) => f(...a)
1377
- });
1378
- (0, import_invariant2.invariant)(!this.connection, "Already connected.", {
1379
- F: __dxlog_file2,
1380
- L: 255,
1381
- S: this,
1382
- A: [
1383
- "!this.connection",
1384
- "'Already connected.'"
1385
- ]
1386
- });
1387
- const connection = new Connection(
1388
- this.topic,
1389
- this.localPeerId,
1390
- this.id,
1391
- sessionId,
1392
- initiator,
1393
- this._signalMessaging,
1394
- // TODO(dmaretskyi): Init only when connection is established.
1395
- this._protocolProvider({
1396
- initiator,
1397
- localPeerId: this.localPeerId,
1398
- remotePeerId: this.id,
1399
- topic: this.topic
1400
- }),
1401
- this._transportFactory,
1402
- {
1403
- onConnected: () => {
1404
- this.availableToConnect = true;
1405
- this._lastConnectionTime = Date.now();
1406
- this._callbacks.onConnected();
1407
- this._connectionLimiter.doneConnecting(sessionId);
1408
- import_log2.log.trace("dxos.mesh.connection.connected", {
1409
- topic: this.topic,
1410
- localPeerId: this.localPeerId,
1411
- remotePeerId: this.id,
1412
- sessionId,
1413
- initiator
1414
- }, {
1415
- F: __dxlog_file2,
1416
- L: 274,
1417
- S: this,
1418
- C: (f, a) => f(...a)
1419
- });
1420
- },
1421
- onClosed: (err) => {
1422
- (0, import_log2.log)("connection closed", {
1423
- topic: this.topic,
1424
- peerId: this.localPeerId,
1425
- remoteId: this.id,
1426
- initiator
1427
- }, {
1428
- F: __dxlog_file2,
1429
- L: 283,
1430
- S: this,
1431
- C: (f, a) => f(...a)
1432
- });
1433
- this._connectionLimiter.doneConnecting(sessionId);
1434
- (0, import_invariant2.invariant)(this.connection === connection, "Connection mismatch (race condition).", {
1435
- F: __dxlog_file2,
1436
- L: 288,
1437
- S: this,
1438
- A: [
1439
- "this.connection === connection",
1440
- "'Connection mismatch (race condition).'"
1441
- ]
1442
- });
1443
- import_log2.log.trace("dxos.mesh.connection.closed", {
1444
- topic: this.topic,
1445
- localPeerId: this.localPeerId,
1446
- remotePeerId: this.id,
1447
- sessionId,
1448
- initiator
1449
- }, {
1450
- F: __dxlog_file2,
1451
- L: 290,
1452
- S: this,
1453
- C: (f, a) => f(...a)
1454
- });
1455
- if (err instanceof ConnectionDisplacedError) {
1456
- this.connectionDisplaced.emit(this.connection);
1457
- } else {
1458
- if (this._lastConnectionTime && this._lastConnectionTime + CONNECTION_COUNTS_STABLE_AFTER < Date.now()) {
1459
- this._availableAfter = 0;
1460
- } else {
1461
- this.availableToConnect = false;
1462
- this._availableAfter = increaseInterval(this._availableAfter);
1463
- }
1464
- this._callbacks.onDisconnected();
1465
- (0, import_async2.scheduleTask)(this._connectionCtx, () => {
1466
- this.availableToConnect = true;
1467
- this._callbacks.onPeerAvailable();
1468
- }, this._availableAfter);
1469
- }
1470
- this.connection = void 0;
1471
- }
1472
- }
1473
- );
1474
- this._callbacks.onInitiated(connection);
1475
- void this._connectionCtx?.dispose();
1476
- this._connectionCtx = this._ctx.derive();
1477
- connection.errors.handle((err) => {
1478
- import_log2.log.info("connection error, closing", {
1479
- topic: this.topic,
1480
- peerId: this.localPeerId,
1481
- remoteId: this.id,
1482
- initiator,
1483
- err
1484
- }, {
1485
- F: __dxlog_file2,
1486
- L: 330,
1487
- S: this,
1488
- C: (f, a) => f(...a)
1489
- });
1490
- import_log2.log.trace("dxos.mesh.connection.error", {
1491
- topic: this.topic,
1492
- localPeerId: this.localPeerId,
1493
- remotePeerId: this.id,
1494
- sessionId,
1495
- initiator,
1496
- err
1497
- }, {
1498
- F: __dxlog_file2,
1499
- L: 337,
1500
- S: this,
1501
- C: (f, a) => f(...a)
1502
- });
1503
- void this.closeConnection(err);
1504
- });
1505
- this.connection = connection;
1506
- return connection;
1507
- }
1508
- async closeConnection(err) {
1509
- if (!this.connection) {
1510
- return;
1511
- }
1512
- const connection = this.connection;
1513
- (0, import_log2.log)("closing...", {
1514
- peerId: this.id,
1515
- sessionId: connection.sessionId
1516
- }, {
1517
- F: __dxlog_file2,
1518
- L: 362,
1519
- S: this,
1520
- C: (f, a) => f(...a)
1521
- });
1522
- await connection.close(err);
1523
- (0, import_log2.log)("closed", {
1524
- peerId: this.id,
1525
- sessionId: connection.sessionId
1526
- }, {
1527
- F: __dxlog_file2,
1528
- L: 368,
1529
- S: this,
1530
- C: (f, a) => f(...a)
1531
- });
1532
- }
1533
- async onSignal(message) {
1534
- if (!this.connection) {
1535
- (0, import_log2.log)("dropping signal message for non-existent connection", {
1536
- message
1537
- }, {
1538
- F: __dxlog_file2,
1539
- L: 373,
1540
- S: this,
1541
- C: (f, a) => f(...a)
1542
- });
1543
- return;
1544
- }
1545
- await this.connection.signal(message);
1546
- }
1547
- async destroy(reason) {
1548
- await this._ctx.dispose();
1549
- (0, import_log2.log)("Destroying peer", {
1550
- peerId: this.id,
1551
- topic: this.topic
1552
- }, {
1553
- F: __dxlog_file2,
1554
- L: 383,
1555
- S: this,
1556
- C: (f, a) => f(...a)
1557
- });
1558
- await this?.connection?.close(reason);
1559
- }
1560
- };
1561
- _ts_decorate2([
1562
- import_async2.synchronized
1563
- ], Peer.prototype, "destroy", null);
1564
- var increaseInterval = (interval) => {
1565
- if (interval === 0) {
1566
- return 50;
1567
- } else if (interval < 500) {
1568
- return 500;
1569
- } else if (interval < 1e3) {
1570
- return 1e3;
1571
- } else if (interval < 5e3) {
1572
- return 5e3;
1573
- }
1574
- return 1e4;
1575
- };
1576
-
1577
- // packages/core/mesh/network-manager/src/signal/swarm-messenger.ts
1578
- var import_context3 = require("@dxos/context");
1579
- var import_invariant3 = require("@dxos/invariant");
1580
- var import_keys3 = require("@dxos/keys");
1581
- var import_log3 = require("@dxos/log");
1582
- var import_protocols3 = require("@dxos/protocols");
1583
- var import_util = require("@dxos/util");
1584
- var __dxlog_file3 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/signal/swarm-messenger.ts";
1585
- var SwarmMessage = import_protocols3.schema.getCodecForType("dxos.mesh.swarm.SwarmMessage");
1586
- var SwarmMessenger = class {
1587
- constructor({ sendMessage, onSignal, onOffer, topic }) {
1588
- this._ctx = new import_context3.Context();
1589
- this._offerRecords = new import_util.ComplexMap((key) => key.toHex());
1590
- this._sendMessage = sendMessage;
1591
- this._onSignal = onSignal;
1592
- this._onOffer = onOffer;
1593
- this._topic = topic;
1594
- }
1595
- async receiveMessage({ author, recipient, payload }) {
1596
- if (payload.type_url !== "dxos.mesh.swarm.SwarmMessage") {
1597
- return;
1598
- }
1599
- const message = SwarmMessage.decode(payload.value);
1600
- if (!this._topic.equals(message.topic)) {
1601
- return;
1602
- }
1603
- (0, import_log3.log)("received", {
1604
- from: author,
1605
- to: recipient,
1606
- msg: message
1607
- }, {
1608
- F: __dxlog_file3,
1609
- L: 69,
1610
- S: this,
1611
- C: (f, a) => f(...a)
1612
- });
1613
- if (message.data?.offer) {
1614
- await this._handleOffer({
1615
- author,
1616
- recipient,
1617
- message
1618
- });
1619
- } else if (message.data?.answer) {
1620
- await this._resolveAnswers(message);
1621
- } else if (message.data?.signal) {
1622
- await this._handleSignal({
1623
- author,
1624
- recipient,
1625
- message
1626
- });
1627
- } else if (message.data?.signalBatch) {
1628
- await this._handleSignal({
1629
- author,
1630
- recipient,
1631
- message
1632
- });
1633
- } else {
1634
- import_log3.log.warn("unknown message", {
1635
- message
1636
- }, {
1637
- F: __dxlog_file3,
1638
- L: 80,
1639
- S: this,
1640
- C: (f, a) => f(...a)
1641
- });
1642
- }
1643
- }
1644
- async signal(message) {
1645
- (0, import_invariant3.invariant)(message.data?.signal || message.data?.signalBatch, "Invalid message", {
1646
- F: __dxlog_file3,
1647
- L: 85,
1648
- S: this,
1649
- A: [
1650
- "message.data?.signal || message.data?.signalBatch",
1651
- "'Invalid message'"
1652
- ]
1653
- });
1654
- await this._sendReliableMessage({
1655
- author: message.author,
1656
- recipient: message.recipient,
1657
- message
1658
- });
1659
- }
1660
- async offer(message) {
1661
- const networkMessage = {
1662
- ...message,
1663
- messageId: import_keys3.PublicKey.random()
1664
- };
1665
- return new Promise((resolve, reject) => {
1666
- this._offerRecords.set(networkMessage.messageId, {
1667
- resolve
1668
- });
1669
- this._sendReliableMessage({
1670
- author: message.author,
1671
- recipient: message.recipient,
1672
- message: networkMessage
1673
- }).catch((err) => reject(err));
1674
- });
1675
- }
1676
- async _sendReliableMessage({ author, recipient, message }) {
1677
- const networkMessage = {
1678
- ...message,
1679
- // Setting unique message_id if it not specified yet.
1680
- messageId: message.messageId ?? import_keys3.PublicKey.random()
1681
- };
1682
- (0, import_log3.log)("sending", {
1683
- from: author,
1684
- to: recipient,
1685
- msg: networkMessage
1686
- }, {
1687
- F: __dxlog_file3,
1688
- L: 123,
1689
- S: this,
1690
- C: (f, a) => f(...a)
1691
- });
1692
- await this._sendMessage({
1693
- author,
1694
- recipient,
1695
- payload: {
1696
- type_url: "dxos.mesh.swarm.SwarmMessage",
1697
- value: SwarmMessage.encode(networkMessage)
1698
- }
1699
- });
1700
- }
1701
- async _resolveAnswers(message) {
1702
- (0, import_invariant3.invariant)(message.data?.answer?.offerMessageId, "No offerMessageId", {
1703
- F: __dxlog_file3,
1704
- L: 135,
1705
- S: this,
1706
- A: [
1707
- "message.data?.answer?.offerMessageId",
1708
- "'No offerMessageId'"
1709
- ]
1710
- });
1711
- const offerRecord = this._offerRecords.get(message.data.answer.offerMessageId);
1712
- if (offerRecord) {
1713
- this._offerRecords.delete(message.data.answer.offerMessageId);
1714
- (0, import_invariant3.invariant)(message.data?.answer, "No answer", {
1715
- F: __dxlog_file3,
1716
- L: 139,
1717
- S: this,
1718
- A: [
1719
- "message.data?.answer",
1720
- "'No answer'"
1721
- ]
1722
- });
1723
- (0, import_log3.log)("resolving", {
1724
- answer: message.data.answer
1725
- }, {
1726
- F: __dxlog_file3,
1727
- L: 140,
1728
- S: this,
1729
- C: (f, a) => f(...a)
1730
- });
1731
- offerRecord.resolve(message.data.answer);
1732
- }
1733
- }
1734
- async _handleOffer({ author, recipient, message }) {
1735
- (0, import_invariant3.invariant)(message.data.offer, "No offer", {
1736
- F: __dxlog_file3,
1737
- L: 154,
1738
- S: this,
1739
- A: [
1740
- "message.data.offer",
1741
- "'No offer'"
1742
- ]
1743
- });
1744
- const offerMessage = {
1745
- author,
1746
- recipient,
1747
- ...message,
1748
- data: {
1749
- offer: message.data.offer
1750
- }
1751
- };
1752
- const answer = await this._onOffer(offerMessage);
1753
- answer.offerMessageId = message.messageId;
1754
- try {
1755
- await this._sendReliableMessage({
1756
- author: recipient,
1757
- recipient: author,
1758
- message: {
1759
- topic: message.topic,
1760
- sessionId: message.sessionId,
1761
- data: {
1762
- answer
1763
- }
1764
- }
1765
- });
1766
- } catch (err) {
1767
- if (err instanceof import_protocols3.TimeoutError) {
1768
- import_log3.log.info("timeout sending answer to offer", {
1769
- err
1770
- }, {
1771
- F: __dxlog_file3,
1772
- L: 175,
1773
- S: this,
1774
- C: (f, a) => f(...a)
1775
- });
1776
- } else {
1777
- import_log3.log.info("error sending answer to offer", {
1778
- err
1779
- }, {
1780
- F: __dxlog_file3,
1781
- L: 177,
1782
- S: this,
1783
- C: (f, a) => f(...a)
1784
- });
1785
- }
1786
- }
1787
- }
1788
- async _handleSignal({ author, recipient, message }) {
1789
- (0, import_invariant3.invariant)(message.messageId, void 0, {
1790
- F: __dxlog_file3,
1791
- L: 191,
1792
- S: this,
1793
- A: [
1794
- "message.messageId",
1795
- ""
1796
- ]
1797
- });
1798
- (0, import_invariant3.invariant)(message.data.signal || message.data.signalBatch, "Invalid message", {
1799
- F: __dxlog_file3,
1800
- L: 192,
1801
- S: this,
1802
- A: [
1803
- "message.data.signal || message.data.signalBatch",
1804
- "'Invalid message'"
1805
- ]
1806
- });
1807
- const signalMessage = {
1808
- author,
1809
- recipient,
1810
- ...message,
1811
- data: {
1812
- signal: message.data.signal,
1813
- signalBatch: message.data.signalBatch
1814
- }
1815
- };
1816
- await this._onSignal(signalMessage);
1817
- }
1818
- };
1819
-
1820
- // packages/core/mesh/network-manager/src/swarm/swarm.ts
1821
- function _ts_decorate3(decorators, target, key, desc) {
1822
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1823
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1824
- r = Reflect.decorate(decorators, target, key, desc);
1825
- else
1826
- for (var i = decorators.length - 1; i >= 0; i--)
1827
- if (d = decorators[i])
1828
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1829
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1830
- }
1831
- var __dxlog_file4 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/swarm/swarm.ts";
1832
- var INITIATION_DELAY = 100;
1833
- var getClassName = (obj) => Object.getPrototypeOf(obj).constructor.name;
1834
- var Swarm = class {
1835
- // TODO(burdon): Swarm => Peer.create/destroy =< Connection.open/close
1836
- // TODO(burdon): Split up properties.
1837
- constructor(_topic, _ownPeerId, _topology, _protocolProvider, _messenger, _transportFactory, _label, _connectionLimiter, _initiationDelay = INITIATION_DELAY) {
1838
- this._topic = _topic;
1839
- this._ownPeerId = _ownPeerId;
1840
- this._topology = _topology;
1841
- this._protocolProvider = _protocolProvider;
1842
- this._messenger = _messenger;
1843
- this._transportFactory = _transportFactory;
1844
- this._label = _label;
1845
- this._connectionLimiter = _connectionLimiter;
1846
- this._initiationDelay = _initiationDelay;
1847
- this._ctx = new import_context4.Context();
1848
- this._listeningHandle = void 0;
1849
- this._peers = new import_util2.ComplexMap(import_keys4.PublicKey.hash);
1850
- this._instanceId = import_keys4.PublicKey.random().toHex();
1851
- this.connectionAdded = new import_async3.Event();
1852
- this.disconnected = new import_async3.Event();
1853
- this.connected = new import_async3.Event();
1854
- this.errors = new import_debug2.ErrorStream();
1855
- import_log4.log.trace("dxos.mesh.swarm.constructor", import_protocols4.trace.begin({
1856
- id: this._instanceId,
1857
- data: {
1858
- topic: this._topic.toHex(),
1859
- peerId: this._ownPeerId.toHex()
1860
- }
1861
- }), {
1862
- F: __dxlog_file4,
1863
- L: 88,
1864
- S: this,
1865
- C: (f, a) => f(...a)
1866
- });
1867
- (0, import_log4.log)("creating swarm", {
1868
- peerId: _ownPeerId
1869
- }, {
1870
- F: __dxlog_file4,
1871
- L: 92,
1872
- S: this,
1873
- C: (f, a) => f(...a)
1874
- });
1875
- _topology.init(this._getSwarmController());
1876
- this._swarmMessenger = new SwarmMessenger({
1877
- sendMessage: async (msg) => await this._messenger.sendMessage(msg),
1878
- onSignal: async (msg) => await this.onSignal(msg),
1879
- onOffer: async (msg) => await this.onOffer(msg),
1880
- topic: this._topic
1881
- });
1882
- import_log4.log.trace("dxos.mesh.swarm.constructor", import_protocols4.trace.end({
1883
- id: this._instanceId
1884
- }), {
1885
- F: __dxlog_file4,
1886
- L: 101,
1887
- S: this,
1888
- C: (f, a) => f(...a)
1889
- });
1890
- }
1891
- get connections() {
1892
- return Array.from(this._peers.values()).map((peer) => peer.connection).filter(import_util2.isNotNullOrUndefined);
1893
- }
1894
- get ownPeerId() {
1895
- return this._ownPeerId;
1896
- }
1897
- /**
1898
- * Custom label assigned to this swarm. Used in devtools to display human-readable names for swarms.
1899
- */
1900
- get label() {
1901
- return this._label;
1902
- }
1903
- get topic() {
1904
- return this._topic;
1905
- }
1906
- async open() {
1907
- (0, import_invariant4.invariant)(!this._listeningHandle, void 0, {
1908
- F: __dxlog_file4,
1909
- L: 128,
1910
- S: this,
1911
- A: [
1912
- "!this._listeningHandle",
1913
- ""
1914
- ]
1915
- });
1916
- this._listeningHandle = await this._messenger.listen({
1917
- peerId: this._ownPeerId,
1918
- payloadType: "dxos.mesh.swarm.SwarmMessage",
1919
- onMessage: async (message) => {
1920
- await this._swarmMessenger.receiveMessage(message).catch((err) => import_log4.log.info("Error while receiving message", {
1921
- err
1922
- }, {
1923
- F: __dxlog_file4,
1924
- L: 136,
1925
- S: this,
1926
- C: (f, a) => f(...a)
1927
- }));
1928
- }
1929
- });
1930
- }
1931
- async destroy() {
1932
- (0, import_log4.log)("destroying...", void 0, {
1933
- F: __dxlog_file4,
1934
- L: 142,
1935
- S: this,
1936
- C: (f, a) => f(...a)
1937
- });
1938
- await this._listeningHandle?.unsubscribe();
1939
- this._listeningHandle = void 0;
1940
- await this._ctx.dispose();
1941
- await this._topology.destroy();
1942
- await Promise.all(Array.from(this._peers.keys()).map((key) => this._destroyPeer(key, "swarm destroyed")));
1943
- (0, import_log4.log)("destroyed", void 0, {
1944
- F: __dxlog_file4,
1945
- L: 149,
1946
- S: this,
1947
- C: (f, a) => f(...a)
1948
- });
1949
- }
1950
- async setTopology(topology) {
1951
- (0, import_invariant4.invariant)(!this._ctx.disposed, "Swarm is offline", {
1952
- F: __dxlog_file4,
1953
- L: 153,
1954
- S: this,
1955
- A: [
1956
- "!this._ctx.disposed",
1957
- "'Swarm is offline'"
1958
- ]
1959
- });
1960
- if (topology === this._topology) {
1961
- return;
1962
- }
1963
- (0, import_log4.log)("setting topology", {
1964
- previous: getClassName(this._topology),
1965
- topology: getClassName(topology)
1966
- }, {
1967
- F: __dxlog_file4,
1968
- L: 157,
1969
- S: this,
1970
- C: (f, a) => f(...a)
1971
- });
1972
- await this._topology.destroy();
1973
- this._topology = topology;
1974
- this._topology.init(this._getSwarmController());
1975
- this._topology.update();
1976
- }
1977
- onSwarmEvent(swarmEvent) {
1978
- (0, import_log4.log)("swarm event", {
1979
- swarmEvent
1980
- }, {
1981
- F: __dxlog_file4,
1982
- L: 170,
1983
- S: this,
1984
- C: (f, a) => f(...a)
1985
- });
1986
- if (this._ctx.disposed) {
1987
- (0, import_log4.log)("swarm event ignored for disposed swarm", void 0, {
1988
- F: __dxlog_file4,
1989
- L: 173,
1990
- S: this,
1991
- C: (f, a) => f(...a)
1992
- });
1993
- return;
1994
- }
1995
- if (swarmEvent.peerAvailable) {
1996
- const peerId = import_keys4.PublicKey.from(swarmEvent.peerAvailable.peer);
1997
- (0, import_log4.log)("new peer", {
1998
- peerId
1999
- }, {
2000
- F: __dxlog_file4,
2001
- L: 179,
2002
- S: this,
2003
- C: (f, a) => f(...a)
2004
- });
2005
- if (!peerId.equals(this._ownPeerId)) {
2006
- const peer = this._getOrCreatePeer(peerId);
2007
- peer.advertizing = true;
2008
- }
2009
- } else if (swarmEvent.peerLeft) {
2010
- const peer = this._peers.get(import_keys4.PublicKey.from(swarmEvent.peerLeft.peer));
2011
- if (peer) {
2012
- peer.advertizing = false;
2013
- if (peer.connection?.state !== ConnectionState.CONNECTED) {
2014
- void this._destroyPeer(peer.id, "peer left").catch((err) => import_log4.log.catch(err, void 0, {
2015
- F: __dxlog_file4,
2016
- L: 190,
2017
- S: this,
2018
- C: (f, a) => f(...a)
2019
- }));
2020
- }
2021
- } else {
2022
- (0, import_log4.log)("received peerLeft but no peer found", {
2023
- peer: swarmEvent.peerLeft.peer
2024
- }, {
2025
- F: __dxlog_file4,
2026
- L: 193,
2027
- S: this,
2028
- C: (f, a) => f(...a)
2029
- });
2030
- }
2031
- }
2032
- this._topology.update();
2033
- }
2034
- async onOffer(message) {
2035
- (0, import_log4.log)("offer", {
2036
- message
2037
- }, {
2038
- F: __dxlog_file4,
2039
- L: 202,
2040
- S: this,
2041
- C: (f, a) => f(...a)
2042
- });
2043
- if (this._ctx.disposed) {
2044
- (0, import_log4.log)("ignored for disposed swarm", void 0, {
2045
- F: __dxlog_file4,
2046
- L: 204,
2047
- S: this,
2048
- C: (f, a) => f(...a)
2049
- });
2050
- return {
2051
- accept: false
2052
- };
2053
- }
2054
- (0, import_invariant4.invariant)(message.author, void 0, {
2055
- F: __dxlog_file4,
2056
- L: 209,
2057
- S: this,
2058
- A: [
2059
- "message.author",
2060
- ""
2061
- ]
2062
- });
2063
- if (!message.recipient?.equals(this._ownPeerId)) {
2064
- (0, import_log4.log)("rejecting offer with incorrect peerId", {
2065
- message
2066
- }, {
2067
- F: __dxlog_file4,
2068
- L: 211,
2069
- S: this,
2070
- C: (f, a) => f(...a)
2071
- });
2072
- return {
2073
- accept: false
2074
- };
2075
- }
2076
- if (!message.topic?.equals(this._topic)) {
2077
- (0, import_log4.log)("rejecting offer with incorrect topic", {
2078
- message
2079
- }, {
2080
- F: __dxlog_file4,
2081
- L: 215,
2082
- S: this,
2083
- C: (f, a) => f(...a)
2084
- });
2085
- return {
2086
- accept: false
2087
- };
2088
- }
2089
- const peer = this._getOrCreatePeer(message.author);
2090
- const answer = await peer.onOffer(message);
2091
- this._topology.update();
2092
- return answer;
2093
- }
2094
- async onSignal(message) {
2095
- (0, import_log4.log)("signal", {
2096
- message
2097
- }, {
2098
- F: __dxlog_file4,
2099
- L: 226,
2100
- S: this,
2101
- C: (f, a) => f(...a)
2102
- });
2103
- if (this._ctx.disposed) {
2104
- import_log4.log.info("ignored for offline swarm", void 0, {
2105
- F: __dxlog_file4,
2106
- L: 228,
2107
- S: this,
2108
- C: (f, a) => f(...a)
2109
- });
2110
- return;
2111
- }
2112
- (0, import_invariant4.invariant)(message.recipient?.equals(this._ownPeerId), `Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`, {
2113
- F: __dxlog_file4,
2114
- L: 231,
2115
- S: this,
2116
- A: [
2117
- "message.recipient?.equals(this._ownPeerId)",
2118
- "`Invalid signal peer id expected=${this.ownPeerId}, actual=${message.recipient}`"
2119
- ]
2120
- });
2121
- (0, import_invariant4.invariant)(message.topic?.equals(this._topic), void 0, {
2122
- F: __dxlog_file4,
2123
- L: 235,
2124
- S: this,
2125
- A: [
2126
- "message.topic?.equals(this._topic)",
2127
- ""
2128
- ]
2129
- });
2130
- (0, import_invariant4.invariant)(message.author, void 0, {
2131
- F: __dxlog_file4,
2132
- L: 236,
2133
- S: this,
2134
- A: [
2135
- "message.author",
2136
- ""
2137
- ]
2138
- });
2139
- const peer = this._getOrCreatePeer(message.author);
2140
- await peer.onSignal(message);
2141
- }
2142
- // For debug purposes
2143
- async goOffline() {
2144
- await this._ctx.dispose();
2145
- await Promise.all([
2146
- ...this._peers.keys()
2147
- ].map((peerId) => this._destroyPeer(peerId, "goOffline")));
2148
- }
2149
- // For debug purposes
2150
- async goOnline() {
2151
- this._ctx = new import_context4.Context();
2152
- }
2153
- _getOrCreatePeer(peerId) {
2154
- let peer = this._peers.get(peerId);
2155
- if (!peer) {
2156
- peer = new Peer(peerId, this._topic, this._ownPeerId, this._swarmMessenger, this._protocolProvider, this._transportFactory, this._connectionLimiter, {
2157
- onInitiated: (connection) => {
2158
- this.connectionAdded.emit(connection);
2159
- },
2160
- onConnected: () => {
2161
- this.connected.emit(peerId);
2162
- },
2163
- onDisconnected: async () => {
2164
- if (!peer.advertizing) {
2165
- await this._destroyPeer(peer.id, "peer disconnected");
2166
- }
2167
- this.disconnected.emit(peerId);
2168
- this._topology.update();
2169
- },
2170
- onRejected: () => {
2171
- if (this._peers.has(peerId)) {
2172
- (0, import_log4.log)("peer rejected connection", {
2173
- peerId
2174
- }, {
2175
- F: __dxlog_file4,
2176
- L: 285,
2177
- S: this,
2178
- C: (f, a) => f(...a)
2179
- });
2180
- void this._destroyPeer(peerId, "peer rejected connection");
2181
- }
2182
- },
2183
- onAccepted: () => {
2184
- this._topology.update();
2185
- },
2186
- onOffer: (remoteId) => {
2187
- return this._topology.onOffer(remoteId);
2188
- },
2189
- onPeerAvailable: () => {
2190
- this._topology.update();
2191
- }
2192
- });
2193
- this._peers.set(peerId, peer);
2194
- }
2195
- return peer;
2196
- }
2197
- async _destroyPeer(peerId, reason) {
2198
- (0, import_invariant4.invariant)(this._peers.has(peerId), void 0, {
2199
- F: __dxlog_file4,
2200
- L: 307,
2201
- S: this,
2202
- A: [
2203
- "this._peers.has(peerId)",
2204
- ""
2205
- ]
2206
- });
2207
- await this._peers.get(peerId).destroy(new Error(reason));
2208
- this._peers.delete(peerId);
2209
- }
2210
- _getSwarmController() {
2211
- return {
2212
- getState: () => ({
2213
- ownPeerId: this._ownPeerId,
2214
- connected: Array.from(this._peers.values()).filter((peer) => peer.connection).map((peer) => peer.id),
2215
- candidates: Array.from(this._peers.values()).filter((peer) => !peer.connection && peer.advertizing && peer.availableToConnect).map((peer) => peer.id)
2216
- }),
2217
- connect: (peer) => {
2218
- if (this._ctx.disposed) {
2219
- return;
2220
- }
2221
- (0, import_async3.scheduleTask)(this._ctx, async () => {
2222
- try {
2223
- await this._initiateConnection(peer);
2224
- } catch (err) {
2225
- (0, import_log4.log)("initiation error", err, {
2226
- F: __dxlog_file4,
2227
- L: 333,
2228
- S: this,
2229
- C: (f, a) => f(...a)
2230
- });
2231
- }
2232
- });
2233
- },
2234
- disconnect: async (peer) => {
2235
- if (this._ctx.disposed) {
2236
- return;
2237
- }
2238
- (0, import_async3.scheduleTask)(this._ctx, async () => {
2239
- await this._closeConnection(peer);
2240
- this._topology.update();
2241
- });
2242
- }
2243
- };
2244
- }
2245
- /**
2246
- * Creates a connection then sends message over signal network.
2247
- */
2248
- async _initiateConnection(remoteId) {
2249
- const ctx = this._ctx;
2250
- if (remoteId.toHex() < this._ownPeerId.toHex()) {
2251
- (0, import_log4.log)("initiation delay", {
2252
- remoteId
2253
- }, {
2254
- F: __dxlog_file4,
2255
- L: 360,
2256
- S: this,
2257
- C: (f, a) => f(...a)
2258
- });
2259
- await (0, import_async3.sleep)(this._initiationDelay);
2260
- }
2261
- if (ctx.disposed) {
2262
- return;
2263
- }
2264
- const peer = this._getOrCreatePeer(remoteId);
2265
- if (peer.connection) {
2266
- return;
2267
- }
2268
- (0, import_log4.log)("initiating connection...", {
2269
- remoteId
2270
- }, {
2271
- F: __dxlog_file4,
2272
- L: 374,
2273
- S: this,
2274
- C: (f, a) => f(...a)
2275
- });
2276
- await peer.initiateConnection();
2277
- this._topology.update();
2278
- (0, import_log4.log)("initiated", {
2279
- remoteId
2280
- }, {
2281
- F: __dxlog_file4,
2282
- L: 377,
2283
- S: this,
2284
- C: (f, a) => f(...a)
2285
- });
2286
- }
2287
- async _closeConnection(peerId) {
2288
- const peer = this._peers.get(peerId);
2289
- if (!peer) {
2290
- return;
2291
- }
2292
- await peer.closeConnection();
2293
- }
2294
- };
2295
- _ts_decorate3([
2296
- import_log4.logInfo
2297
- ], Swarm.prototype, "_instanceId", void 0);
2298
- _ts_decorate3([
2299
- import_log4.logInfo
2300
- ], Swarm.prototype, "ownPeerId", null);
2301
- _ts_decorate3([
2302
- import_log4.logInfo
2303
- ], Swarm.prototype, "topic", null);
2304
- _ts_decorate3([
2305
- import_async3.synchronized
2306
- ], Swarm.prototype, "onSwarmEvent", null);
2307
- _ts_decorate3([
2308
- import_async3.synchronized
2309
- ], Swarm.prototype, "onOffer", null);
2310
- _ts_decorate3([
2311
- import_async3.synchronized
2312
- ], Swarm.prototype, "goOffline", null);
2313
- _ts_decorate3([
2314
- import_async3.synchronized
2315
- ], Swarm.prototype, "goOnline", null);
2316
-
2317
- // packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts
2318
- var import_async4 = require("@dxos/async");
2319
- var import_keys5 = require("@dxos/keys");
2320
- var import_log5 = require("@dxos/log");
2321
- var import_util3 = require("@dxos/util");
2322
- var __dxlog_file5 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/swarm/swarm-mapper.ts";
2323
- var SwarmMapper = class {
2324
- get peers() {
2325
- return Array.from(this._peers.values());
2326
- }
2327
- constructor(_swarm) {
2328
- this._swarm = _swarm;
2329
- this._subscriptions = new import_async4.EventSubscriptions();
2330
- this._connectionSubscriptions = new import_util3.ComplexMap(import_keys5.PublicKey.hash);
2331
- this._peers = new import_util3.ComplexMap(import_keys5.PublicKey.hash);
2332
- this.mapUpdated = new import_async4.Event();
2333
- this._subscriptions.add(_swarm.connectionAdded.on((connection) => {
2334
- this._update();
2335
- this._connectionSubscriptions.set(connection.remoteId, connection.stateChanged.on(() => {
2336
- this._update();
2337
- }));
2338
- }));
2339
- this._subscriptions.add(_swarm.disconnected.on((peerId) => {
2340
- this._connectionSubscriptions.get(peerId)?.();
2341
- this._connectionSubscriptions.delete(peerId);
2342
- this._update();
2343
- }));
2344
- this._update();
2345
- }
2346
- _update() {
2347
- (0, import_log5.log)("updating swarm", void 0, {
2348
- F: __dxlog_file5,
2349
- L: 72,
2350
- S: this,
2351
- C: (f, a) => f(...a)
2352
- });
2353
- this._peers.clear();
2354
- this._peers.set(this._swarm.ownPeerId, {
2355
- id: this._swarm.ownPeerId,
2356
- state: "ME",
2357
- connections: []
2358
- });
2359
- for (const connection of this._swarm.connections) {
2360
- this._peers.set(connection.remoteId, {
2361
- id: connection.remoteId,
2362
- state: connection.state,
2363
- connections: [
2364
- this._swarm.ownPeerId
2365
- ]
2366
- });
2367
- }
2368
- (0, import_log5.log)("graph changed", {
2369
- directConnections: this._swarm.connections.length,
2370
- totalPeersInSwarm: this._peers.size
2371
- }, {
2372
- F: __dxlog_file5,
2373
- L: 113,
2374
- S: this,
2375
- C: (f, a) => f(...a)
2376
- });
2377
- this.mapUpdated.emit(Array.from(this._peers.values()));
2378
- }
2379
- // TODO(burdon): Async open/close.
2380
- destroy() {
2381
- Array.from(this._connectionSubscriptions.values()).forEach((cb) => cb());
2382
- this._subscriptions.clear();
2383
- }
2384
- };
2385
-
2386
- // packages/core/mesh/network-manager/src/swarm/connection-limiter.ts
2387
- var import_async5 = require("@dxos/async");
2388
- var import_context5 = require("@dxos/context");
2389
- var import_invariant5 = require("@dxos/invariant");
2390
- var import_keys6 = require("@dxos/keys");
2391
- var import_log6 = require("@dxos/log");
2392
- var import_protocols5 = require("@dxos/protocols");
2393
- var import_util4 = require("@dxos/util");
2394
- var __dxlog_file6 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/swarm/connection-limiter.ts";
2395
- var MAX_CONCURRENT_INITIATING_CONNECTIONS = 50;
2396
- var ConnectionLimiter = class {
2397
- constructor({ maxConcurrentInitConnections = MAX_CONCURRENT_INITIATING_CONNECTIONS } = {}) {
2398
- this._ctx = new import_context5.Context();
2399
- /**
2400
- * Queue of promises to resolve when initiating connections amount is below the limit.
2401
- */
2402
- this._waitingPromises = new import_util4.ComplexMap(import_keys6.PublicKey.hash);
2403
- this.resolveWaitingPromises = new import_async5.DeferredTask(this._ctx, async () => {
2404
- Array.from(this._waitingPromises.values()).slice(0, this._maxConcurrentInitConnections).forEach(({ resolve }) => {
2405
- resolve();
2406
- });
2407
- });
2408
- this._maxConcurrentInitConnections = maxConcurrentInitConnections;
2409
- }
2410
- /**
2411
- * @returns Promise that resolves in queue when connections amount with 'CONNECTING' state is below the limit.
2412
- */
2413
- async connecting(sessionId) {
2414
- (0, import_invariant5.invariant)(!this._waitingPromises.has(sessionId), "Peer is already waiting for connection", {
2415
- F: __dxlog_file6,
2416
- L: 48,
2417
- S: this,
2418
- A: [
2419
- "!this._waitingPromises.has(sessionId)",
2420
- "'Peer is already waiting for connection'"
2421
- ]
2422
- });
2423
- (0, import_log6.log)("waiting", {
2424
- sessionId
2425
- }, {
2426
- F: __dxlog_file6,
2427
- L: 49,
2428
- S: this,
2429
- C: (f, a) => f(...a)
2430
- });
2431
- await new Promise((resolve, reject) => {
2432
- this._waitingPromises.set(sessionId, {
2433
- resolve,
2434
- reject
2435
- });
2436
- this.resolveWaitingPromises.schedule();
2437
- });
2438
- (0, import_log6.log)("allow", {
2439
- sessionId
2440
- }, {
2441
- F: __dxlog_file6,
2442
- L: 57,
2443
- S: this,
2444
- C: (f, a) => f(...a)
2445
- });
2446
- }
2447
- /**
2448
- * Rejects promise returned by `connecting` method.
2449
- */
2450
- doneConnecting(sessionId) {
2451
- (0, import_log6.log)("done", {
2452
- sessionId
2453
- }, {
2454
- F: __dxlog_file6,
2455
- L: 64,
2456
- S: this,
2457
- C: (f, a) => f(...a)
2458
- });
2459
- if (!this._waitingPromises.has(sessionId)) {
2460
- return;
2461
- }
2462
- this._waitingPromises.get(sessionId).reject(new import_protocols5.CancelledError());
2463
- this._waitingPromises.delete(sessionId);
2464
- this.resolveWaitingPromises.schedule();
2465
- }
2466
- };
2467
-
2468
- // packages/core/mesh/network-manager/src/connection-log.ts
2469
- var EventType;
2470
- (function(EventType2) {
2471
- EventType2["CONNECTION_STATE_CHANGED"] = "CONNECTION_STATE_CHANGED";
2472
- EventType2["PROTOCOL_ERROR"] = "PROTOCOL_ERROR";
2473
- EventType2["PROTOCOL_EXTENSIONS_INITIALIZED"] = "PROTOCOL_EXTENSIONS_INITIALIZED";
2474
- EventType2["PROTOCOL_EXTENSIONS_HANDSHAKE"] = "PROTOCOL_EXTENSIONS_HANDSHAKE";
2475
- EventType2["PROTOCOL_HANDSHAKE"] = "PROTOCOL_HANDSHAKE";
2476
- })(EventType || (EventType = {}));
2477
- var ConnectionLog = class {
2478
- constructor() {
2479
- /**
2480
- * SwarmId => info
2481
- */
2482
- this._swarms = new import_util5.ComplexMap(import_keys7.PublicKey.hash);
2483
- this.update = new import_async6.Event();
2484
- }
2485
- getSwarmInfo(swarmId) {
2486
- return this._swarms.get(swarmId) ?? (0, import_debug3.raise)(new Error(`Swarm not found: ${swarmId}`));
2487
- }
2488
- get swarms() {
2489
- return Array.from(this._swarms.values());
2490
- }
2491
- joinedSwarm(swarm) {
2492
- const info = {
2493
- id: import_keys7.PublicKey.from(swarm._instanceId),
2494
- topic: swarm.topic,
2495
- isActive: true,
2496
- label: swarm.label,
2497
- connections: []
2498
- };
2499
- this._swarms.set(import_keys7.PublicKey.from(swarm._instanceId), info);
2500
- this.update.emit();
2501
- swarm.connectionAdded.on((connection) => {
2502
- const connectionInfo = {
2503
- state: ConnectionState.CREATED,
2504
- closeReason: connection.closeReason,
2505
- remotePeerId: connection.remoteId,
2506
- sessionId: connection.sessionId,
2507
- transport: connection.transport && Object.getPrototypeOf(connection.transport).constructor.name,
2508
- protocolExtensions: [],
2509
- events: []
2510
- };
2511
- info.connections.push(connectionInfo);
2512
- this.update.emit();
2513
- connection.stateChanged.on((state) => {
2514
- connectionInfo.state = state;
2515
- connectionInfo.closeReason = connection.closeReason;
2516
- connectionInfo.events.push({
2517
- type: EventType.CONNECTION_STATE_CHANGED,
2518
- newState: state
2519
- });
2520
- this.update.emit();
2521
- });
2522
- connection.protocol?.stats?.on((stats) => {
2523
- connectionInfo.readBufferSize = stats.readBufferSize;
2524
- connectionInfo.writeBufferSize = stats.writeBufferSize;
2525
- connectionInfo.streams = stats.channels;
2526
- this.update.emit();
2527
- });
2528
- });
2529
- }
2530
- leftSwarm(swarm) {
2531
- this.getSwarmInfo(import_keys7.PublicKey.from(swarm._instanceId)).isActive = false;
2532
- this.update.emit();
2533
- }
2534
- };
2535
-
2536
- // packages/core/mesh/network-manager/src/network-manager.ts
2537
- var import_async7 = require("@dxos/async");
2538
- var import_invariant6 = require("@dxos/invariant");
2539
- var import_keys8 = require("@dxos/keys");
2540
- var import_log7 = require("@dxos/log");
2541
- var import_messaging = require("@dxos/messaging");
2542
- var import_protocols6 = require("@dxos/protocols");
2543
- var import_services = require("@dxos/protocols/proto/dxos/client/services");
2544
- var import_util6 = require("@dxos/util");
2545
- var __dxlog_file7 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/network-manager.ts";
2546
- var NetworkManager = class {
2547
- constructor({ transportFactory, signalManager, log: log1 }) {
2548
- /**
2549
- * @internal
2550
- */
2551
- this._swarms = new import_util6.ComplexMap(import_keys8.PublicKey.hash);
2552
- this._mappers = new import_util6.ComplexMap(import_keys8.PublicKey.hash);
2553
- this._connectionState = import_services.ConnectionState.ONLINE;
2554
- this.connectionStateChanged = new import_async7.Event();
2555
- this.topicsUpdated = new import_async7.Event();
2556
- this._instanceId = import_keys8.PublicKey.random().toHex();
2557
- this._transportFactory = transportFactory;
2558
- this._signalManager = signalManager;
2559
- this._signalManager.swarmEvent.on(({ topic, swarmEvent: event }) => this._swarms.get(topic)?.onSwarmEvent(event));
2560
- this._messenger = new import_messaging.Messenger({
2561
- signalManager: this._signalManager
2562
- });
2563
- this._signalConnection = {
2564
- join: (opts) => this._signalManager.join(opts),
2565
- leave: (opts) => this._signalManager.leave(opts)
2566
- };
2567
- this._connectionLimiter = new ConnectionLimiter();
2568
- if (log1) {
2569
- this._connectionLog = new ConnectionLog();
2570
- }
2571
- }
2572
- // TODO(burdon): Remove access (Devtools only).
2573
- get connectionLog() {
2574
- return this._connectionLog;
2575
- }
2576
- get connectionState() {
2577
- return this._connectionState;
2578
- }
2579
- // TODO(burdon): Reconcile with "discovery_key".
2580
- get topics() {
2581
- return Array.from(this._swarms.keys());
2582
- }
2583
- getSwarmMap(topic) {
2584
- return this._mappers.get(topic);
2585
- }
2586
- getSwarm(topic) {
2587
- return this._swarms.get(topic);
2588
- }
2589
- async open() {
2590
- import_log7.log.trace("dxos.mesh.network-manager.open", import_protocols6.trace.begin({
2591
- id: this._instanceId
2592
- }), {
2593
- F: __dxlog_file7,
2594
- L: 130,
2595
- S: this,
2596
- C: (f, a) => f(...a)
2597
- });
2598
- await this._messenger.open();
2599
- await this._signalManager.open();
2600
- import_log7.log.trace("dxos.mesh.network-manager.open", import_protocols6.trace.end({
2601
- id: this._instanceId
2602
- }), {
2603
- F: __dxlog_file7,
2604
- L: 133,
2605
- S: this,
2606
- C: (f, a) => f(...a)
2607
- });
2608
- }
2609
- async close() {
2610
- for (const topic of this._swarms.keys()) {
2611
- await this.leaveSwarm(topic).catch((err) => {
2612
- (0, import_log7.log)(err, void 0, {
2613
- F: __dxlog_file7,
2614
- L: 139,
2615
- S: this,
2616
- C: (f, a) => f(...a)
2617
- });
2618
- });
2619
- }
2620
- await this._messenger.close();
2621
- await this._signalManager.close();
2622
- }
2623
- /**
2624
- * Join the swarm.
2625
- */
2626
- async joinSwarm({ topic, peerId, topology, protocolProvider: protocol, label }) {
2627
- (0, import_invariant6.invariant)(import_keys8.PublicKey.isPublicKey(topic), void 0, {
2628
- F: __dxlog_file7,
2629
- L: 157,
2630
- S: this,
2631
- A: [
2632
- "PublicKey.isPublicKey(topic)",
2633
- ""
2634
- ]
2635
- });
2636
- (0, import_invariant6.invariant)(import_keys8.PublicKey.isPublicKey(peerId), void 0, {
2637
- F: __dxlog_file7,
2638
- L: 158,
2639
- S: this,
2640
- A: [
2641
- "PublicKey.isPublicKey(peerId)",
2642
- ""
2643
- ]
2644
- });
2645
- (0, import_invariant6.invariant)(topology, void 0, {
2646
- F: __dxlog_file7,
2647
- L: 159,
2648
- S: this,
2649
- A: [
2650
- "topology",
2651
- ""
2652
- ]
2653
- });
2654
- (0, import_invariant6.invariant)(typeof protocol === "function", void 0, {
2655
- F: __dxlog_file7,
2656
- L: 160,
2657
- S: this,
2658
- A: [
2659
- "typeof protocol === 'function'",
2660
- ""
2661
- ]
2662
- });
2663
- if (this._swarms.has(topic)) {
2664
- throw new Error(`Already connected to swarm: ${import_keys8.PublicKey.from(topic)}`);
2665
- }
2666
- (0, import_log7.log)("joining", {
2667
- topic: import_keys8.PublicKey.from(topic),
2668
- peerId,
2669
- topology: topology.toString()
2670
- }, {
2671
- F: __dxlog_file7,
2672
- L: 165,
2673
- S: this,
2674
- C: (f, a) => f(...a)
2675
- });
2676
- const swarm = new Swarm(topic, peerId, topology, protocol, this._messenger, this._transportFactory, label, this._connectionLimiter);
2677
- swarm.errors.handle((error) => {
2678
- (0, import_log7.log)("swarm error", {
2679
- error
2680
- }, {
2681
- F: __dxlog_file7,
2682
- L: 178,
2683
- S: this,
2684
- C: (f, a) => f(...a)
2685
- });
2686
- });
2687
- this._swarms.set(topic, swarm);
2688
- this._mappers.set(topic, new SwarmMapper(swarm));
2689
- await swarm.open();
2690
- this._signalConnection.join({
2691
- topic,
2692
- peerId
2693
- }).catch((error) => import_log7.log.catch(error, void 0, {
2694
- F: __dxlog_file7,
2695
- L: 187,
2696
- S: this,
2697
- C: (f, a) => f(...a)
2698
- }));
2699
- this.topicsUpdated.emit();
2700
- this._connectionLog?.joinedSwarm(swarm);
2701
- (0, import_log7.log)("joined", {
2702
- topic: import_keys8.PublicKey.from(topic),
2703
- count: this._swarms.size
2704
- }, {
2705
- F: __dxlog_file7,
2706
- L: 191,
2707
- S: this,
2708
- C: (f, a) => f(...a)
2709
- });
2710
- return {
2711
- close: () => this.leaveSwarm(topic)
2712
- };
2713
- }
2714
- /**
2715
- * Close the connection.
2716
- */
2717
- async leaveSwarm(topic) {
2718
- if (!this._swarms.has(topic)) {
2719
- return;
2720
- }
2721
- (0, import_log7.log)("leaving", {
2722
- topic: import_keys8.PublicKey.from(topic)
2723
- }, {
2724
- F: __dxlog_file7,
2725
- L: 207,
2726
- S: this,
2727
- C: (f, a) => f(...a)
2728
- });
2729
- const swarm = this._swarms.get(topic);
2730
- await this._signalConnection.leave({
2731
- topic,
2732
- peerId: swarm.ownPeerId
2733
- });
2734
- const map = this._mappers.get(topic);
2735
- map.destroy();
2736
- this._mappers.delete(topic);
2737
- this._connectionLog?.leftSwarm(swarm);
2738
- await swarm.destroy();
2739
- this._swarms.delete(topic);
2740
- await this.topicsUpdated.emit();
2741
- (0, import_log7.log)("left", {
2742
- topic: import_keys8.PublicKey.from(topic),
2743
- count: this._swarms.size
2744
- }, {
2745
- F: __dxlog_file7,
2746
- L: 221,
2747
- S: this,
2748
- C: (f, a) => f(...a)
2749
- });
2750
- }
2751
- async setConnectionState(state) {
2752
- if (state === this._connectionState) {
2753
- return;
2754
- }
2755
- switch (state) {
2756
- case import_services.ConnectionState.OFFLINE: {
2757
- this._connectionState = state;
2758
- await Promise.all([
2759
- ...this._swarms.values()
2760
- ].map((swarm) => swarm.goOffline()));
2761
- await this._messenger.close();
2762
- await this._signalManager.close();
2763
- break;
2764
- }
2765
- case import_services.ConnectionState.ONLINE: {
2766
- this._connectionState = state;
2767
- this._messenger.open();
2768
- await Promise.all([
2769
- ...this._swarms.values()
2770
- ].map((swarm) => swarm.goOnline()));
2771
- await this._signalManager.open();
2772
- break;
2773
- }
2774
- }
2775
- this.connectionStateChanged.emit(this._connectionState);
2776
- }
2777
- };
2778
-
2779
- // packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts
2780
- var import_invariant7 = require("@dxos/invariant");
2781
- var __dxlog_file8 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/topology/fully-connected-topology.ts";
2782
- var FullyConnectedTopology = class {
2783
- toString() {
2784
- return "FullyConnectedTopology";
2785
- }
2786
- init(controller) {
2787
- (0, import_invariant7.invariant)(!this._controller, "Already initialized", {
2788
- F: __dxlog_file8,
2789
- L: 18,
2790
- S: this,
2791
- A: [
2792
- "!this._controller",
2793
- "'Already initialized'"
2794
- ]
2795
- });
2796
- this._controller = controller;
2797
- }
2798
- update() {
2799
- (0, import_invariant7.invariant)(this._controller, "Not initialized", {
2800
- F: __dxlog_file8,
2801
- L: 23,
2802
- S: this,
2803
- A: [
2804
- "this._controller",
2805
- "'Not initialized'"
2806
- ]
2807
- });
2808
- const { candidates: discovered } = this._controller.getState();
2809
- for (const peer of discovered) {
2810
- this._controller.connect(peer);
2811
- }
2812
- }
2813
- async onOffer(peer) {
2814
- return true;
2815
- }
2816
- async destroy() {
2817
- }
2818
- };
2819
-
2820
- // packages/core/mesh/network-manager/src/topology/mmst-topology.ts
2821
- var import_xor_distance = __toESM(require("xor-distance"));
2822
- var import_invariant8 = require("@dxos/invariant");
2823
- var import_log8 = require("@dxos/log");
2824
- var __dxlog_file9 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/topology/mmst-topology.ts";
2825
- var MMSTTopology = class {
2826
- constructor({ originateConnections = 2, maxPeers = 4, sampleSize = 10 } = {}) {
2827
- this._sampleCollected = false;
2828
- this._originateConnections = originateConnections;
2829
- this._maxPeers = maxPeers;
2830
- this._sampleSize = sampleSize;
2831
- }
2832
- init(controller) {
2833
- (0, import_invariant8.invariant)(!this._controller, "Already initialized", {
2834
- F: __dxlog_file9,
2835
- L: 46,
2836
- S: this,
2837
- A: [
2838
- "!this._controller",
2839
- "'Already initialized'"
2840
- ]
2841
- });
2842
- this._controller = controller;
2843
- }
2844
- update() {
2845
- (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2846
- F: __dxlog_file9,
2847
- L: 51,
2848
- S: this,
2849
- A: [
2850
- "this._controller",
2851
- "'Not initialized'"
2852
- ]
2853
- });
2854
- const { connected, candidates } = this._controller.getState();
2855
- if (this._sampleCollected || connected.length > this._maxPeers || candidates.length > 0) {
2856
- (0, import_log8.log)("Running the algorithm.", void 0, {
2857
- F: __dxlog_file9,
2858
- L: 55,
2859
- S: this,
2860
- C: (f, a) => f(...a)
2861
- });
2862
- this._sampleCollected = true;
2863
- this._runAlgorithm();
2864
- }
2865
- }
2866
- async onOffer(peer) {
2867
- (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2868
- F: __dxlog_file9,
2869
- L: 62,
2870
- S: this,
2871
- A: [
2872
- "this._controller",
2873
- "'Not initialized'"
2874
- ]
2875
- });
2876
- const { connected } = this._controller.getState();
2877
- const accept = connected.length < this._maxPeers;
2878
- (0, import_log8.log)(`Offer ${peer} accept=${accept}`, void 0, {
2879
- F: __dxlog_file9,
2880
- L: 65,
2881
- S: this,
2882
- C: (f, a) => f(...a)
2883
- });
2884
- return accept;
2885
- }
2886
- async destroy() {
2887
- }
2888
- _runAlgorithm() {
2889
- (0, import_invariant8.invariant)(this._controller, "Not initialized", {
2890
- F: __dxlog_file9,
2891
- L: 74,
2892
- S: this,
2893
- A: [
2894
- "this._controller",
2895
- "'Not initialized'"
2896
- ]
2897
- });
2898
- const { connected, candidates, ownPeerId } = this._controller.getState();
2899
- if (connected.length > this._maxPeers) {
2900
- const sorted = sortByXorDistance(connected, ownPeerId).reverse().slice(0, this._maxPeers - connected.length);
2901
- for (const peer of sorted) {
2902
- (0, import_log8.log)(`Disconnect ${peer}.`, void 0, {
2903
- F: __dxlog_file9,
2904
- L: 83,
2905
- S: this,
2906
- C: (f, a) => f(...a)
2907
- });
2908
- this._controller.disconnect(peer);
2909
- }
2910
- } else if (connected.length < this._originateConnections) {
2911
- const sample = candidates.sort(() => Math.random() - 0.5).slice(0, this._sampleSize);
2912
- const sorted = sortByXorDistance(sample, ownPeerId).slice(0, this._originateConnections - connected.length);
2913
- for (const peer of sorted) {
2914
- (0, import_log8.log)(`Connect ${peer}.`, void 0, {
2915
- F: __dxlog_file9,
2916
- L: 91,
2917
- S: this,
2918
- C: (f, a) => f(...a)
2919
- });
2920
- this._controller.connect(peer);
2921
- }
2922
- }
2923
- }
2924
- toString() {
2925
- return "MMSTTopology";
2926
- }
2927
- };
2928
- var sortByXorDistance = (keys, reference) => keys.sort((a, b) => import_xor_distance.default.gt((0, import_xor_distance.default)(a.asBuffer(), reference.asBuffer()), (0, import_xor_distance.default)(b.asBuffer(), reference.asBuffer())));
2929
-
2930
- // packages/core/mesh/network-manager/src/topology/star-topology.ts
2931
- var import_invariant9 = require("@dxos/invariant");
2932
- var import_log9 = require("@dxos/log");
2933
- var __dxlog_file10 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/topology/star-topology.ts";
2934
- var StarTopology = class {
2935
- constructor(_centralPeer) {
2936
- this._centralPeer = _centralPeer;
2937
- }
2938
- toString() {
2939
- return `StarTopology(${this._centralPeer.truncate()})`;
2940
- }
2941
- init(controller) {
2942
- (0, import_invariant9.invariant)(!this._controller, "Already initialized.", {
2943
- F: __dxlog_file10,
2944
- L: 21,
2945
- S: this,
2946
- A: [
2947
- "!this._controller",
2948
- "'Already initialized.'"
2949
- ]
2950
- });
2951
- this._controller = controller;
2952
- }
2953
- update() {
2954
- (0, import_invariant9.invariant)(this._controller, "Not initialized.", {
2955
- F: __dxlog_file10,
2956
- L: 26,
2957
- S: this,
2958
- A: [
2959
- "this._controller",
2960
- "'Not initialized.'"
2961
- ]
2962
- });
2963
- const { candidates, connected, ownPeerId } = this._controller.getState();
2964
- if (!ownPeerId.equals(this._centralPeer)) {
2965
- (0, import_log9.log)("leaf peer dropping all connections apart from central peer.", void 0, {
2966
- F: __dxlog_file10,
2967
- L: 29,
2968
- S: this,
2969
- C: (f, a) => f(...a)
2970
- });
2971
- for (const peer of connected) {
2972
- if (!peer.equals(this._centralPeer)) {
2973
- (0, import_log9.log)("dropping connection", {
2974
- peer
2975
- }, {
2976
- F: __dxlog_file10,
2977
- L: 34,
2978
- S: this,
2979
- C: (f, a) => f(...a)
2980
- });
2981
- this._controller.disconnect(peer);
2982
- }
2983
- }
2984
- }
2985
- for (const peer of candidates) {
2986
- if (peer.equals(this._centralPeer) || ownPeerId.equals(this._centralPeer)) {
2987
- (0, import_log9.log)("connecting to peer", {
2988
- peer
2989
- }, {
2990
- F: __dxlog_file10,
2991
- L: 43,
2992
- S: this,
2993
- C: (f, a) => f(...a)
2994
- });
2995
- this._controller.connect(peer);
2996
- }
2997
- }
2998
- }
2999
- async onOffer(peer) {
3000
- (0, import_invariant9.invariant)(this._controller, "Not initialized.", {
3001
- F: __dxlog_file10,
3002
- L: 50,
3003
- S: this,
3004
- A: [
3005
- "this._controller",
3006
- "'Not initialized.'"
3007
- ]
3008
- });
3009
- const { ownPeerId } = this._controller.getState();
3010
- (0, import_log9.log)("offer", {
3011
- peer,
3012
- isCentral: peer.equals(this._centralPeer),
3013
- isSelfCentral: ownPeerId.equals(this._centralPeer)
3014
- }, {
3015
- F: __dxlog_file10,
3016
- L: 52,
3017
- S: this,
3018
- C: (f, a) => f(...a)
3019
- });
3020
- return ownPeerId.equals(this._centralPeer) || peer.equals(this._centralPeer);
3021
- }
3022
- async destroy() {
3023
- }
3024
- };
3025
-
3026
- // packages/core/mesh/network-manager/src/transport/memory-transport.ts
3027
- var import_node_stream = require("node:stream");
3028
- var import_async8 = require("@dxos/async");
3029
- var import_debug4 = require("@dxos/debug");
3030
- var import_invariant10 = require("@dxos/invariant");
3031
- var import_keys9 = require("@dxos/keys");
3032
- var import_log10 = require("@dxos/log");
3033
- var import_util7 = require("@dxos/util");
3034
- function _ts_decorate4(decorators, target, key, desc) {
3035
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3036
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3037
- r = Reflect.decorate(decorators, target, key, desc);
3038
- else
3039
- for (var i = decorators.length - 1; i >= 0; i--)
3040
- if (d = decorators[i])
3041
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3042
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3043
- }
3044
- var __dxlog_file11 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/transport/memory-transport.ts";
3045
- var MEMORY_TRANSPORT_DELAY = 1;
3046
- var createStreamDelay = (delay) => {
3047
- return new import_node_stream.Transform({
3048
- objectMode: true,
3049
- transform: (chunk, _, cb) => {
3050
- setTimeout(() => cb(null, chunk), delay);
3051
- }
3052
- });
3053
- };
3054
- var MemoryTransportFactory = {
3055
- createTransport: (params) => new MemoryTransport(params)
3056
- };
3057
- var MemoryTransport = class _MemoryTransport {
3058
- static {
3059
- // TODO(burdon): Remove static properties (inject context into constructor).
3060
- this._connections = new import_util7.ComplexMap(import_keys9.PublicKey.hash);
3061
- }
3062
- constructor(options) {
3063
- this.options = options;
3064
- this.closed = new import_async8.Event();
3065
- this.connected = new import_async8.Event();
3066
- this.errors = new import_debug4.ErrorStream();
3067
- this._instanceId = import_keys9.PublicKey.random();
3068
- this._remote = new import_async8.Trigger();
3069
- this._outgoingDelay = createStreamDelay(MEMORY_TRANSPORT_DELAY);
3070
- this._incomingDelay = createStreamDelay(MEMORY_TRANSPORT_DELAY);
3071
- this._destroyed = false;
3072
- (0, import_log10.log)("creating", void 0, {
3073
- F: __dxlog_file11,
3074
- L: 64,
3075
- S: this,
3076
- C: (f, a) => f(...a)
3077
- });
3078
- (0, import_invariant10.invariant)(!_MemoryTransport._connections.has(this._instanceId), "Duplicate memory connection", {
3079
- F: __dxlog_file11,
3080
- L: 66,
3081
- S: this,
3082
- A: [
3083
- "!MemoryTransport._connections.has(this._instanceId)",
3084
- "'Duplicate memory connection'"
3085
- ]
3086
- });
3087
- _MemoryTransport._connections.set(this._instanceId, this);
3088
- if (this.options.initiator) {
3089
- setTimeout(async () => {
3090
- (0, import_log10.log)("sending signal", void 0, {
3091
- F: __dxlog_file11,
3092
- L: 73,
3093
- S: this,
3094
- C: (f, a) => f(...a)
3095
- });
3096
- void this.options.sendSignal({
3097
- payload: {
3098
- transportId: this._instanceId.toHex()
3099
- }
3100
- }).catch((err) => {
3101
- if (!this._destroyed) {
3102
- this.errors.raise(err);
3103
- }
3104
- });
3105
- });
3106
- } else {
3107
- this._remote.wait({
3108
- timeout: this.options.timeout ?? 1e3
3109
- }).then((remoteId) => {
3110
- if (this._destroyed) {
3111
- return;
3112
- }
3113
- this._remoteInstanceId = remoteId;
3114
- this._remoteConnection = _MemoryTransport._connections.get(this._remoteInstanceId);
3115
- if (!this._remoteConnection) {
3116
- this._destroyed = true;
3117
- this.closed.emit();
3118
- return;
3119
- }
3120
- (0, import_invariant10.invariant)(!this._remoteConnection._remoteConnection, `Remote already connected: ${this._remoteInstanceId}`, {
3121
- F: __dxlog_file11,
3122
- L: 99,
3123
- S: this,
3124
- A: [
3125
- "!this._remoteConnection._remoteConnection",
3126
- "`Remote already connected: ${this._remoteInstanceId}`"
3127
- ]
3128
- });
3129
- this._remoteConnection._remoteConnection = this;
3130
- this._remoteConnection._remoteInstanceId = this._instanceId;
3131
- (0, import_log10.log)("connected", void 0, {
3132
- F: __dxlog_file11,
3133
- L: 103,
3134
- S: this,
3135
- C: (f, a) => f(...a)
3136
- });
3137
- this.options.stream.pipe(this._outgoingDelay).pipe(this._remoteConnection.options.stream).pipe(this._incomingDelay).pipe(this.options.stream);
3138
- this.connected.emit();
3139
- this._remoteConnection.connected.emit();
3140
- }).catch((err) => {
3141
- if (this._destroyed) {
3142
- return;
3143
- }
3144
- this.errors.raise(err);
3145
- });
3146
- }
3147
- }
3148
- async destroy() {
3149
- (0, import_log10.log)("closing", void 0, {
3150
- F: __dxlog_file11,
3151
- L: 124,
3152
- S: this,
3153
- C: (f, a) => f(...a)
3154
- });
3155
- this._destroyed = true;
3156
- _MemoryTransport._connections.delete(this._instanceId);
3157
- if (this._remoteConnection) {
3158
- (0, import_log10.log)("closing", void 0, {
3159
- F: __dxlog_file11,
3160
- L: 129,
3161
- S: this,
3162
- C: (f, a) => f(...a)
3163
- });
3164
- this._remoteConnection._destroyed = true;
3165
- _MemoryTransport._connections.delete(this._remoteInstanceId);
3166
- this.options.stream.unpipe(this._incomingDelay);
3167
- this._incomingDelay.unpipe(this._remoteConnection.options.stream);
3168
- this._remoteConnection.options.stream.unpipe(this._outgoingDelay);
3169
- this._outgoingDelay.unpipe(this.options.stream);
3170
- this.options.stream.unpipe(this._outgoingDelay);
3171
- this._remoteConnection.closed.emit();
3172
- this._remoteConnection._remoteConnection = void 0;
3173
- this._remoteConnection = void 0;
3174
- (0, import_log10.log)("closed", void 0, {
3175
- F: __dxlog_file11,
3176
- L: 150,
3177
- S: this,
3178
- C: (f, a) => f(...a)
3179
- });
3180
- }
3181
- this.closed.emit();
3182
- (0, import_log10.log)("closed", void 0, {
3183
- F: __dxlog_file11,
3184
- L: 154,
3185
- S: this,
3186
- C: (f, a) => f(...a)
3187
- });
3188
- }
3189
- signal({ payload }) {
3190
- (0, import_log10.log)("received signal", {
3191
- payload
3192
- }, {
3193
- F: __dxlog_file11,
3194
- L: 158,
3195
- S: this,
3196
- C: (f, a) => f(...a)
3197
- });
3198
- if (!payload?.transportId) {
3199
- return;
3200
- }
3201
- const transportId = payload.transportId;
3202
- if (transportId) {
3203
- const remoteId = import_keys9.PublicKey.fromHex(transportId);
3204
- this._remote.wake(remoteId);
3205
- }
3206
- }
3207
- };
3208
- _ts_decorate4([
3209
- import_log10.logInfo
3210
- ], MemoryTransport.prototype, "_instanceId", void 0);
3211
- _ts_decorate4([
3212
- import_log10.logInfo
3213
- ], MemoryTransport.prototype, "_remoteInstanceId", void 0);
3214
-
3215
- // packages/core/mesh/network-manager/src/transport/transport.ts
3216
- var TransportKind;
3217
- (function(TransportKind2) {
3218
- TransportKind2["SIMPLE_PEER"] = "SIMPLE_PEER";
3219
- TransportKind2["LIBDATACHANNEL"] = "LIBDATACHANNEL";
3220
- TransportKind2["SIMPLE_PEER_PROXY"] = "SIMPLE_PEER_PROXY";
3221
- TransportKind2["MEMORY"] = "MEMORY";
3222
- TransportKind2["TCP"] = "TCP";
3223
- })(TransportKind || (TransportKind = {}));
3224
-
3225
- // packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts
3226
- var import_simple_peer = __toESM(require("simple-peer"));
3227
- var import_tiny_invariant = __toESM(require("tiny-invariant"));
3228
- var import_async9 = require("@dxos/async");
3229
- var import_debug5 = require("@dxos/debug");
3230
- var import_keys10 = require("@dxos/keys");
3231
- var import_log11 = require("@dxos/log");
3232
- var import_protocols7 = require("@dxos/protocols");
3233
-
3234
- // packages/core/mesh/network-manager/src/transport/webrtc.ts
3235
- var wrtc = null;
3236
- try {
3237
- wrtc = require("@koush/wrtc");
3238
- } catch {
3239
- }
3240
-
3241
- // packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts
3242
- var __dxlog_file12 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/transport/simplepeer-transport.ts";
3243
- var SimplePeerTransport = class {
3244
- constructor(params) {
3245
- this.params = params;
3246
- this._closed = false;
3247
- this._piped = false;
3248
- this.closed = new import_async9.Event();
3249
- this.connected = new import_async9.Event();
3250
- this.errors = new import_debug5.ErrorStream();
3251
- this._instanceId = import_keys10.PublicKey.random().toHex();
3252
- import_log11.log.trace("dxos.mesh.webrtc-transport.constructor", import_protocols7.trace.begin({
3253
- id: this._instanceId
3254
- }), {
3255
- F: __dxlog_file12,
3256
- L: 41,
3257
- S: this,
3258
- C: (f, a) => f(...a)
3259
- });
3260
- (0, import_log11.log)("created connection", params, {
3261
- F: __dxlog_file12,
3262
- L: 42,
3263
- S: this,
3264
- C: (f, a) => f(...a)
3265
- });
3266
- this._peer = new import_simple_peer.default({
3267
- channelName: "dxos.mesh.transport",
3268
- initiator: this.params.initiator,
3269
- wrtc: import_simple_peer.default.WEBRTC_SUPPORT ? void 0 : wrtc ?? (0, import_debug5.raise)(new Error("wrtc not available")),
3270
- config: this.params.webrtcConfig
3271
- });
3272
- this._peer.on("signal", async (data) => {
3273
- (0, import_log11.log)("signal", data, {
3274
- F: __dxlog_file12,
3275
- L: 51,
3276
- S: this,
3277
- C: (f, a) => f(...a)
3278
- });
3279
- await this.params.sendSignal({
3280
- payload: {
3281
- data
3282
- }
3283
- });
3284
- });
3285
- this._peer.on("connect", () => {
3286
- (0, import_log11.log)("connected", void 0, {
3287
- F: __dxlog_file12,
3288
- L: 56,
3289
- S: this,
3290
- C: (f, a) => f(...a)
3291
- });
3292
- this.params.stream.pipe(this._peer).pipe(this.params.stream);
3293
- this._piped = true;
3294
- this.connected.emit();
3295
- });
3296
- this._peer.on("close", async () => {
3297
- (0, import_log11.log)("closed", void 0, {
3298
- F: __dxlog_file12,
3299
- L: 63,
3300
- S: this,
3301
- C: (f, a) => f(...a)
3302
- });
3303
- await this.destroy();
3304
- });
3305
- this._peer.on("error", async (err) => {
3306
- if (typeof RTCError !== "undefined" && err instanceof RTCError) {
3307
- if (err.errorDetail === "sctp-failure") {
3308
- this.errors.raise(new import_protocols7.ConnectionResetError("sctp-failure from RTCError", err));
3309
- } else {
3310
- this.errors.raise(new import_protocols7.UnknownProtocolError("unknown RTCError", err));
3311
- }
3312
- } else if ("code" in err) {
3313
- import_log11.log.info("simple-peer error", err, {
3314
- F: __dxlog_file12,
3315
- L: 78,
3316
- S: this,
3317
- C: (f, a) => f(...a)
3318
- });
3319
- switch (err.code) {
3320
- case "ERR_WEBRTC_SUPPORT":
3321
- this.errors.raise(new import_protocols7.ProtocolError("WebRTC not supported", err));
3322
- break;
3323
- case "ERR_ICE_CONNECTION_FAILURE":
3324
- case "ERR_DATA_CHANNEL":
3325
- case "ERR_CONNECTION_FAILURE":
3326
- case "ERR_SIGNALING":
3327
- this.errors.raise(new import_protocols7.ConnectivityError("unknown communication failure", err));
3328
- break;
3329
- case "ERR_CREATE_OFFER":
3330
- case "ERR_CREATE_ANSWER":
3331
- case "ERR_SET_LOCAL_DESCRIPTION":
3332
- case "ERR_SET_REMOTE_DESCRIPTION":
3333
- case "ERR_ADD_ICE_CANDIDATE":
3334
- this.errors.raise(new import_protocols7.UnknownProtocolError("unknown simple-peer library failure", err));
3335
- break;
3336
- default:
3337
- this.errors.raise(new Error("unknown simple-peer error"));
3338
- break;
3339
- }
3340
- } else {
3341
- import_log11.log.info("unknown peer connection error", err, {
3342
- F: __dxlog_file12,
3343
- L: 102,
3344
- S: this,
3345
- C: (f, a) => f(...a)
3346
- });
3347
- this.errors.raise(err);
3348
- }
3349
- try {
3350
- if (typeof this._peer?._pc?.getStats === "function") {
3351
- this._peer._pc.getStats().then((stats) => {
3352
- import_log11.log.info("report after webrtc error", {
3353
- config: this.params.webrtcConfig,
3354
- stats
3355
- }, {
3356
- F: __dxlog_file12,
3357
- L: 110,
3358
- S: this,
3359
- C: (f, a) => f(...a)
3360
- });
3361
- });
3362
- }
3363
- } catch (err2) {
3364
- import_log11.log.catch(err2, void 0, {
3365
- F: __dxlog_file12,
3366
- L: 117,
3367
- S: this,
3368
- C: (f, a) => f(...a)
3369
- });
3370
- }
3371
- await this.destroy();
3372
- });
3373
- import_log11.log.trace("dxos.mesh.webrtc-transport.constructor", import_protocols7.trace.end({
3374
- id: this._instanceId
3375
- }), {
3376
- F: __dxlog_file12,
3377
- L: 122,
3378
- S: this,
3379
- C: (f, a) => f(...a)
3380
- });
3381
- }
3382
- async destroy() {
3383
- (0, import_log11.log)("closing...", void 0, {
3384
- F: __dxlog_file12,
3385
- L: 126,
3386
- S: this,
3387
- C: (f, a) => f(...a)
3388
- });
3389
- if (this._closed) {
3390
- return;
3391
- }
3392
- this._closed = true;
3393
- this._disconnectStreams();
3394
- this._peer.destroy();
3395
- this.closed.emit();
3396
- (0, import_log11.log)("closed", void 0, {
3397
- F: __dxlog_file12,
3398
- L: 134,
3399
- S: this,
3400
- C: (f, a) => f(...a)
3401
- });
3402
- }
3403
- signal(signal) {
3404
- if (this._closed) {
3405
- return;
3406
- }
3407
- (0, import_tiny_invariant.default)(signal.payload.data, "Signal message must contain signal data.");
3408
- this._peer.signal(signal.payload.data);
3409
- }
3410
- _disconnectStreams() {
3411
- if (this._piped) {
3412
- this.params.stream.unpipe?.(this._peer)?.unpipe?.(this.params.stream);
3413
- }
3414
- }
3415
- };
3416
- var createSimplePeerTransportFactory = (webrtcConfig) => ({
3417
- createTransport: (params) => new SimplePeerTransport({
3418
- ...params,
3419
- webrtcConfig
3420
- })
3421
- });
3422
-
3423
- // packages/core/mesh/network-manager/src/transport/simplepeer-transport-service.ts
3424
- var import_node_stream2 = require("node:stream");
3425
- var import_codec_protobuf = require("@dxos/codec-protobuf");
3426
- var import_invariant11 = require("@dxos/invariant");
3427
- var import_keys11 = require("@dxos/keys");
3428
- var import_log12 = require("@dxos/log");
3429
- var import_bridge = require("@dxos/protocols/proto/dxos/mesh/bridge");
3430
- var import_util8 = require("@dxos/util");
3431
- var __dxlog_file13 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/transport/simplepeer-transport-service.ts";
3432
- var SimplePeerTransportService = class {
3433
- constructor(_webrtcConfig) {
3434
- this._webrtcConfig = _webrtcConfig;
3435
- this.transports = new import_util8.ComplexMap(import_keys11.PublicKey.hash);
3436
- }
3437
- open(request) {
3438
- const rpcStream = new import_codec_protobuf.Stream(({ ready, next, close }) => {
3439
- const duplex = new import_node_stream2.Duplex({
3440
- read: () => {
3441
- const callbacks = [
3442
- ...transportState.writeCallbacks
3443
- ];
3444
- transportState.writeCallbacks.length = 0;
3445
- for (const cb of callbacks) {
3446
- cb();
3447
- }
3448
- },
3449
- write: function(chunk, _, callback) {
3450
- next({
3451
- data: {
3452
- payload: chunk
3453
- }
3454
- });
3455
- callback();
3456
- }
3457
- });
3458
- const transport = new SimplePeerTransport({
3459
- initiator: request.initiator,
3460
- stream: duplex,
3461
- webrtcConfig: this._webrtcConfig,
3462
- sendSignal: async (signal) => {
3463
- next({
3464
- signal: {
3465
- payload: signal
3466
- }
3467
- });
3468
- }
3469
- });
3470
- next({
3471
- connection: {
3472
- state: import_bridge.ConnectionState.CONNECTING
3473
- }
3474
- });
3475
- transport.connected.on(() => {
3476
- next({
3477
- connection: {
3478
- state: import_bridge.ConnectionState.CONNECTED
3479
- }
3480
- });
3481
- });
3482
- transport.errors.handle((err) => {
3483
- next({
3484
- connection: {
3485
- state: import_bridge.ConnectionState.CLOSED,
3486
- error: err.toString()
3487
- }
3488
- });
3489
- close(err);
3490
- });
3491
- transport.closed.on(() => {
3492
- next({
3493
- connection: {
3494
- state: import_bridge.ConnectionState.CLOSED
3495
- }
3496
- });
3497
- close();
3498
- });
3499
- const transportState = {
3500
- transport,
3501
- stream: duplex,
3502
- writeCallbacks: [],
3503
- state: "OPEN"
3504
- };
3505
- ready();
3506
- this.transports.set(request.proxyId, transportState);
3507
- });
3508
- return rpcStream;
3509
- }
3510
- async sendSignal({ proxyId, signal }) {
3511
- (0, import_invariant11.invariant)(this.transports.has(proxyId), void 0, {
3512
- F: __dxlog_file13,
3513
- L: 112,
3514
- S: this,
3515
- A: [
3516
- "this.transports.has(proxyId)",
3517
- ""
3518
- ]
3519
- });
3520
- await this.transports.get(proxyId).transport.signal(signal);
3521
- }
3522
- async sendData({ proxyId, payload }) {
3523
- if (this.transports.get(proxyId)?.state !== "OPEN") {
3524
- import_log12.log.debug("transport is closed", void 0, {
3525
- F: __dxlog_file13,
3526
- L: 118,
3527
- S: this,
3528
- C: (f, a) => f(...a)
3529
- });
3530
- }
3531
- (0, import_invariant11.invariant)(this.transports.has(proxyId), void 0, {
3532
- F: __dxlog_file13,
3533
- L: 120,
3534
- S: this,
3535
- A: [
3536
- "this.transports.has(proxyId)",
3537
- ""
3538
- ]
3539
- });
3540
- const state = this.transports.get(proxyId);
3541
- const bufferHasSpace = state.stream.push(payload);
3542
- if (!bufferHasSpace) {
3543
- await new Promise((resolve) => {
3544
- state.writeCallbacks.push(resolve);
3545
- });
3546
- }
3547
- }
3548
- async close({ proxyId }) {
3549
- await this.transports.get(proxyId)?.transport.destroy();
3550
- await this.transports.get(proxyId)?.stream.end();
3551
- if (this.transports.get(proxyId)) {
3552
- this.transports.get(proxyId).state = "CLOSED";
3553
- }
3554
- (0, import_log12.log)("Closed.", void 0, {
3555
- F: __dxlog_file13,
3556
- L: 136,
3557
- S: this,
3558
- C: (f, a) => f(...a)
3559
- });
3560
- }
3561
- };
3562
-
3563
- // packages/core/mesh/network-manager/src/transport/simplepeer-transport-proxy.ts
3564
- var import_node_stream3 = require("node:stream");
3565
- var import_async10 = require("@dxos/async");
3566
- var import_context6 = require("@dxos/context");
3567
- var import_debug6 = require("@dxos/debug");
3568
- var import_invariant12 = require("@dxos/invariant");
3569
- var import_keys12 = require("@dxos/keys");
3570
- var import_log13 = require("@dxos/log");
3571
- var import_protocols8 = require("@dxos/protocols");
3572
- var import_bridge2 = require("@dxos/protocols/proto/dxos/mesh/bridge");
3573
- var import_util9 = require("@dxos/util");
3574
- var __dxlog_file14 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/transport/simplepeer-transport-proxy.ts";
3575
- var RESP_MIN_THRESHOLD = 500;
3576
- var TIMEOUT_THRESHOLD = 10;
3577
- var SimplePeerTransportProxy = class {
3578
- constructor(_params) {
3579
- this._params = _params;
3580
- this._proxyId = import_keys12.PublicKey.random();
3581
- this._ctx = new import_context6.Context();
3582
- this._timeoutCount = 0;
3583
- this.closed = new import_async10.Event();
3584
- this.connected = new import_async10.Event();
3585
- this.errors = new import_debug6.ErrorStream();
3586
- this._closed = false;
3587
- this._serviceStream = this._params.bridgeService.open({
3588
- proxyId: this._proxyId,
3589
- initiator: this._params.initiator
3590
- });
3591
- this._serviceStream.waitUntilReady().then(() => {
3592
- this._serviceStream.subscribe(async (event) => {
3593
- (0, import_log13.log)("SimplePeerTransportProxy: event", event, {
3594
- F: __dxlog_file14,
3595
- L: 59,
3596
- S: this,
3597
- C: (f, a) => f(...a)
3598
- });
3599
- if (event.connection) {
3600
- await this._handleConnection(event.connection);
3601
- } else if (event.data) {
3602
- this._handleData(event.data);
3603
- } else if (event.signal) {
3604
- await this._handleSignal(event.signal);
3605
- }
3606
- });
3607
- const proxyStream = new import_node_stream3.Writable({
3608
- write: (chunk, _, callback) => {
3609
- const then = performance.now();
3610
- this._params.bridgeService.sendData({
3611
- proxyId: this._proxyId,
3612
- payload: chunk
3613
- }).then(() => {
3614
- if (performance.now() - then > RESP_MIN_THRESHOLD) {
3615
- (0, import_log13.log)("slow response, delaying callback", void 0, {
3616
- F: __dxlog_file14,
3617
- L: 80,
3618
- S: this,
3619
- C: (f, a) => f(...a)
3620
- });
3621
- (0, import_async10.scheduleTask)(this._ctx, () => callback(), RESP_MIN_THRESHOLD);
3622
- } else {
3623
- callback();
3624
- }
3625
- this._timeoutCount = 0;
3626
- }, (err) => {
3627
- if (err instanceof import_protocols8.TimeoutError || err.constructor.name === "TimeoutError") {
3628
- if (this._timeoutCount++ > TIMEOUT_THRESHOLD) {
3629
- throw new import_protocols8.TimeoutError(`too many timeoutes (${this._timeoutCount} > ${TIMEOUT_THRESHOLD}`);
3630
- } else {
3631
- (0, import_log13.log)("timeout error, but still invoking callback", void 0, {
3632
- F: __dxlog_file14,
3633
- L: 92,
3634
- S: this,
3635
- C: (f, a) => f(...a)
3636
- });
3637
- callback();
3638
- }
3639
- } else {
3640
- import_log13.log.catch(err, void 0, {
3641
- F: __dxlog_file14,
3642
- L: 96,
3643
- S: this,
3644
- C: (f, a) => f(...a)
3645
- });
3646
- }
3647
- });
3648
- }
3649
- });
3650
- proxyStream.on("error", (err) => {
3651
- (0, import_log13.log)("proxystream error", {
3652
- err
3653
- }, {
3654
- F: __dxlog_file14,
3655
- L: 104,
3656
- S: this,
3657
- C: (f, a) => f(...a)
3658
- });
3659
- });
3660
- this._params.stream.pipe(proxyStream);
3661
- }, (error) => import_log13.log.catch(error, void 0, {
3662
- F: __dxlog_file14,
3663
- L: 109,
3664
- S: this,
3665
- C: (f, a) => f(...a)
3666
- }));
3667
- }
3668
- async _handleConnection(connectionEvent) {
3669
- if (connectionEvent.error) {
3670
- this.errors.raise(decodeError(connectionEvent.error));
3671
- }
3672
- switch (connectionEvent.state) {
3673
- case import_bridge2.ConnectionState.CONNECTED: {
3674
- this.connected.emit();
3675
- break;
3676
- }
3677
- case import_bridge2.ConnectionState.CLOSED: {
3678
- await this.destroy();
3679
- break;
3680
- }
3681
- }
3682
- }
3683
- _handleData(dataEvent) {
3684
- this._params.stream.write((0, import_util9.arrayToBuffer)(dataEvent.payload));
3685
- }
3686
- async _handleSignal(signalEvent) {
3687
- await this._params.sendSignal(signalEvent.payload);
3688
- }
3689
- signal(signal) {
3690
- this._params.bridgeService.sendSignal({
3691
- proxyId: this._proxyId,
3692
- signal
3693
- }).catch((err) => this.errors.raise(decodeError(err)));
3694
- }
3695
- // TODO(burdon): Move open from constructor.
3696
- async destroy() {
3697
- await this._ctx.dispose();
3698
- if (this._closed) {
3699
- return;
3700
- }
3701
- await this._serviceStream.close();
3702
- try {
3703
- await this._params.bridgeService.close({
3704
- proxyId: this._proxyId
3705
- });
3706
- } catch (err) {
3707
- import_log13.log.catch(err, void 0, {
3708
- F: __dxlog_file14,
3709
- L: 160,
3710
- S: this,
3711
- C: (f, a) => f(...a)
3712
- });
3713
- }
3714
- this.closed.emit();
3715
- this._closed = true;
3716
- }
3717
- /**
3718
- * Called when underlying proxy service becomes unavailable.
3719
- */
3720
- // TODO(burdon): Option on close method.
3721
- forceClose() {
3722
- void this._serviceStream.close();
3723
- this.closed.emit();
3724
- this._closed = true;
3725
- }
3726
- };
3727
- var SimplePeerTransportProxyFactory = class {
3728
- constructor() {
3729
- this._connections = /* @__PURE__ */ new Set();
3730
- }
3731
- /**
3732
- * Sets the current BridgeService to be used to open connections.
3733
- * Calling this method will close any existing connections.
3734
- */
3735
- setBridgeService(bridgeService) {
3736
- this._bridgeService = bridgeService;
3737
- for (const connection of this._connections) {
3738
- connection.forceClose();
3739
- }
3740
- return this;
3741
- }
3742
- createTransport(options) {
3743
- (0, import_invariant12.invariant)(this._bridgeService, "SimplePeerTransportProxyFactory is not ready to open connections", {
3744
- F: __dxlog_file14,
3745
- L: 197,
3746
- S: this,
3747
- A: [
3748
- "this._bridgeService",
3749
- "'SimplePeerTransportProxyFactory is not ready to open connections'"
3750
- ]
3751
- });
3752
- const transport = new SimplePeerTransportProxy({
3753
- ...options,
3754
- bridgeService: this._bridgeService
3755
- });
3756
- this._connections.add(transport);
3757
- transport.closed.on(() => this._connections.delete(transport));
3758
- return transport;
3759
- }
3760
- };
3761
- var decodeError = (err) => {
3762
- const message = typeof err === "string" ? err : err.message;
3763
- if (message.includes("CONNECTION_RESET")) {
3764
- return new import_protocols8.ConnectionResetError(message);
3765
- } else if (message.includes("TIMEOUT")) {
3766
- return new import_protocols8.TimeoutError(message);
3767
- } else if (message.includes("PROTOCOL_ERROR")) {
3768
- return new import_protocols8.ProtocolError(message);
3769
- } else if (message.includes("CONNECTIVITY_ERROR")) {
3770
- return new import_protocols8.ConnectivityError(message);
3771
- } else if (message.includes("UNKNOWN_PROTOCOL_ERROR")) {
3772
- return new import_protocols8.UnknownProtocolError(message);
3773
- } else {
3774
- return typeof err === "string" ? new Error(err) : err;
3775
- }
3776
- };
3777
-
3778
- // packages/core/mesh/network-manager/src/transport/index.ts
3779
- init_datachannel();
3780
-
3781
- // packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts
3782
- var import_stream = require("stream");
3783
- var import_async11 = require("@dxos/async");
3784
- var import_debug7 = require("@dxos/debug");
3785
- var import_log14 = require("@dxos/log");
3786
- function _ts_decorate5(decorators, target, key, desc) {
3787
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3788
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
3789
- r = Reflect.decorate(decorators, target, key, desc);
3790
- else
3791
- for (var i = decorators.length - 1; i >= 0; i--)
3792
- if (d = decorators[i])
3793
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
3794
- return c > 3 && r && Object.defineProperty(target, key, r), r;
3795
- }
3796
- var __dxlog_file15 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/transport/libdatachannel-transport.ts";
3797
- var DATACHANNEL_LABEL = "dxos.mesh.transport";
3798
- var MAX_BUFFERED_AMOUNT = 64 * 1024;
3799
- var MAX_MESSAGE_SIZE = 64 * 1024;
3800
- var LibDataChannelTransport = class {
3801
- constructor(params) {
3802
- this.params = params;
3803
- this._closed = false;
3804
- this.closed = new import_async11.Event();
3805
- this._connected = false;
3806
- this.connected = new import_async11.Event();
3807
- this.errors = new import_debug7.ErrorStream();
3808
- this._readyForCandidates = new import_async11.Trigger();
3809
- this._writeCallback = null;
3810
- this._peer = (async () => {
3811
- const { RTCPeerConnection: PeerConnection2 } = await Promise.resolve().then(() => (init_datachannel(), datachannel_exports));
3812
- if (this._closed) {
3813
- this.errors.raise(new Error("connection already closed"));
3814
- }
3815
- const peer = new PeerConnection2(params.webrtcConfig);
3816
- peer.onicecandidateerror = (event) => {
3817
- import_log14.log.error("peer.onicecandidateerror", {
3818
- event
3819
- }, {
3820
- F: __dxlog_file15,
3821
- L: 53,
3822
- S: this,
3823
- C: (f, a) => f(...a)
3824
- });
3825
- };
3826
- peer.onconnectionstatechange = (event) => {
3827
- import_log14.log.debug("peer.onconnectionstatechange", {
3828
- event,
3829
- peerConnectionState: peer.connectionState,
3830
- transportConnectionState: this._connected
3831
- }, {
3832
- F: __dxlog_file15,
3833
- L: 57,
3834
- S: this,
3835
- C: (f, a) => f(...a)
3836
- });
3837
- };
3838
- peer.onicecandidate = async (event) => {
3839
- import_log14.log.debug("peer.onicecandidate", {
3840
- event
3841
- }, {
3842
- F: __dxlog_file15,
3843
- L: 66,
3844
- S: this,
3845
- C: (f, a) => f(...a)
3846
- });
3847
- if (event.candidate) {
3848
- try {
3849
- await params.sendSignal({
3850
- payload: {
3851
- data: {
3852
- type: "candidate",
3853
- candidate: {
3854
- candidate: event.candidate.candidate,
3855
- // these fields never seem to be not null, but connecting to Chrome doesn't work if they are
3856
- sdpMLineIndex: event.candidate.sdpMLineIndex ?? 0,
3857
- sdpMid: event.candidate.sdpMid ?? 0
3858
- }
3859
- }
3860
- }
3861
- });
3862
- } catch (err) {
3863
- import_log14.log.info("signaling errror", {
3864
- err
3865
- }, {
3866
- F: __dxlog_file15,
3867
- L: 83,
3868
- S: this,
3869
- C: (f, a) => f(...a)
3870
- });
3871
- }
3872
- }
3873
- };
3874
- if (params.initiator) {
3875
- peer.createOffer().then(async (offer) => {
3876
- if (peer.connectionState !== "connecting") {
3877
- import_log14.log.error("i am initiator but peer not in state connecting", {
3878
- peer
3879
- }, {
3880
- F: __dxlog_file15,
3881
- L: 92,
3882
- S: this,
3883
- C: (f, a) => f(...a)
3884
- });
3885
- this.errors.raise(new Error("invalid state: peer is initiator, but other peer not in state connecting"));
3886
- }
3887
- import_log14.log.debug(`im the initiator, creating offer, peer is in state ${peer.connectionState}`, {
3888
- offer
3889
- }, {
3890
- F: __dxlog_file15,
3891
- L: 95,
3892
- S: this,
3893
- C: (f, a) => f(...a)
3894
- });
3895
- await peer.setLocalDescription(offer);
3896
- await params.sendSignal({
3897
- payload: {
3898
- data: {
3899
- type: offer.type,
3900
- sdp: offer.sdp
3901
- }
3902
- }
3903
- });
3904
- return offer;
3905
- }).catch((err) => {
3906
- this.errors.raise(err);
3907
- });
3908
- this.handleChannel(peer.createDataChannel(DATACHANNEL_LABEL));
3909
- import_log14.log.debug("created data channel", void 0, {
3910
- F: __dxlog_file15,
3911
- L: 104,
3912
- S: this,
3913
- C: (f, a) => f(...a)
3914
- });
3915
- peer.ondatachannel = (event) => {
3916
- this.errors.raise(new Error("got ondatachannel when i am the initiator?"));
3917
- };
3918
- } else {
3919
- peer.ondatachannel = (event) => {
3920
- import_log14.log.debug("peer.ondatachannel (non-initiator)", {
3921
- event
3922
- }, {
3923
- F: __dxlog_file15,
3924
- L: 110,
3925
- S: this,
3926
- C: (f, a) => f(...a)
3927
- });
3928
- if (event.channel.label !== DATACHANNEL_LABEL) {
3929
- this.errors.raise(new Error(`unexpected channel label ${event.channel.label}`));
3930
- }
3931
- this.handleChannel(event.channel);
3932
- };
3933
- }
3934
- return peer;
3935
- })();
3936
- }
3937
- handleChannel(dataChannel) {
3938
- this._channel = dataChannel;
3939
- this._channel.onopen = () => {
3940
- import_log14.log.debug("dataChannel.onopen", void 0, {
3941
- F: __dxlog_file15,
3942
- L: 126,
3943
- S: this,
3944
- C: (f, a) => f(...a)
3945
- });
3946
- const duplex = new import_stream.Duplex({
3947
- read: () => {
3948
- },
3949
- write: (chunk, encoding, callback) => {
3950
- if (chunk.length > MAX_MESSAGE_SIZE) {
3951
- this.errors.raise(new Error(`message too large: ${chunk.length} > ${MAX_MESSAGE_SIZE}`));
3952
- }
3953
- dataChannel.send(chunk);
3954
- if (this._channel.bufferedAmount > MAX_BUFFERED_AMOUNT) {
3955
- if (this._writeCallback !== null) {
3956
- import_log14.log.error("consumer trying to write before we're ready for more data", void 0, {
3957
- F: __dxlog_file15,
3958
- L: 139,
3959
- S: this,
3960
- C: (f, a) => f(...a)
3961
- });
3962
- }
3963
- this._writeCallback = callback;
3964
- } else {
3965
- callback();
3966
- }
3967
- }
3968
- });
3969
- duplex.pipe(this.params.stream).pipe(duplex);
3970
- this._stream = duplex;
3971
- this._connected = true;
3972
- this.connected.emit();
3973
- };
3974
- this._channel.onerror = async (err) => {
3975
- this.errors.raise(new Error("channel error: " + err.toString()));
3976
- await this._close();
3977
- };
3978
- this._channel.onclose = async (err) => {
3979
- import_log14.log.info("channel onclose", {
3980
- err
3981
- }, {
3982
- F: __dxlog_file15,
3983
- L: 159,
3984
- S: this,
3985
- C: (f, a) => f(...a)
3986
- });
3987
- await this._close();
3988
- };
3989
- this._channel.onmessage = (event) => {
3990
- let data = event.data;
3991
- if (data instanceof ArrayBuffer) {
3992
- data = Buffer.from(data);
3993
- }
3994
- this._stream.push(data);
3995
- };
3996
- this._channel.onbufferedamountlow = () => {
3997
- const cb = this._writeCallback;
3998
- this._writeCallback = null;
3999
- cb?.();
4000
- };
4001
- }
4002
- async _close() {
4003
- if (this._closed) {
4004
- return;
4005
- }
4006
- await this._disconnectStreams();
4007
- this._closed = true;
4008
- this.closed.emit();
4009
- }
4010
- signal(signal) {
4011
- this._peer.then(async (peer) => {
4012
- const data = signal.payload.data;
4013
- switch (data.type) {
4014
- case "offer": {
4015
- if ((await this._peer).connectionState !== "new") {
4016
- import_log14.log.error("received offer but peer not in state new", {
4017
- peer
4018
- }, {
4019
- F: __dxlog_file15,
4020
- L: 194,
4021
- S: this,
4022
- C: (f, a) => f(...a)
4023
- });
4024
- this.errors.raise(new Error("invalid signalling state: received offer when peer is not in state new"));
4025
- break;
4026
- }
4027
- try {
4028
- await peer.setRemoteDescription({
4029
- type: data.type,
4030
- sdp: data.sdp
4031
- });
4032
- const answer = await peer.createAnswer();
4033
- await peer.setLocalDescription(answer);
4034
- await this.params.sendSignal({
4035
- payload: {
4036
- data: {
4037
- type: answer.type,
4038
- sdp: answer.sdp
4039
- }
4040
- }
4041
- });
4042
- this._readyForCandidates.wake();
4043
- } catch (err) {
4044
- import_log14.log.error("can't handle offer from signalling server", {
4045
- err
4046
- }, {
4047
- F: __dxlog_file15,
4048
- L: 205,
4049
- S: this,
4050
- C: (f, a) => f(...a)
4051
- });
4052
- this.errors.raise(new Error("error handling offer"));
4053
- }
4054
- break;
4055
- }
4056
- case "answer":
4057
- try {
4058
- await peer.setRemoteDescription({
4059
- type: data.type,
4060
- sdp: data.sdp
4061
- });
4062
- this._readyForCandidates.wake();
4063
- } catch (err) {
4064
- import_log14.log.error("can't handle answer from signalling server", {
4065
- err
4066
- }, {
4067
- F: __dxlog_file15,
4068
- L: 216,
4069
- S: this,
4070
- C: (f, a) => f(...a)
4071
- });
4072
- this.errors.raise(new Error("error handling answer"));
4073
- }
4074
- break;
4075
- case "candidate":
4076
- await this._readyForCandidates.wait();
4077
- await peer.addIceCandidate({
4078
- candidate: data.candidate.candidate
4079
- });
4080
- break;
4081
- default:
4082
- import_log14.log.error("unhandled signal type", {
4083
- type: data.type,
4084
- signal
4085
- }, {
4086
- F: __dxlog_file15,
4087
- L: 227,
4088
- S: this,
4089
- C: (f, a) => f(...a)
4090
- });
4091
- this.errors.raise(new Error(`unhandled signal type ${data.type}`));
4092
- }
4093
- }).catch((err) => {
4094
- import_log14.log.catch(err, void 0, {
4095
- F: __dxlog_file15,
4096
- L: 232,
4097
- S: this,
4098
- C: (f, a) => f(...a)
4099
- });
4100
- });
4101
- }
4102
- // TODO(nf): add classmethod to call node-datachannel.cleanup() when all instances have been destroyed?
4103
- async destroy() {
4104
- await this._close();
4105
- }
4106
- async _disconnectStreams() {
4107
- this.params.stream.unpipe?.(this._stream)?.unpipe?.(this.params.stream);
4108
- }
4109
- };
4110
- _ts_decorate5([
4111
- import_async11.synchronized
4112
- ], LibDataChannelTransport.prototype, "_close", null);
4113
- var createLibDataChannelTransportFactory = (webrtcConfig) => ({
4114
- createTransport: (params) => new LibDataChannelTransport({
4115
- ...params,
4116
- webrtcConfig
4117
- })
4118
- });
4119
-
4120
- // packages/core/mesh/network-manager/src/transport/tcp-transport.ts
4121
- var import_node_net = require("node:net");
4122
- var import_async12 = require("@dxos/async");
4123
- var import_debug8 = require("@dxos/debug");
4124
- var import_log15 = require("@dxos/log");
4125
- var __dxlog_file16 = "/mnt/ramdisk/work/packages/core/mesh/network-manager/src/transport/tcp-transport.ts";
4126
- var TcpTransportFactory = {
4127
- createTransport: (params) => new TcpTransport(params)
4128
- };
4129
- var TcpTransport = class {
4130
- constructor(options) {
4131
- this.options = options;
4132
- this._server = void 0;
4133
- this._socket = void 0;
4134
- this.closed = new import_async12.Event();
4135
- this.connected = new import_async12.Event();
4136
- this.errors = new import_debug8.ErrorStream();
4137
- this._destroyed = false;
4138
- this._connected = false;
4139
- (0, import_log15.log)("creating", void 0, {
4140
- F: __dxlog_file16,
4141
- L: 34,
4142
- S: this,
4143
- C: (f, a) => f(...a)
4144
- });
4145
- if (this.options.initiator) {
4146
- setTimeout(async () => {
4147
- const { Server } = await import("node:net");
4148
- this._server = new Server((socket) => {
4149
- (0, import_log15.log)("new connection", void 0, {
4150
- F: __dxlog_file16,
4151
- L: 42,
4152
- S: this,
4153
- C: (f, a) => f(...a)
4154
- });
4155
- if (this._connected) {
4156
- socket.destroy();
4157
- }
4158
- this._handleSocket(socket);
4159
- });
4160
- this._server.on("listening", () => {
4161
- const { port } = this._server.address();
4162
- (0, import_log15.log)("listening", {
4163
- port
4164
- }, {
4165
- F: __dxlog_file16,
4166
- L: 51,
4167
- S: this,
4168
- C: (f, a) => f(...a)
4169
- });
4170
- void this.options.sendSignal({
4171
- payload: {
4172
- port
4173
- }
4174
- }).catch((err) => {
4175
- if (!this._destroyed) {
4176
- this.errors.raise(err);
4177
- }
4178
- });
4179
- });
4180
- this._server.on("error", (err) => {
4181
- this.errors.raise(err);
4182
- });
4183
- this._server.listen(0);
4184
- });
4185
- }
4186
- }
4187
- async destroy() {
4188
- (0, import_log15.log)("closing", void 0, {
4189
- F: __dxlog_file16,
4190
- L: 72,
4191
- S: this,
4192
- C: (f, a) => f(...a)
4193
- });
4194
- this._socket?.destroy();
4195
- this._server?.close();
4196
- this._destroyed = true;
4197
- }
4198
- signal({ payload }) {
4199
- (0, import_log15.log)("received signal", {
4200
- payload
4201
- }, {
4202
- F: __dxlog_file16,
4203
- L: 80,
4204
- S: this,
4205
- C: (f, a) => f(...a)
4206
- });
4207
- if (this.options.initiator || this._connected) {
4208
- return;
4209
- }
4210
- const socket = new import_node_net.Socket();
4211
- this._handleSocket(socket);
4212
- socket.connect({
4213
- port: payload.port,
4214
- host: "localhost"
4215
- });
4216
- }
4217
- _handleSocket(socket) {
4218
- (0, import_log15.log)("handling socket", {
4219
- remotePort: socket.remotePort,
4220
- localPort: socket.localPort
4221
- }, {
4222
- F: __dxlog_file16,
4223
- L: 91,
4224
- S: this,
4225
- C: (f, a) => f(...a)
4226
- });
4227
- this._socket = socket;
4228
- this.connected.emit();
4229
- this.options.stream.pipe(this._socket).pipe(this.options.stream);
4230
- this._socket.on("connect", () => {
4231
- (0, import_log15.log)("connected to", {
4232
- port: this._socket?.remotePort
4233
- }, {
4234
- F: __dxlog_file16,
4235
- L: 97,
4236
- S: this,
4237
- C: (f, a) => f(...a)
4238
- });
4239
- this._connected = true;
4240
- });
4241
- this._socket.on("error", (err) => {
4242
- this.errors.raise(err);
4243
- });
4244
- this._socket.on("close", () => {
4245
- this.closed.emit();
4246
- });
4247
- }
4248
- };
4249
-
4250
- // packages/core/mesh/network-manager/src/wire-protocol.ts
4251
- var import_teleport = require("@dxos/teleport");
4252
- var createTeleportProtocolFactory = (onConnection) => {
4253
- return (params) => {
4254
- const teleport = new import_teleport.Teleport(params);
4255
- return {
4256
- stream: teleport.stream,
4257
- open: async () => {
4258
- await teleport.open();
4259
- await onConnection(teleport);
4260
- },
4261
- close: async () => {
4262
- await teleport.close();
4263
- },
4264
- abort: async () => {
4265
- await teleport.abort();
4266
- }
4267
- };
4268
- };
4269
- };
52
+ module.exports = __toCommonJS(node_exports);
53
+ var import_chunk_PWHTYBOL = require("./chunk-PWHTYBOL.cjs");
54
+ var import_chunk_XE5JOIGD = require("./chunk-XE5JOIGD.cjs");
4270
55
  // Annotate the CommonJS export names for ESM import in node:
4271
56
  0 && (module.exports = {
4272
57
  Connection,