@dxos/teleport 0.6.13 → 0.6.14-main.1366248

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