@dxos/teleport 0.3.8-next.f4e0086 → 0.3.9-main.14901ff

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,9 +1,7 @@
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
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,1894 +15,17 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // packages/core/mesh/teleport/src/testing/index.ts
31
19
  var testing_exports = {};
32
20
  __export(testing_exports, {
33
- TestBuilder: () => TestBuilder,
34
- TestConnection: () => TestConnection,
35
- TestExtension: () => TestExtension,
36
- TestExtensionWithStreams: () => TestExtensionWithStreams,
37
- TestPeer: () => TestPeer
21
+ TestBuilder: () => import_chunk_GVV33WCQ.TestBuilder,
22
+ TestConnection: () => import_chunk_GVV33WCQ.TestConnection,
23
+ TestExtension: () => import_chunk_GVV33WCQ.TestExtension,
24
+ TestExtensionWithStreams: () => import_chunk_GVV33WCQ.TestExtensionWithStreams,
25
+ TestPeer: () => import_chunk_GVV33WCQ.TestPeer
38
26
  });
39
27
  module.exports = __toCommonJS(testing_exports);
40
-
41
- // packages/core/mesh/teleport/src/testing/test-builder.ts
42
- var import_node_stream3 = require("node:stream");
43
- var import_invariant5 = require("@dxos/invariant");
44
- var import_keys2 = require("@dxos/keys");
45
- var import_log6 = require("@dxos/log");
46
-
47
- // packages/core/mesh/teleport/src/teleport.ts
48
- var import_async5 = require("@dxos/async");
49
- var import_context3 = require("@dxos/context");
50
- var import_debug2 = require("@dxos/debug");
51
- var import_invariant4 = require("@dxos/invariant");
52
- var import_keys = require("@dxos/keys");
53
- var import_log5 = require("@dxos/log");
54
- var import_protocols3 = require("@dxos/protocols");
55
-
56
- // packages/core/mesh/teleport/src/control-extension.ts
57
- var import_async = require("@dxos/async");
58
- var import_context = require("@dxos/context");
59
- var import_log = require("@dxos/log");
60
- var import_protocols = require("@dxos/protocols");
61
- var import_rpc = require("@dxos/rpc");
62
- var import_util = require("@dxos/util");
63
- var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts";
64
- var HEARTBEAT_RTT_WARN_THRESH = 1e4;
65
- var ControlExtension = class {
66
- constructor(opts, localPeerId, remotePeerId) {
67
- this.opts = opts;
68
- this.localPeerId = localPeerId;
69
- this.remotePeerId = remotePeerId;
70
- this._ctx = new import_context.Context({
71
- onError: (err) => {
72
- this._extensionContext.close(err);
73
- }
74
- });
75
- this.onExtensionRegistered = new import_util.Callback();
76
- }
77
- async registerExtension(name) {
78
- await this._rpc.rpc.Control.registerExtension({
79
- name
80
- });
81
- }
82
- async onOpen(extensionContext) {
83
- this._extensionContext = extensionContext;
84
- this._rpc = (0, import_rpc.createProtoRpcPeer)({
85
- requested: {
86
- Control: import_protocols.schema.getService("dxos.mesh.teleport.control.ControlService")
87
- },
88
- exposed: {
89
- Control: import_protocols.schema.getService("dxos.mesh.teleport.control.ControlService")
90
- },
91
- handlers: {
92
- Control: {
93
- registerExtension: async (request) => {
94
- this.onExtensionRegistered.call(request.name);
95
- },
96
- heartbeat: async (request) => {
97
- (0, import_log.log)("received heartbeat request", {
98
- ts: request.requestTimestamp,
99
- localPeerId: this.localPeerId.truncate(),
100
- remotePeerId: this.remotePeerId.truncate()
101
- }, {
102
- F: __dxlog_file,
103
- L: 66,
104
- S: this,
105
- C: (f, a) => f(...a)
106
- });
107
- return {
108
- requestTimestamp: request.requestTimestamp
109
- };
110
- }
111
- }
112
- },
113
- port: await extensionContext.createPort("rpc", {
114
- contentType: 'application/x-protobuf; messageType="dxos.rpc.Message"'
115
- }),
116
- timeout: this.opts.heartbeatTimeout
117
- });
118
- await this._rpc.open();
119
- (0, import_async.scheduleTaskInterval)(this._ctx, async () => {
120
- const reqTS = /* @__PURE__ */ new Date();
121
- try {
122
- const resp = await (0, import_async.asyncTimeout)(this._rpc.rpc.Control.heartbeat({
123
- requestTimestamp: reqTS
124
- }), this.opts.heartbeatTimeout);
125
- const now = Date.now();
126
- if (resp.requestTimestamp instanceof Date) {
127
- if (now - resp.requestTimestamp.getTime() > (HEARTBEAT_RTT_WARN_THRESH < this.opts.heartbeatTimeout ? HEARTBEAT_RTT_WARN_THRESH : this.opts.heartbeatTimeout / 2)) {
128
- import_log.log.warn(`heartbeat RTT for Teleport > ${HEARTBEAT_RTT_WARN_THRESH / 1e3}s`, {
129
- rtt: now - resp.requestTimestamp.getTime(),
130
- localPeerId: this.localPeerId.truncate(),
131
- remotePeerId: this.remotePeerId.truncate()
132
- }, {
133
- F: __dxlog_file,
134
- L: 103,
135
- S: this,
136
- C: (f, a) => f(...a)
137
- });
138
- } else {
139
- (0, import_log.log)("heartbeat RTT", {
140
- rtt: now - resp.requestTimestamp.getTime(),
141
- localPeerId: this.localPeerId.truncate(),
142
- remotePeerId: this.remotePeerId.truncate()
143
- }, {
144
- F: __dxlog_file,
145
- L: 109,
146
- S: this,
147
- C: (f, a) => f(...a)
148
- });
149
- }
150
- }
151
- } catch (err) {
152
- const now = Date.now();
153
- if (err instanceof import_protocols.RpcClosedError) {
154
- (0, import_log.log)("ignoring RpcClosedError in heartbeat", void 0, {
155
- F: __dxlog_file,
156
- L: 119,
157
- S: this,
158
- C: (f, a) => f(...a)
159
- });
160
- return;
161
- }
162
- if (err instanceof import_async.TimeoutError) {
163
- (0, import_log.log)("timeout waiting for heartbeat response", {
164
- err,
165
- delay: now - reqTS.getTime()
166
- }, {
167
- F: __dxlog_file,
168
- L: 123,
169
- S: this,
170
- C: (f, a) => f(...a)
171
- });
172
- this.opts.onTimeout(err);
173
- } else {
174
- import_log.log.info("other error waiting for heartbeat response", {
175
- err,
176
- delay: now - reqTS.getTime()
177
- }, {
178
- F: __dxlog_file,
179
- L: 126,
180
- S: this,
181
- C: (f, a) => f(...a)
182
- });
183
- this.opts.onTimeout(err);
184
- }
185
- }
186
- }, this.opts.heartbeatInterval);
187
- }
188
- async onClose(err) {
189
- await this._ctx.dispose();
190
- await this._rpc.close();
191
- }
192
- async onAbort(err) {
193
- await this._ctx.dispose();
194
- await this._rpc.abort();
195
- }
196
- };
197
-
198
- // packages/core/mesh/teleport/src/muxing/framer.ts
199
- var import_node_stream = require("node:stream");
200
- var import_async2 = require("@dxos/async");
201
- var import_invariant = require("@dxos/invariant");
202
- var import_log2 = require("@dxos/log");
203
- var __dxlog_file2 = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts";
204
- var FRAME_LENGTH_SIZE = 2;
205
- var Framer = class {
206
- constructor() {
207
- // private readonly _tagBuffer = Buffer.alloc(4)
208
- this._messageCb = void 0;
209
- this._subscribeCb = void 0;
210
- this._buffer = void 0;
211
- this._sendCallbacks = [];
212
- this._bytesSent = 0;
213
- this._bytesReceived = 0;
214
- this._writable = true;
215
- this.drain = new import_async2.Event();
216
- // TODO(egorgripasov): Consider using a Transform stream if it provides better backpressure handling.
217
- this._stream = new import_node_stream.Duplex({
218
- objectMode: false,
219
- read: () => {
220
- this._processResponseQueue();
221
- },
222
- write: (chunk, encoding, callback) => {
223
- (0, import_invariant.invariant)(!this._subscribeCb, "Internal Framer bug. Concurrent writes detected.", {
224
- F: __dxlog_file2,
225
- L: 40,
226
- S: this,
227
- A: [
228
- "!this._subscribeCb",
229
- "'Internal Framer bug. Concurrent writes detected.'"
230
- ]
231
- });
232
- this._bytesReceived += chunk.length;
233
- if (this._buffer && this._buffer.length > 0) {
234
- this._buffer = Buffer.concat([
235
- this._buffer,
236
- chunk
237
- ]);
238
- } else {
239
- this._buffer = chunk;
240
- }
241
- if (this._messageCb) {
242
- this._popFrames();
243
- callback();
244
- } else {
245
- this._subscribeCb = () => {
246
- this._popFrames();
247
- this._subscribeCb = void 0;
248
- callback();
249
- };
250
- }
251
- }
252
- });
253
- this.port = {
254
- send: (message) => {
255
- return new Promise((resolve) => {
256
- const frame = encodeFrame(message);
257
- this._bytesSent += frame.length;
258
- this._writable = this._stream.push(frame);
259
- if (!this._writable) {
260
- this._sendCallbacks.push(resolve);
261
- } else {
262
- resolve();
263
- }
264
- });
265
- },
266
- subscribe: (callback) => {
267
- (0, import_invariant.invariant)(!this._messageCb, "Rpc port already has a message listener.", {
268
- F: __dxlog_file2,
269
- L: 79,
270
- S: this,
271
- A: [
272
- "!this._messageCb",
273
- "'Rpc port already has a message listener.'"
274
- ]
275
- });
276
- this._messageCb = callback;
277
- this._subscribeCb?.();
278
- return () => {
279
- this._messageCb = void 0;
280
- };
281
- }
282
- };
283
- }
284
- get stream() {
285
- return this._stream;
286
- }
287
- get bytesSent() {
288
- return this._bytesSent;
289
- }
290
- get bytesReceived() {
291
- return this._bytesReceived;
292
- }
293
- get writable() {
294
- return this._writable;
295
- }
296
- _processResponseQueue() {
297
- const responseQueue = this._sendCallbacks;
298
- this._sendCallbacks = [];
299
- this._writable = true;
300
- this.drain.emit();
301
- responseQueue.forEach((cb) => cb());
302
- }
303
- /**
304
- * Attempts to pop frames from the buffer and call the message callback.
305
- */
306
- _popFrames() {
307
- let offset = 0;
308
- while (offset < this._buffer.length) {
309
- const frame = decodeFrame(this._buffer, offset);
310
- if (!frame) {
311
- break;
312
- }
313
- offset += frame.bytesConsumed;
314
- this._messageCb(frame.payload);
315
- }
316
- if (offset < this._buffer.length) {
317
- this._buffer = this._buffer.subarray(offset);
318
- } else {
319
- this._buffer = void 0;
320
- }
321
- }
322
- destroy() {
323
- if (this._stream.readableLength > 0) {
324
- import_log2.log.info("framer destroyed while there are still read bytes in the buffer.", void 0, {
325
- F: __dxlog_file2,
326
- L: 140,
327
- S: this,
328
- C: (f, a) => f(...a)
329
- });
330
- }
331
- if (this._stream.writableLength > 0) {
332
- import_log2.log.warn("framer destroyed while there are still write bytes in the buffer.", void 0, {
333
- F: __dxlog_file2,
334
- L: 143,
335
- S: this,
336
- C: (f, a) => f(...a)
337
- });
338
- }
339
- this._stream.destroy();
340
- }
341
- };
342
- var decodeFrame = (buffer, offset) => {
343
- if (buffer.length < offset + FRAME_LENGTH_SIZE) {
344
- return void 0;
345
- }
346
- const frameLength = buffer.readUInt16BE(offset);
347
- const bytesConsumed = FRAME_LENGTH_SIZE + frameLength;
348
- if (buffer.length < offset + bytesConsumed) {
349
- return void 0;
350
- }
351
- const payload = buffer.subarray(offset + FRAME_LENGTH_SIZE, offset + bytesConsumed);
352
- return {
353
- payload,
354
- bytesConsumed
355
- };
356
- };
357
- var encodeFrame = (payload) => {
358
- const frame = Buffer.allocUnsafe(FRAME_LENGTH_SIZE + payload.length);
359
- frame.writeUInt16BE(payload.length, 0);
360
- frame.set(payload, FRAME_LENGTH_SIZE);
361
- return frame;
362
- };
363
-
364
- // packages/core/mesh/teleport/src/muxing/muxer.ts
365
- var import_node_stream2 = require("node:stream");
366
- var import_async4 = require("@dxos/async");
367
- var import_context2 = require("@dxos/context");
368
- var import_debug = require("@dxos/debug");
369
- var import_invariant3 = require("@dxos/invariant");
370
- var import_log4 = require("@dxos/log");
371
- var import_protocols2 = require("@dxos/protocols");
372
-
373
- // packages/core/mesh/teleport/src/muxing/balancer.ts
374
- var varint = __toESM(require("varint"));
375
- var import_async3 = require("@dxos/async");
376
- var import_invariant2 = require("@dxos/invariant");
377
- var import_log3 = require("@dxos/log");
378
- var __dxlog_file3 = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/balancer.ts";
379
- var MAX_CHUNK_SIZE = 8192;
380
- var Balancer = class {
381
- constructor(_sysChannelId) {
382
- this._sysChannelId = _sysChannelId;
383
- this._lastCallerIndex = 0;
384
- this._channels = [];
385
- this._framer = new Framer();
386
- this._sendBuffers = /* @__PURE__ */ new Map();
387
- this._receiveBuffers = /* @__PURE__ */ new Map();
388
- this._sending = false;
389
- this.incomingData = new import_async3.Event();
390
- this.stream = this._framer.stream;
391
- this._channels.push(_sysChannelId);
392
- this._framer.port.subscribe(this._processIncomingMessage.bind(this));
393
- }
394
- get bytesSent() {
395
- return this._framer.bytesSent;
396
- }
397
- get bytesReceived() {
398
- return this._framer.bytesReceived;
399
- }
400
- get buffersCount() {
401
- return this._sendBuffers.size;
402
- }
403
- addChannel(channel) {
404
- this._channels.push(channel);
405
- }
406
- pushData(data, trigger, channelId) {
407
- this._enqueueChunk(data, trigger, channelId);
408
- this._sendChunks().catch((err) => import_log3.log.catch(err, void 0, {
409
- F: __dxlog_file3,
410
- L: 75,
411
- S: this,
412
- C: (f, a) => f(...a)
413
- }));
414
- }
415
- destroy() {
416
- if (this._sendBuffers.size !== 0) {
417
- import_log3.log.info("destroying balancer with pending calls", void 0, {
418
- F: __dxlog_file3,
419
- L: 80,
420
- S: this,
421
- C: (f, a) => f(...a)
422
- });
423
- }
424
- this._sendBuffers.clear();
425
- this._framer.destroy();
426
- }
427
- _processIncomingMessage(msg) {
428
- const { channelId, dataLength, chunk } = decodeChunk(msg, (channelId2) => !this._receiveBuffers.has(channelId2));
429
- if (!this._receiveBuffers.has(channelId)) {
430
- if (chunk.length < dataLength) {
431
- this._receiveBuffers.set(channelId, {
432
- buffer: Buffer.from(chunk),
433
- msgLength: dataLength
434
- });
435
- } else {
436
- this.incomingData.emit(chunk);
437
- }
438
- } else {
439
- const channelBuffer = this._receiveBuffers.get(channelId);
440
- channelBuffer.buffer = Buffer.concat([
441
- channelBuffer.buffer,
442
- chunk
443
- ]);
444
- if (channelBuffer.buffer.length < channelBuffer.msgLength) {
445
- return;
446
- }
447
- const msg2 = channelBuffer.buffer;
448
- this._receiveBuffers.delete(channelId);
449
- this.incomingData.emit(msg2);
450
- }
451
- }
452
- _getNextCallerId() {
453
- if (this._sendBuffers.has(this._sysChannelId)) {
454
- return this._sysChannelId;
455
- }
456
- const index = this._lastCallerIndex;
457
- this._lastCallerIndex = (this._lastCallerIndex + 1) % this._channels.length;
458
- return this._channels[index];
459
- }
460
- _enqueueChunk(data, trigger, channelId) {
461
- if (!this._channels.includes(channelId)) {
462
- throw new Error(`Unknown channel ${channelId}`);
463
- }
464
- if (!this._sendBuffers.has(channelId)) {
465
- this._sendBuffers.set(channelId, []);
466
- }
467
- const sendBuffer = this._sendBuffers.get(channelId);
468
- const chunks = [];
469
- for (let idx = 0; idx < data.length; idx += MAX_CHUNK_SIZE) {
470
- chunks.push(data.subarray(idx, idx + MAX_CHUNK_SIZE));
471
- }
472
- chunks.forEach((chunk, index) => {
473
- const msg = encodeChunk({
474
- chunk,
475
- channelId,
476
- dataLength: index === 0 ? data.length : void 0
477
- });
478
- sendBuffer.push({
479
- msg,
480
- trigger: index === chunks.length - 1 ? trigger : void 0
481
- });
482
- });
483
- }
484
- // get the next chunk or null if there are no chunks remaining
485
- _getNextChunk() {
486
- let chunk;
487
- while (this._sendBuffers.size > 0) {
488
- const channelId = this._getNextCallerId();
489
- const sendBuffer = this._sendBuffers.get(channelId);
490
- if (!sendBuffer) {
491
- continue;
492
- }
493
- chunk = sendBuffer.shift();
494
- if (!chunk) {
495
- continue;
496
- }
497
- if (sendBuffer.length === 0) {
498
- this._sendBuffers.delete(channelId);
499
- }
500
- return chunk;
501
- }
502
- return null;
503
- }
504
- async _sendChunks() {
505
- if (this._sending) {
506
- return;
507
- }
508
- this._sending = true;
509
- let chunk;
510
- chunk = this._getNextChunk();
511
- while (chunk) {
512
- if (!this._framer.writable) {
513
- (0, import_log3.log)("PAUSE for drain", void 0, {
514
- F: __dxlog_file3,
515
- L: 179,
516
- S: this,
517
- C: (f, a) => f(...a)
518
- });
519
- await this._framer.drain.waitForCount(1);
520
- (0, import_log3.log)("RESUME for drain", void 0, {
521
- F: __dxlog_file3,
522
- L: 181,
523
- S: this,
524
- C: (f, a) => f(...a)
525
- });
526
- }
527
- try {
528
- await this._framer.port.send(chunk.msg);
529
- chunk.trigger?.wake();
530
- } catch (err) {
531
- (0, import_log3.log)("Error sending chunk", {
532
- err
533
- }, {
534
- F: __dxlog_file3,
535
- L: 187,
536
- S: this,
537
- C: (f, a) => f(...a)
538
- });
539
- chunk.trigger?.throw(err);
540
- }
541
- chunk = this._getNextChunk();
542
- }
543
- (0, import_invariant2.invariant)(this._sendBuffers.size === 0, "sendBuffers not empty", {
544
- F: __dxlog_file3,
545
- L: 192,
546
- S: this,
547
- A: [
548
- "this._sendBuffers.size === 0",
549
- "'sendBuffers not empty'"
550
- ]
551
- });
552
- this._sending = false;
553
- }
554
- };
555
- var encodeChunk = ({ channelId, dataLength, chunk }) => {
556
- const channelTagLength = varint.encodingLength(channelId);
557
- const dataLengthLength = dataLength ? varint.encodingLength(dataLength) : 0;
558
- const message = Buffer.allocUnsafe(channelTagLength + dataLengthLength + chunk.length);
559
- varint.encode(channelId, message);
560
- if (dataLength) {
561
- varint.encode(dataLength, message, channelTagLength);
562
- }
563
- message.set(chunk, channelTagLength + dataLengthLength);
564
- return message;
565
- };
566
- var decodeChunk = (data, withLength) => {
567
- const channelId = varint.decode(data);
568
- let dataLength;
569
- let offset = varint.decode.bytes;
570
- if (withLength(channelId)) {
571
- dataLength = varint.decode(data, offset);
572
- offset += varint.decode.bytes;
573
- }
574
- const chunk = data.subarray(offset);
575
- return {
576
- channelId,
577
- dataLength,
578
- chunk
579
- };
580
- };
581
-
582
- // packages/core/mesh/teleport/src/muxing/muxer.ts
583
- var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts";
584
- var Command = import_protocols2.schema.getCodecForType("dxos.mesh.muxer.Command");
585
- var DEFAULT_SEND_COMMAND_TIMEOUT = 6e4;
586
- var DESTROY_COMMAND_SEND_TIMEOUT = 5e3;
587
- var STATS_INTERVAL = 1e3;
588
- var MAX_SAFE_FRAME_SIZE = 1e6;
589
- var SYSTEM_CHANNEL_ID = 0;
590
- var GRACEFUL_CLOSE_TIMEOUT = 3e3;
591
- var Muxer = class {
592
- constructor() {
593
- this._balancer = new Balancer(SYSTEM_CHANNEL_ID);
594
- this._channelsByLocalId = /* @__PURE__ */ new Map();
595
- this._channelsByTag = /* @__PURE__ */ new Map();
596
- this._ctx = new import_context2.Context();
597
- this._nextId = 1;
598
- this._closing = false;
599
- this._destroying = false;
600
- this._disposed = false;
601
- this._lastStats = void 0;
602
- this._lastChannelStats = /* @__PURE__ */ new Map();
603
- this.afterClosed = new import_async4.Event();
604
- this.statsUpdated = new import_async4.Event();
605
- this.stream = this._balancer.stream;
606
- this._balancer.incomingData.on(async (msg) => {
607
- await this._handleCommand(Command.decode(msg));
608
- });
609
- }
610
- /**
611
- * Creates a duplex Node.js-style stream.
612
- * The remote peer is expected to call `createStream` with the same tag.
613
- * The stream is immediately readable and writable.
614
- * NOTE: The data will be buffered until the stream is opened remotely with the same tag (may cause a memory leak).
615
- */
616
- async createStream(tag, opts = {}) {
617
- const channel = this._getOrCreateStream({
618
- tag,
619
- contentType: opts.contentType
620
- });
621
- (0, import_invariant3.invariant)(!channel.push, `Channel already open: ${tag}`, {
622
- F: __dxlog_file4,
623
- L: 140,
624
- S: this,
625
- A: [
626
- "!channel.push",
627
- "`Channel already open: ${tag}`"
628
- ]
629
- });
630
- const stream = new import_node_stream2.Duplex({
631
- write: (data, encoding, callback) => {
632
- this._sendData(channel, data).then(() => callback()).catch(callback);
633
- },
634
- read: () => {
635
- }
636
- });
637
- channel.push = (data) => {
638
- channel.stats.bytesReceived += data.length;
639
- stream.push(data);
640
- };
641
- channel.destroy = (err) => {
642
- stream.destroy(err);
643
- };
644
- try {
645
- await this._sendCommand({
646
- openChannel: {
647
- id: channel.id,
648
- tag: channel.tag,
649
- contentType: channel.contentType
650
- }
651
- }, SYSTEM_CHANNEL_ID);
652
- } catch (err) {
653
- this._destroyChannel(channel, err);
654
- throw err;
655
- }
656
- return stream;
657
- }
658
- /**
659
- * Creates an RPC port.
660
- * The remote peer is expected to call `createPort` with the same tag.
661
- * The port is immediately usable.
662
- * NOTE: The data will be buffered until the stream is opened remotely with the same tag (may cause a memory leak).
663
- */
664
- async createPort(tag, opts = {}) {
665
- const channel = this._getOrCreateStream({
666
- tag,
667
- contentType: opts.contentType
668
- });
669
- (0, import_invariant3.invariant)(!channel.push, `Channel already open: ${tag}`, {
670
- F: __dxlog_file4,
671
- L: 192,
672
- S: this,
673
- A: [
674
- "!channel.push",
675
- "`Channel already open: ${tag}`"
676
- ]
677
- });
678
- let inboundBuffer = [];
679
- let callback;
680
- channel.push = (data) => {
681
- channel.stats.bytesReceived += data.length;
682
- if (callback) {
683
- callback(data);
684
- } else {
685
- inboundBuffer.push(data);
686
- }
687
- };
688
- const port = {
689
- send: async (data, timeout) => {
690
- await this._sendData(channel, data, timeout);
691
- },
692
- subscribe: (cb) => {
693
- (0, import_invariant3.invariant)(!callback, "Only one subscriber is allowed", {
694
- F: __dxlog_file4,
695
- L: 214,
696
- S: this,
697
- A: [
698
- "!callback",
699
- "'Only one subscriber is allowed'"
700
- ]
701
- });
702
- callback = cb;
703
- for (const data of inboundBuffer) {
704
- cb(data);
705
- }
706
- inboundBuffer = [];
707
- }
708
- };
709
- try {
710
- await this._sendCommand({
711
- openChannel: {
712
- id: channel.id,
713
- tag: channel.tag,
714
- contentType: channel.contentType
715
- }
716
- }, SYSTEM_CHANNEL_ID);
717
- } catch (err) {
718
- this._destroyChannel(channel, err);
719
- throw err;
720
- }
721
- return port;
722
- }
723
- // initiate graceful close
724
- async close(err) {
725
- if (this._destroying) {
726
- (0, import_log4.log)("already destroying, ignoring graceful close request", void 0, {
727
- F: __dxlog_file4,
728
- L: 247,
729
- S: this,
730
- C: (f, a) => f(...a)
731
- });
732
- return;
733
- }
734
- if (this._closing) {
735
- (0, import_log4.log)("already closing, ignoring graceful close request", void 0, {
736
- F: __dxlog_file4,
737
- L: 251,
738
- S: this,
739
- C: (f, a) => f(...a)
740
- });
741
- return;
742
- }
743
- this._closing = true;
744
- await this._sendCommand({
745
- close: {
746
- error: err?.message
747
- }
748
- }, SYSTEM_CHANNEL_ID, DESTROY_COMMAND_SEND_TIMEOUT).catch(async (err2) => {
749
- (0, import_log4.log)("error sending close command", {
750
- err: err2
751
- }, {
752
- F: __dxlog_file4,
753
- L: 266,
754
- S: this,
755
- C: (f, a) => f(...a)
756
- });
757
- await this.dispose(err2);
758
- });
759
- await Promise.race([
760
- new Promise((_resolve, reject) => {
761
- setTimeout(() => {
762
- reject(new import_protocols2.TimeoutError("gracefully closing muxer"));
763
- }, GRACEFUL_CLOSE_TIMEOUT);
764
- }),
765
- (async () => {
766
- await this.dispose(err);
767
- })()
768
- ]);
769
- }
770
- // force close without confirmation
771
- async destroy(err) {
772
- if (this._destroying) {
773
- (0, import_log4.log)("already destroying, ignoring destroy request", void 0, {
774
- F: __dxlog_file4,
775
- L: 287,
776
- S: this,
777
- C: (f, a) => f(...a)
778
- });
779
- return;
780
- }
781
- this._destroying = true;
782
- void this._ctx.dispose();
783
- if (this._closing) {
784
- (0, import_log4.log)("destroy cancelling graceful close", void 0, {
785
- F: __dxlog_file4,
786
- L: 293,
787
- S: this,
788
- C: (f, a) => f(...a)
789
- });
790
- this._closing = false;
791
- } else {
792
- await this._sendCommand({
793
- close: {
794
- error: err?.message
795
- }
796
- }, SYSTEM_CHANNEL_ID).catch(async (err2) => {
797
- (0, import_log4.log)("error sending courtesy close command", {
798
- err: err2
799
- }, {
800
- F: __dxlog_file4,
801
- L: 306,
802
- S: this,
803
- C: (f, a) => f(...a)
804
- });
805
- });
806
- }
807
- this.dispose(err).catch((err2) => {
808
- (0, import_log4.log)("error disposing after destroy", {
809
- err: err2
810
- }, {
811
- F: __dxlog_file4,
812
- L: 311,
813
- S: this,
814
- C: (f, a) => f(...a)
815
- });
816
- });
817
- }
818
- // complete the termination, graceful or otherwise
819
- async dispose(err) {
820
- if (this._disposed) {
821
- (0, import_log4.log)("already destroyed, ignoring dispose request", void 0, {
822
- F: __dxlog_file4,
823
- L: 319,
824
- S: this,
825
- C: (f, a) => f(...a)
826
- });
827
- return;
828
- }
829
- void this._ctx.dispose();
830
- await this._balancer.destroy();
831
- for (const channel of this._channelsByTag.values()) {
832
- channel.destroy?.(err);
833
- }
834
- this._disposed = true;
835
- this.afterClosed.emit(err);
836
- this._channelsByLocalId.clear();
837
- this._channelsByTag.clear();
838
- }
839
- async _handleCommand(cmd) {
840
- if (this._disposed) {
841
- import_log4.log.warn("Received command after disposed", {
842
- cmd
843
- }, {
844
- F: __dxlog_file4,
845
- L: 341,
846
- S: this,
847
- C: (f, a) => f(...a)
848
- });
849
- return;
850
- }
851
- if (cmd.close) {
852
- if (!this._closing) {
853
- (0, import_log4.log)("received peer close, initiating my own graceful close", void 0, {
854
- F: __dxlog_file4,
855
- L: 347,
856
- S: this,
857
- C: (f, a) => f(...a)
858
- });
859
- await this.close();
860
- } else {
861
- (0, import_log4.log)("received close from peer, already closing", void 0, {
862
- F: __dxlog_file4,
863
- L: 350,
864
- S: this,
865
- C: (f, a) => f(...a)
866
- });
867
- }
868
- return;
869
- }
870
- if (cmd.openChannel) {
871
- const channel = this._getOrCreateStream({
872
- tag: cmd.openChannel.tag,
873
- contentType: cmd.openChannel.contentType
874
- });
875
- channel.remoteId = cmd.openChannel.id;
876
- for (const data of channel.buffer) {
877
- await this._sendCommand({
878
- data: {
879
- channelId: channel.remoteId,
880
- data
881
- }
882
- }, channel.id);
883
- }
884
- channel.buffer = [];
885
- } else if (cmd.data) {
886
- const stream = this._channelsByLocalId.get(cmd.data.channelId) ?? (0, import_debug.failUndefined)();
887
- if (!stream.push) {
888
- import_log4.log.warn("Received data for channel before it was opened", {
889
- tag: stream.tag
890
- }, {
891
- F: __dxlog_file4,
892
- L: 379,
893
- S: this,
894
- C: (f, a) => f(...a)
895
- });
896
- return;
897
- }
898
- stream.push(cmd.data.data);
899
- }
900
- }
901
- async _sendCommand(cmd, channelId = -1, timeout = DEFAULT_SEND_COMMAND_TIMEOUT) {
902
- if (this._disposed) {
903
- import_log4.log.info("ignoring sendCommand after disposed", {
904
- cmd
905
- }, {
906
- F: __dxlog_file4,
907
- L: 388,
908
- S: this,
909
- C: (f, a) => f(...a)
910
- });
911
- return;
912
- }
913
- try {
914
- const trigger = new import_async4.Trigger();
915
- this._balancer.pushData(Command.encode(cmd), trigger, channelId);
916
- await trigger.wait({
917
- timeout
918
- });
919
- } catch (err) {
920
- await this.destroy(err);
921
- }
922
- }
923
- _getOrCreateStream(params) {
924
- if (this._channelsByTag.size === 0) {
925
- (0, import_async4.scheduleTaskInterval)(this._ctx, async () => this._emitStats(), STATS_INTERVAL);
926
- }
927
- let channel = this._channelsByTag.get(params.tag);
928
- if (!channel) {
929
- channel = {
930
- id: this._nextId++,
931
- remoteId: null,
932
- tag: params.tag,
933
- contentType: params.contentType,
934
- buffer: [],
935
- push: null,
936
- destroy: null,
937
- stats: {
938
- bytesSent: 0,
939
- bytesReceived: 0
940
- }
941
- };
942
- this._channelsByTag.set(channel.tag, channel);
943
- this._channelsByLocalId.set(channel.id, channel);
944
- this._balancer.addChannel(channel.id);
945
- }
946
- return channel;
947
- }
948
- async _sendData(channel, data, timeout) {
949
- if (data.length > MAX_SAFE_FRAME_SIZE) {
950
- import_log4.log.warn("frame size exceeds maximum safe value", {
951
- size: data.length,
952
- threshold: MAX_SAFE_FRAME_SIZE
953
- }, {
954
- F: __dxlog_file4,
955
- L: 429,
956
- S: this,
957
- C: (f, a) => f(...a)
958
- });
959
- }
960
- channel.stats.bytesSent += data.length;
961
- if (channel.remoteId === null) {
962
- channel.buffer.push(data);
963
- return;
964
- }
965
- await this._sendCommand({
966
- data: {
967
- channelId: channel.remoteId,
968
- data
969
- }
970
- }, channel.id, timeout);
971
- }
972
- _destroyChannel(channel, err) {
973
- if (channel.destroy) {
974
- channel.destroy(err);
975
- }
976
- this._channelsByLocalId.delete(channel.id);
977
- this._channelsByTag.delete(channel.tag);
978
- }
979
- async _emitStats() {
980
- if (this._disposed || this._destroying) {
981
- this._lastStats = void 0;
982
- this._lastChannelStats.clear();
983
- return;
984
- }
985
- const bytesSent = this._balancer.bytesSent;
986
- const bytesReceived = this._balancer.bytesReceived;
987
- const now = Date.now();
988
- const interval = this._lastStats ? (now - this._lastStats.timestamp) / 1e3 : 0;
989
- const calculateThroughput = (current, last) => last ? {
990
- bytesSentRate: interval ? (current.bytesSent - last.bytesSent) / interval : void 0,
991
- bytesReceivedRate: interval ? (current.bytesReceived - last.bytesReceived) / interval : void 0
992
- } : {};
993
- this._lastStats = {
994
- timestamp: now,
995
- channels: Array.from(this._channelsByTag.values()).map((channel) => {
996
- const stats = {
997
- id: channel.id,
998
- tag: channel.tag,
999
- contentType: channel.contentType,
1000
- writeBufferSize: channel.buffer.length,
1001
- bytesSent: channel.stats.bytesSent,
1002
- bytesReceived: channel.stats.bytesReceived,
1003
- ...calculateThroughput(channel.stats, this._lastChannelStats.get(channel.id))
1004
- };
1005
- this._lastChannelStats.set(channel.id, stats);
1006
- return stats;
1007
- }),
1008
- bytesSent,
1009
- bytesReceived,
1010
- ...calculateThroughput({
1011
- bytesSent,
1012
- bytesReceived
1013
- }, this._lastStats),
1014
- readBufferSize: this._balancer.stream.readableLength,
1015
- writeBufferSize: this._balancer.stream.writableLength
1016
- };
1017
- this.statsUpdated.emit(this._lastStats);
1018
- }
1019
- };
1020
-
1021
- // packages/core/mesh/teleport/src/teleport.ts
1022
- function _ts_decorate(decorators, target, key, desc) {
1023
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
1024
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
1025
- r = Reflect.decorate(decorators, target, key, desc);
1026
- else
1027
- for (var i = decorators.length - 1; i >= 0; i--)
1028
- if (d = decorators[i])
1029
- r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
1030
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1031
- }
1032
- var __dxlog_file5 = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts";
1033
- var CONTROL_HEARTBEAT_INTERVAL = 1e4;
1034
- var CONTROL_HEARTBEAT_TIMEOUT = 6e4;
1035
- var Teleport = class {
1036
- constructor({ initiator, localPeerId, remotePeerId }) {
1037
- this._ctx = new import_context3.Context({
1038
- onError: (err) => {
1039
- void this.destroy(err).catch(() => {
1040
- import_log5.log.error("Error during destroy", err, {
1041
- F: __dxlog_file5,
1042
- L: 38,
1043
- S: this,
1044
- C: (f, a) => f(...a)
1045
- });
1046
- });
1047
- }
1048
- });
1049
- this._muxer = new Muxer();
1050
- this._extensions = /* @__PURE__ */ new Map();
1051
- this._remoteExtensions = /* @__PURE__ */ new Set();
1052
- this._open = false;
1053
- this._destroying = false;
1054
- this._aborting = false;
1055
- (0, import_invariant4.invariant)(typeof initiator === "boolean", void 0, {
1056
- F: __dxlog_file5,
1057
- L: 55,
1058
- S: this,
1059
- A: [
1060
- "typeof initiator === 'boolean'",
1061
- ""
1062
- ]
1063
- });
1064
- (0, import_invariant4.invariant)(import_keys.PublicKey.isPublicKey(localPeerId), void 0, {
1065
- F: __dxlog_file5,
1066
- L: 56,
1067
- S: this,
1068
- A: [
1069
- "PublicKey.isPublicKey(localPeerId)",
1070
- ""
1071
- ]
1072
- });
1073
- (0, import_invariant4.invariant)(import_keys.PublicKey.isPublicKey(remotePeerId), void 0, {
1074
- F: __dxlog_file5,
1075
- L: 57,
1076
- S: this,
1077
- A: [
1078
- "PublicKey.isPublicKey(remotePeerId)",
1079
- ""
1080
- ]
1081
- });
1082
- this.initiator = initiator;
1083
- this.localPeerId = localPeerId;
1084
- this.remotePeerId = remotePeerId;
1085
- this._control = new ControlExtension({
1086
- heartbeatInterval: CONTROL_HEARTBEAT_INTERVAL,
1087
- heartbeatTimeout: CONTROL_HEARTBEAT_TIMEOUT,
1088
- onTimeout: () => {
1089
- if (this._destroying || this._aborting) {
1090
- return;
1091
- }
1092
- import_log5.log.info("abort teleport due to onTimeout in ControlExtension", void 0, {
1093
- F: __dxlog_file5,
1094
- L: 70,
1095
- S: this,
1096
- C: (f, a) => f(...a)
1097
- });
1098
- this.abort(new import_protocols3.TimeoutError("control extension")).catch((err) => import_log5.log.catch(err, void 0, {
1099
- F: __dxlog_file5,
1100
- L: 71,
1101
- S: this,
1102
- C: (f, a) => f(...a)
1103
- }));
1104
- }
1105
- }, this.localPeerId, this.remotePeerId);
1106
- this._control.onExtensionRegistered.set(async (name) => {
1107
- (0, import_log5.log)("remote extension", {
1108
- name
1109
- }, {
1110
- F: __dxlog_file5,
1111
- L: 79,
1112
- S: this,
1113
- C: (f, a) => f(...a)
1114
- });
1115
- (0, import_invariant4.invariant)(!this._remoteExtensions.has(name), "Remote extension already exists", {
1116
- F: __dxlog_file5,
1117
- L: 80,
1118
- S: this,
1119
- A: [
1120
- "!this._remoteExtensions.has(name)",
1121
- "'Remote extension already exists'"
1122
- ]
1123
- });
1124
- this._remoteExtensions.add(name);
1125
- if (this._extensions.has(name)) {
1126
- try {
1127
- await this._openExtension(name);
1128
- } catch (err) {
1129
- await this.destroy(err);
1130
- }
1131
- }
1132
- });
1133
- {
1134
- this._muxer.stream.on("close", async () => {
1135
- if (this._destroying || this._aborting) {
1136
- (0, import_log5.log)("destroy teleport due to muxer stream close, skipping due to already destroying/aborting", void 0, {
1137
- F: __dxlog_file5,
1138
- L: 96,
1139
- S: this,
1140
- C: (f, a) => f(...a)
1141
- });
1142
- return;
1143
- }
1144
- await this.destroy();
1145
- });
1146
- this._muxer.stream.on("error", async (err) => {
1147
- await this.destroy(err);
1148
- });
1149
- }
1150
- this._muxer.statsUpdated.on((stats) => {
1151
- import_log5.log.trace("dxos.mesh.teleport.stats", {
1152
- localPeerId,
1153
- remotePeerId,
1154
- bytesSent: stats.bytesSent,
1155
- bytesSentRate: stats.bytesSentRate,
1156
- bytesReceived: stats.bytesReceived,
1157
- bytesReceivedRate: stats.bytesReceivedRate,
1158
- channels: stats.channels
1159
- }, {
1160
- F: __dxlog_file5,
1161
- L: 109,
1162
- S: this,
1163
- C: (f, a) => f(...a)
1164
- });
1165
- });
1166
- }
1167
- get stream() {
1168
- return this._muxer.stream;
1169
- }
1170
- get stats() {
1171
- return this._muxer.statsUpdated;
1172
- }
1173
- /**
1174
- * Blocks until the handshake is complete.
1175
- */
1176
- async open() {
1177
- this._setExtension("dxos.mesh.teleport.control", this._control);
1178
- await this._openExtension("dxos.mesh.teleport.control");
1179
- this._open = true;
1180
- }
1181
- async close(err) {
1182
- await this.destroy(err);
1183
- }
1184
- async abort(err) {
1185
- if (this._aborting || this._destroying) {
1186
- return;
1187
- }
1188
- this._aborting = true;
1189
- if (this._ctx.disposed) {
1190
- return;
1191
- }
1192
- await this._ctx.dispose();
1193
- for (const extension of this._extensions.values()) {
1194
- try {
1195
- await extension.onAbort(err);
1196
- } catch (err2) {
1197
- import_log5.log.catch(err2, void 0, {
1198
- F: __dxlog_file5,
1199
- L: 162,
1200
- S: this,
1201
- C: (f, a) => f(...a)
1202
- });
1203
- }
1204
- }
1205
- await this._muxer.destroy(err);
1206
- }
1207
- async destroy(err) {
1208
- if (this._destroying || this._aborting) {
1209
- return;
1210
- }
1211
- this._destroying = true;
1212
- if (this._ctx.disposed) {
1213
- return;
1214
- }
1215
- await this._ctx.dispose();
1216
- for (const extension of this._extensions.values()) {
1217
- try {
1218
- await extension.onClose(err);
1219
- } catch (err2) {
1220
- import_log5.log.catch(err2, void 0, {
1221
- F: __dxlog_file5,
1222
- L: 186,
1223
- S: this,
1224
- C: (f, a) => f(...a)
1225
- });
1226
- }
1227
- }
1228
- await this._muxer.close();
1229
- }
1230
- addExtension(name, extension) {
1231
- if (!this._open) {
1232
- throw new Error("Not open");
1233
- }
1234
- (0, import_log5.log)("addExtension", {
1235
- name
1236
- }, {
1237
- F: __dxlog_file5,
1238
- L: 198,
1239
- S: this,
1240
- C: (f, a) => f(...a)
1241
- });
1242
- this._setExtension(name, extension);
1243
- (0, import_async5.scheduleTask)(this._ctx, async () => {
1244
- try {
1245
- await this._control.registerExtension(name);
1246
- } catch (err) {
1247
- if (err instanceof import_protocols3.RpcClosedError) {
1248
- return;
1249
- }
1250
- throw err;
1251
- }
1252
- });
1253
- if (this._remoteExtensions.has(name)) {
1254
- (0, import_async5.scheduleTask)(this._ctx, async () => {
1255
- await this._openExtension(name);
1256
- });
1257
- }
1258
- }
1259
- _setExtension(extensionName, extension) {
1260
- (0, import_invariant4.invariant)(!extensionName.includes("/"), "Invalid extension name", {
1261
- F: __dxlog_file5,
1262
- L: 222,
1263
- S: this,
1264
- A: [
1265
- "!extensionName.includes('/')",
1266
- "'Invalid extension name'"
1267
- ]
1268
- });
1269
- (0, import_invariant4.invariant)(!this._extensions.has(extensionName), "Extension already exists", {
1270
- F: __dxlog_file5,
1271
- L: 223,
1272
- S: this,
1273
- A: [
1274
- "!this._extensions.has(extensionName)",
1275
- "'Extension already exists'"
1276
- ]
1277
- });
1278
- this._extensions.set(extensionName, extension);
1279
- }
1280
- async _openExtension(extensionName) {
1281
- (0, import_log5.log)("open extension", {
1282
- extensionName
1283
- }, {
1284
- F: __dxlog_file5,
1285
- L: 228,
1286
- S: this,
1287
- C: (f, a) => f(...a)
1288
- });
1289
- const extension = this._extensions.get(extensionName) ?? (0, import_debug2.failUndefined)();
1290
- const context = {
1291
- initiator: this.initiator,
1292
- localPeerId: this.localPeerId,
1293
- remotePeerId: this.remotePeerId,
1294
- createPort: async (channelName, opts) => {
1295
- (0, import_invariant4.invariant)(!channelName.includes("/"), "Invalid channel name", {
1296
- F: __dxlog_file5,
1297
- L: 236,
1298
- S: this,
1299
- A: [
1300
- "!channelName.includes('/')",
1301
- "'Invalid channel name'"
1302
- ]
1303
- });
1304
- return this._muxer.createPort(`${extensionName}/${channelName}`, opts);
1305
- },
1306
- createStream: async (channelName, opts) => {
1307
- (0, import_invariant4.invariant)(!channelName.includes("/"), "Invalid channel name", {
1308
- F: __dxlog_file5,
1309
- L: 240,
1310
- S: this,
1311
- A: [
1312
- "!channelName.includes('/')",
1313
- "'Invalid channel name'"
1314
- ]
1315
- });
1316
- return this._muxer.createStream(`${extensionName}/${channelName}`, opts);
1317
- },
1318
- close: (err) => {
1319
- void (0, import_async5.runInContextAsync)(this._ctx, async () => {
1320
- await this.close(err);
1321
- });
1322
- }
1323
- };
1324
- await extension.onOpen(context);
1325
- (0, import_log5.log)("extension opened", {
1326
- extensionName
1327
- }, {
1328
- F: __dxlog_file5,
1329
- L: 251,
1330
- S: this,
1331
- C: (f, a) => f(...a)
1332
- });
1333
- }
1334
- };
1335
- _ts_decorate([
1336
- import_async5.synchronized
1337
- ], Teleport.prototype, "abort", null);
1338
- _ts_decorate([
1339
- import_async5.synchronized
1340
- ], Teleport.prototype, "destroy", null);
1341
-
1342
- // packages/core/mesh/teleport/src/testing/test-builder.ts
1343
- var __dxlog_file6 = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/testing/test-builder.ts";
1344
- var TestBuilder = class {
1345
- constructor() {
1346
- this._peers = /* @__PURE__ */ new Set();
1347
- }
1348
- createPeer(opts) {
1349
- const peer = opts.factory();
1350
- this._peers.add(peer);
1351
- return peer;
1352
- }
1353
- *createPeers(opts) {
1354
- while (true) {
1355
- yield this.createPeer(opts);
1356
- }
1357
- }
1358
- async destroy() {
1359
- await Promise.all(Array.from(this._peers).map((agent) => agent.destroy()));
1360
- }
1361
- async connect(peer1, peer2) {
1362
- (0, import_invariant5.invariant)(peer1 !== peer2, void 0, {
1363
- F: __dxlog_file6,
1364
- L: 37,
1365
- S: this,
1366
- A: [
1367
- "peer1 !== peer2",
1368
- ""
1369
- ]
1370
- });
1371
- (0, import_invariant5.invariant)(this._peers.has(peer1), void 0, {
1372
- F: __dxlog_file6,
1373
- L: 38,
1374
- S: this,
1375
- A: [
1376
- "this._peers.has(peer1)",
1377
- ""
1378
- ]
1379
- });
1380
- (0, import_invariant5.invariant)(this._peers.has(peer1), void 0, {
1381
- F: __dxlog_file6,
1382
- L: 39,
1383
- S: this,
1384
- A: [
1385
- "this._peers.has(peer1)",
1386
- ""
1387
- ]
1388
- });
1389
- const connection1 = peer1.createConnection({
1390
- initiator: true,
1391
- remotePeerId: peer2.peerId
1392
- });
1393
- const connection2 = peer2.createConnection({
1394
- initiator: false,
1395
- remotePeerId: peer1.peerId
1396
- });
1397
- pipeStreams(connection1.teleport.stream, connection2.teleport.stream);
1398
- await Promise.all([
1399
- peer1.openConnection(connection1),
1400
- peer2.openConnection(connection2)
1401
- ]);
1402
- return [
1403
- connection1,
1404
- connection2
1405
- ];
1406
- }
1407
- async disconnect(peer1, peer2) {
1408
- (0, import_invariant5.invariant)(peer1 !== peer2, void 0, {
1409
- F: __dxlog_file6,
1410
- L: 51,
1411
- S: this,
1412
- A: [
1413
- "peer1 !== peer2",
1414
- ""
1415
- ]
1416
- });
1417
- (0, import_invariant5.invariant)(this._peers.has(peer1), void 0, {
1418
- F: __dxlog_file6,
1419
- L: 52,
1420
- S: this,
1421
- A: [
1422
- "this._peers.has(peer1)",
1423
- ""
1424
- ]
1425
- });
1426
- (0, import_invariant5.invariant)(this._peers.has(peer1), void 0, {
1427
- F: __dxlog_file6,
1428
- L: 53,
1429
- S: this,
1430
- A: [
1431
- "this._peers.has(peer1)",
1432
- ""
1433
- ]
1434
- });
1435
- const connection1 = Array.from(peer1.connections).find((connection) => connection.remotePeerId.equals(peer2.peerId));
1436
- const connection2 = Array.from(peer2.connections).find((connection) => connection.remotePeerId.equals(peer1.peerId));
1437
- (0, import_invariant5.invariant)(connection1, void 0, {
1438
- F: __dxlog_file6,
1439
- L: 62,
1440
- S: this,
1441
- A: [
1442
- "connection1",
1443
- ""
1444
- ]
1445
- });
1446
- (0, import_invariant5.invariant)(connection2, void 0, {
1447
- F: __dxlog_file6,
1448
- L: 63,
1449
- S: this,
1450
- A: [
1451
- "connection2",
1452
- ""
1453
- ]
1454
- });
1455
- await Promise.all([
1456
- peer1.closeConnection(connection1),
1457
- peer2.closeConnection(connection2)
1458
- ]);
1459
- }
1460
- };
1461
- var TestPeer = class {
1462
- constructor(peerId = import_keys2.PublicKey.random()) {
1463
- this.peerId = peerId;
1464
- this.connections = /* @__PURE__ */ new Set();
1465
- }
1466
- async onOpen(connection) {
1467
- }
1468
- async onClose(connection) {
1469
- }
1470
- createConnection({ initiator, remotePeerId }) {
1471
- const connection = new TestConnection(this.peerId, remotePeerId, initiator);
1472
- this.connections.add(connection);
1473
- return connection;
1474
- }
1475
- async openConnection(connection) {
1476
- (0, import_invariant5.invariant)(this.connections.has(connection), void 0, {
1477
- F: __dxlog_file6,
1478
- L: 84,
1479
- S: this,
1480
- A: [
1481
- "this.connections.has(connection)",
1482
- ""
1483
- ]
1484
- });
1485
- await connection.teleport.open();
1486
- await this.onOpen(connection);
1487
- }
1488
- async closeConnection(connection) {
1489
- (0, import_invariant5.invariant)(this.connections.has(connection), void 0, {
1490
- F: __dxlog_file6,
1491
- L: 90,
1492
- S: this,
1493
- A: [
1494
- "this.connections.has(connection)",
1495
- ""
1496
- ]
1497
- });
1498
- await this.onClose(connection);
1499
- await connection.teleport.close();
1500
- this.connections.delete(connection);
1501
- }
1502
- async destroy() {
1503
- for (const teleport of this.connections) {
1504
- await this.closeConnection(teleport);
1505
- }
1506
- }
1507
- };
1508
- var pipeStreams = (stream1, stream2) => {
1509
- (0, import_node_stream3.pipeline)(stream1, stream2, (err) => {
1510
- if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") {
1511
- import_log6.log.catch(err, void 0, {
1512
- F: __dxlog_file6,
1513
- L: 106,
1514
- S: void 0,
1515
- C: (f, a) => f(...a)
1516
- });
1517
- }
1518
- });
1519
- (0, import_node_stream3.pipeline)(stream2, stream1, (err) => {
1520
- if (err && err.code !== "ERR_STREAM_PREMATURE_CLOSE") {
1521
- import_log6.log.catch(err, void 0, {
1522
- F: __dxlog_file6,
1523
- L: 111,
1524
- S: void 0,
1525
- C: (f, a) => f(...a)
1526
- });
1527
- }
1528
- });
1529
- };
1530
- var TestConnection = class {
1531
- constructor(localPeerId, remotePeerId, initiator) {
1532
- this.localPeerId = localPeerId;
1533
- this.remotePeerId = remotePeerId;
1534
- this.initiator = initiator;
1535
- this.teleport = new Teleport({
1536
- initiator,
1537
- localPeerId,
1538
- remotePeerId
1539
- });
1540
- }
1541
- };
1542
-
1543
- // packages/core/mesh/teleport/src/testing/test-extension.ts
1544
- var import_async6 = require("@dxos/async");
1545
- var import_invariant6 = require("@dxos/invariant");
1546
- var import_log7 = require("@dxos/log");
1547
- var import_protocols4 = require("@dxos/protocols");
1548
- var import_rpc2 = require("@dxos/rpc");
1549
- var __dxlog_file7 = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/testing/test-extension.ts";
1550
- var TestExtension = class {
1551
- constructor(callbacks = {}) {
1552
- this.callbacks = callbacks;
1553
- this.open = new import_async6.Trigger();
1554
- this.closed = new import_async6.Trigger();
1555
- this.aborted = new import_async6.Trigger();
1556
- }
1557
- get remotePeerId() {
1558
- return this.extensionContext?.remotePeerId;
1559
- }
1560
- async onOpen(context) {
1561
- (0, import_log7.log)("onOpen", {
1562
- localPeerId: context.localPeerId,
1563
- remotePeerId: context.remotePeerId
1564
- }, {
1565
- F: __dxlog_file7,
1566
- L: 34,
1567
- S: this,
1568
- C: (f, a) => f(...a)
1569
- });
1570
- this.extensionContext = context;
1571
- this._rpc = (0, import_rpc2.createProtoRpcPeer)({
1572
- port: await context.createPort("rpc", {
1573
- contentType: 'application/x-protobuf; messageType="dxos.rpc.Message"'
1574
- }),
1575
- requested: {
1576
- TestService: import_protocols4.schema.getService("example.testing.rpc.TestService")
1577
- },
1578
- exposed: {
1579
- TestService: import_protocols4.schema.getService("example.testing.rpc.TestService")
1580
- },
1581
- handlers: {
1582
- TestService: {
1583
- voidCall: async (request) => {
1584
- },
1585
- testCall: async (request) => {
1586
- return {
1587
- data: request.data
1588
- };
1589
- }
1590
- }
1591
- },
1592
- timeout: 2e3
1593
- });
1594
- await this._rpc.open();
1595
- await this.callbacks.onOpen?.();
1596
- this.open.wake();
1597
- }
1598
- async onClose(err) {
1599
- (0, import_log7.log)("onClose", {
1600
- err
1601
- }, {
1602
- F: __dxlog_file7,
1603
- L: 68,
1604
- S: this,
1605
- C: (f, a) => f(...a)
1606
- });
1607
- await this.callbacks.onClose?.();
1608
- this.closed.wake();
1609
- await this._rpc?.close();
1610
- }
1611
- async onAbort(err) {
1612
- (0, import_log7.log)("onAbort", {
1613
- err
1614
- }, {
1615
- F: __dxlog_file7,
1616
- L: 75,
1617
- S: this,
1618
- C: (f, a) => f(...a)
1619
- });
1620
- await this.callbacks.onAbort?.();
1621
- this.aborted.wake();
1622
- await this._rpc?.abort();
1623
- }
1624
- async test(message = "test") {
1625
- await this.open.wait({
1626
- timeout: 1500
1627
- });
1628
- const res = await (0, import_async6.asyncTimeout)(this._rpc.rpc.TestService.testCall({
1629
- data: message
1630
- }), 1500);
1631
- (0, import_invariant6.invariant)(res.data === message, void 0, {
1632
- F: __dxlog_file7,
1633
- L: 84,
1634
- S: this,
1635
- A: [
1636
- "res.data === message",
1637
- ""
1638
- ]
1639
- });
1640
- }
1641
- /**
1642
- * Force-close the connection.
1643
- */
1644
- async closeConnection(err) {
1645
- this.extensionContext?.close(err);
1646
- }
1647
- };
1648
-
1649
- // packages/core/mesh/teleport/src/testing/test-extension-with-streams.ts
1650
- var import_node_crypto = require("node:crypto");
1651
- var import_async7 = require("@dxos/async");
1652
- var import_invariant7 = require("@dxos/invariant");
1653
- var import_log8 = require("@dxos/log");
1654
- var import_protocols5 = require("@dxos/protocols");
1655
- var import_rpc3 = require("@dxos/rpc");
1656
- var __dxlog_file8 = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/testing/test-extension-with-streams.ts";
1657
- var TestExtensionWithStreams = class {
1658
- constructor(callbacks = {}) {
1659
- this.callbacks = callbacks;
1660
- this.open = new import_async7.Trigger();
1661
- this.closed = new import_async7.Trigger();
1662
- this.aborted = new import_async7.Trigger();
1663
- this._streams = /* @__PURE__ */ new Map();
1664
- }
1665
- get remotePeerId() {
1666
- return this.extensionContext?.remotePeerId;
1667
- }
1668
- async _openStream(streamTag, interval = 5, chunkSize = 2048) {
1669
- (0, import_invariant7.invariant)(!this._streams.has(streamTag), `Stream already exists: ${streamTag}`, {
1670
- F: __dxlog_file8,
1671
- L: 39,
1672
- S: this,
1673
- A: [
1674
- "!this._streams.has(streamTag)",
1675
- "`Stream already exists: ${streamTag}`"
1676
- ]
1677
- });
1678
- const networkStream = await this.extensionContext.createStream(streamTag, {
1679
- contentType: "application/x-test-stream"
1680
- });
1681
- const streamEntry = {
1682
- networkStream,
1683
- bytesSent: 0,
1684
- bytesReceived: 0,
1685
- sendErrors: 0,
1686
- receiveErrors: 0,
1687
- startTimestamp: Date.now()
1688
- };
1689
- const pushChunk = () => {
1690
- streamEntry.timer = setTimeout(() => {
1691
- const chunk = (0, import_node_crypto.randomBytes)(chunkSize);
1692
- if (!networkStream.write(chunk, "binary", (err) => {
1693
- if (!err) {
1694
- streamEntry.bytesSent += chunk.length;
1695
- } else {
1696
- streamEntry.sendErrors += 1;
1697
- }
1698
- })) {
1699
- networkStream.once("drain", pushChunk);
1700
- } else {
1701
- process.nextTick(pushChunk);
1702
- }
1703
- }, interval);
1704
- };
1705
- pushChunk();
1706
- this._streams.set(streamTag, streamEntry);
1707
- networkStream.on("data", (data) => {
1708
- streamEntry.bytesReceived += data.length;
1709
- });
1710
- networkStream.on("error", (err) => {
1711
- streamEntry.receiveErrors += 1;
1712
- });
1713
- networkStream.on("close", () => {
1714
- networkStream.removeAllListeners();
1715
- });
1716
- streamEntry.reportingTimer = setInterval(() => {
1717
- const { bytesSent, bytesReceived, sendErrors, receiveErrors } = streamEntry;
1718
- import_log8.log.trace("dxos.test.stream-stats", {
1719
- streamTag,
1720
- bytesSent,
1721
- bytesReceived,
1722
- sendErrors,
1723
- receiveErrors,
1724
- from: this.extensionContext?.localPeerId,
1725
- to: this.extensionContext?.remotePeerId
1726
- }, {
1727
- F: __dxlog_file8,
1728
- L: 93,
1729
- S: this,
1730
- C: (f, a) => f(...a)
1731
- });
1732
- }, 100);
1733
- }
1734
- _closeStream(streamTag) {
1735
- (0, import_invariant7.invariant)(this._streams.has(streamTag), `Stream does not exist: ${streamTag}`, {
1736
- F: __dxlog_file8,
1737
- L: 106,
1738
- S: this,
1739
- A: [
1740
- "this._streams.has(streamTag)",
1741
- "`Stream does not exist: ${streamTag}`"
1742
- ]
1743
- });
1744
- const stream = this._streams.get(streamTag);
1745
- clearTimeout(stream.timer);
1746
- clearTimeout(stream.reportingTimer);
1747
- const { bytesSent, bytesReceived, sendErrors, receiveErrors, startTimestamp } = stream;
1748
- stream.networkStream.destroy();
1749
- this._streams.delete(streamTag);
1750
- return {
1751
- bytesSent,
1752
- bytesReceived,
1753
- sendErrors,
1754
- receiveErrors,
1755
- runningTime: Date.now() - (startTimestamp ?? 0)
1756
- };
1757
- }
1758
- async onOpen(context) {
1759
- (0, import_log8.log)("onOpen", {
1760
- localPeerId: context.localPeerId,
1761
- remotePeerId: context.remotePeerId
1762
- }, {
1763
- F: __dxlog_file8,
1764
- L: 128,
1765
- S: this,
1766
- C: (f, a) => f(...a)
1767
- });
1768
- this.extensionContext = context;
1769
- this._rpc = (0, import_rpc3.createProtoRpcPeer)({
1770
- port: await context.createPort("rpc", {
1771
- contentType: 'application/x-protobuf; messageType="dxos.rpc.Message"'
1772
- }),
1773
- requested: {
1774
- TestServiceWithStreams: import_protocols5.schema.getService("example.testing.rpc.TestServiceWithStreams")
1775
- },
1776
- exposed: {
1777
- TestServiceWithStreams: import_protocols5.schema.getService("example.testing.rpc.TestServiceWithStreams")
1778
- },
1779
- handlers: {
1780
- TestServiceWithStreams: {
1781
- requestTestStream: async (request) => {
1782
- const { data: streamTag, streamLoadInterval, streamLoadChunkSize } = request;
1783
- await this._openStream(streamTag, streamLoadInterval, streamLoadChunkSize);
1784
- return {
1785
- data: streamTag
1786
- };
1787
- },
1788
- closeTestStream: async (request) => {
1789
- const streamTag = request.data;
1790
- const { bytesSent, bytesReceived, sendErrors, receiveErrors, runningTime } = this._closeStream(streamTag);
1791
- return {
1792
- data: streamTag,
1793
- bytesSent,
1794
- bytesReceived,
1795
- sendErrors,
1796
- receiveErrors,
1797
- runningTime
1798
- };
1799
- }
1800
- }
1801
- },
1802
- timeout: 2e3
1803
- });
1804
- await this._rpc.open();
1805
- await this.callbacks.onOpen?.();
1806
- this.open.wake();
1807
- }
1808
- async onClose(err) {
1809
- (0, import_log8.log)("onClose", {
1810
- err
1811
- }, {
1812
- F: __dxlog_file8,
1813
- L: 179,
1814
- S: this,
1815
- C: (f, a) => f(...a)
1816
- });
1817
- await this.callbacks.onClose?.();
1818
- this.closed.wake();
1819
- for (const [streamTag, stream] of Object.entries(this._streams)) {
1820
- (0, import_log8.log)("closing stream", {
1821
- streamTag
1822
- }, {
1823
- F: __dxlog_file8,
1824
- L: 183,
1825
- S: this,
1826
- C: (f, a) => f(...a)
1827
- });
1828
- clearTimeout(stream.interval);
1829
- stream.networkStream.destroy();
1830
- }
1831
- await this._rpc?.close();
1832
- }
1833
- async onAbort(err) {
1834
- (0, import_log8.log)("onAbort", {
1835
- err
1836
- }, {
1837
- F: __dxlog_file8,
1838
- L: 191,
1839
- S: this,
1840
- C: (f, a) => f(...a)
1841
- });
1842
- await this.callbacks.onAbort?.();
1843
- this.aborted.wake();
1844
- await this._rpc?.abort();
1845
- }
1846
- async addNewStream(streamLoadInterval, streamLoadChunkSize, streamTag) {
1847
- await this.open.wait({
1848
- timeout: 1500
1849
- });
1850
- if (!streamTag) {
1851
- streamTag = `stream-${(0, import_node_crypto.randomBytes)(4).toString("hex")}`;
1852
- }
1853
- const { data } = await this._rpc.rpc.TestServiceWithStreams.requestTestStream({
1854
- data: streamTag,
1855
- streamLoadInterval,
1856
- streamLoadChunkSize
1857
- });
1858
- (0, import_invariant7.invariant)(data === streamTag, void 0, {
1859
- F: __dxlog_file8,
1860
- L: 207,
1861
- S: this,
1862
- A: [
1863
- "data === streamTag",
1864
- ""
1865
- ]
1866
- });
1867
- await this._openStream(streamTag, streamLoadInterval, streamLoadChunkSize);
1868
- return streamTag;
1869
- }
1870
- async closeStream(streamTag) {
1871
- await this.open.wait({
1872
- timeout: 1500
1873
- });
1874
- const { data, bytesSent, bytesReceived, sendErrors, receiveErrors, runningTime } = await this._rpc.rpc.TestServiceWithStreams.closeTestStream({
1875
- data: streamTag
1876
- });
1877
- (0, import_invariant7.invariant)(data === streamTag, void 0, {
1878
- F: __dxlog_file8,
1879
- L: 220,
1880
- S: this,
1881
- A: [
1882
- "data === streamTag",
1883
- ""
1884
- ]
1885
- });
1886
- const local = this._closeStream(streamTag);
1887
- return {
1888
- streamTag,
1889
- stats: {
1890
- local,
1891
- remote: {
1892
- bytesSent,
1893
- bytesReceived,
1894
- sendErrors,
1895
- receiveErrors,
1896
- runningTime
1897
- }
1898
- }
1899
- };
1900
- }
1901
- /**
1902
- * Force-close the connection.
1903
- */
1904
- async closeConnection(err) {
1905
- this.extensionContext?.close(err);
1906
- }
1907
- };
28
+ var import_chunk_GVV33WCQ = require("../chunk-GVV33WCQ.cjs");
1908
29
  // Annotate the CommonJS export names for ESM import in node:
1909
30
  0 && (module.exports = {
1910
31
  TestBuilder,