@dxos/teleport 0.3.7 → 0.3.8-main.0ae9c21

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