@dxos/teleport 0.8.3-staging.0fa589b → 0.8.4-main.3f58842

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