@dxos/teleport 0.6.13-staging.1e988a3 → 0.6.14-main.2b6a0f3

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