@dxos/teleport 0.6.10-main.e92b5eb → 0.6.10-staging.7621a6e

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.
@@ -26,8 +26,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  mod
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var chunk_6CFOQWV3_exports = {};
30
- __export(chunk_6CFOQWV3_exports, {
29
+ var chunk_OMLDRTR3_exports = {};
30
+ __export(chunk_OMLDRTR3_exports, {
31
31
  Framer: () => Framer,
32
32
  Muxer: () => Muxer,
33
33
  Teleport: () => Teleport,
@@ -39,7 +39,7 @@ __export(chunk_6CFOQWV3_exports, {
39
39
  decodeFrame: () => decodeFrame,
40
40
  encodeFrame: () => encodeFrame
41
41
  });
42
- module.exports = __toCommonJS(chunk_6CFOQWV3_exports);
42
+ module.exports = __toCommonJS(chunk_OMLDRTR3_exports);
43
43
  var import_node_stream = require("node:stream");
44
44
  var import_async = require("@dxos/async");
45
45
  var import_invariant = require("@dxos/invariant");
@@ -56,6 +56,7 @@ var import_async3 = require("@dxos/async");
56
56
  var import_context2 = require("@dxos/context");
57
57
  var import_log3 = require("@dxos/log");
58
58
  var import_protocols2 = require("@dxos/protocols");
59
+ var import_proto = require("@dxos/protocols/proto");
59
60
  var import_rpc = require("@dxos/rpc");
60
61
  var import_util = require("@dxos/util");
61
62
  var import_node_stream2 = require("node:stream");
@@ -69,6 +70,7 @@ var import_debug2 = require("@dxos/debug");
69
70
  var import_invariant4 = require("@dxos/invariant");
70
71
  var import_log5 = require("@dxos/log");
71
72
  var import_protocols3 = require("@dxos/protocols");
73
+ var import_proto2 = require("@dxos/protocols/proto");
72
74
  var varint = __toESM(require("varint"));
73
75
  var import_async6 = require("@dxos/async");
74
76
  var import_invariant5 = require("@dxos/invariant");
@@ -76,13 +78,13 @@ var import_log6 = require("@dxos/log");
76
78
  var import_async7 = require("@dxos/async");
77
79
  var import_invariant6 = require("@dxos/invariant");
78
80
  var import_log7 = require("@dxos/log");
79
- var import_protocols4 = require("@dxos/protocols");
81
+ var import_proto3 = require("@dxos/protocols/proto");
80
82
  var import_rpc2 = require("@dxos/rpc");
81
83
  var import_node_crypto = require("node:crypto");
82
84
  var import_async8 = require("@dxos/async");
83
85
  var import_invariant7 = require("@dxos/invariant");
84
86
  var import_log8 = require("@dxos/log");
85
- var import_protocols5 = require("@dxos/protocols");
87
+ var import_proto4 = require("@dxos/protocols/proto");
86
88
  var import_rpc3 = require("@dxos/rpc");
87
89
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/control-extension.ts";
88
90
  var HEARTBEAT_RTT_WARN_THRESH = 1e4;
@@ -98,7 +100,7 @@ var ControlExtension = class {
98
100
  }
99
101
  }, {
100
102
  F: __dxlog_file,
101
- L: 30
103
+ L: 31
102
104
  });
103
105
  this.onExtensionRegistered = new import_util.Callback();
104
106
  }
@@ -111,10 +113,10 @@ var ControlExtension = class {
111
113
  this._extensionContext = extensionContext;
112
114
  this._rpc = (0, import_rpc.createProtoRpcPeer)({
113
115
  requested: {
114
- Control: import_protocols2.schema.getService("dxos.mesh.teleport.control.ControlService")
116
+ Control: import_proto.schema.getService("dxos.mesh.teleport.control.ControlService")
115
117
  },
116
118
  exposed: {
117
- Control: import_protocols2.schema.getService("dxos.mesh.teleport.control.ControlService")
119
+ Control: import_proto.schema.getService("dxos.mesh.teleport.control.ControlService")
118
120
  },
119
121
  handlers: {
120
122
  Control: {
@@ -129,7 +131,7 @@ var ControlExtension = class {
129
131
  remotePeerId: this.remotePeerId.truncate()
130
132
  }, {
131
133
  F: __dxlog_file,
132
- L: 68,
134
+ L: 69,
133
135
  S: this,
134
136
  C: (f, a) => f(...a)
135
137
  });
@@ -161,7 +163,7 @@ var ControlExtension = class {
161
163
  remotePeerId: this.remotePeerId.truncate()
162
164
  }, {
163
165
  F: __dxlog_file,
164
- L: 106,
166
+ L: 107,
165
167
  S: this,
166
168
  C: (f, a) => f(...a)
167
169
  });
@@ -173,7 +175,7 @@ var ControlExtension = class {
173
175
  remotePeerId: this.remotePeerId.truncate()
174
176
  }, {
175
177
  F: __dxlog_file,
176
- L: 113,
178
+ L: 114,
177
179
  S: this,
178
180
  C: (f, a) => f(...a)
179
181
  });
@@ -185,7 +187,7 @@ var ControlExtension = class {
185
187
  if (err instanceof import_protocols2.RpcClosedError) {
186
188
  (0, import_log3.log)("ignoring RpcClosedError in heartbeat", void 0, {
187
189
  F: __dxlog_file,
188
- L: 125,
190
+ L: 126,
189
191
  S: this,
190
192
  C: (f, a) => f(...a)
191
193
  });
@@ -198,7 +200,7 @@ var ControlExtension = class {
198
200
  delay: now - reqTS.getTime()
199
201
  }, {
200
202
  F: __dxlog_file,
201
- L: 130,
203
+ L: 131,
202
204
  S: this,
203
205
  C: (f, a) => f(...a)
204
206
  });
@@ -209,7 +211,7 @@ var ControlExtension = class {
209
211
  delay: now - reqTS.getTime()
210
212
  }, {
211
213
  F: __dxlog_file,
212
- L: 133,
214
+ L: 134,
213
215
  S: this,
214
216
  C: (f, a) => f(...a)
215
217
  });
@@ -599,7 +601,7 @@ function _ts_decorate(decorators, target, key, desc) {
599
601
  return c > 3 && r && Object.defineProperty(target, key, r), r;
600
602
  }
601
603
  var __dxlog_file4 = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts";
602
- var Command = import_protocols3.schema.getCodecForType("dxos.mesh.muxer.Command");
604
+ var Command = import_proto2.schema.getCodecForType("dxos.mesh.muxer.Command");
603
605
  var DEFAULT_SEND_COMMAND_TIMEOUT = 6e4;
604
606
  var DESTROY_COMMAND_SEND_TIMEOUT = 5e3;
605
607
  var STATS_INTERVAL = 1e3;
@@ -613,7 +615,7 @@ var Muxer = class {
613
615
  this._channelsByTag = /* @__PURE__ */ new Map();
614
616
  this._ctx = new import_context3.Context(void 0, {
615
617
  F: __dxlog_file4,
616
- L: 107
618
+ L: 108
617
619
  });
618
620
  this._nextId = 1;
619
621
  this._closing = false;
@@ -647,7 +649,7 @@ var Muxer = class {
647
649
  });
648
650
  (0, import_invariant4.invariant)(!channel.push, `Channel already open: ${tag}`, {
649
651
  F: __dxlog_file4,
650
- L: 151,
652
+ L: 152,
651
653
  S: this,
652
654
  A: [
653
655
  "!channel.push",
@@ -703,7 +705,7 @@ var Muxer = class {
703
705
  });
704
706
  (0, import_invariant4.invariant)(!channel.push, `Channel already open: ${tag}`, {
705
707
  F: __dxlog_file4,
706
- L: 211,
708
+ L: 212,
707
709
  S: this,
708
710
  A: [
709
711
  "!channel.push",
@@ -727,7 +729,7 @@ var Muxer = class {
727
729
  subscribe: (cb) => {
728
730
  (0, import_invariant4.invariant)(!callback, "Only one subscriber is allowed", {
729
731
  F: __dxlog_file4,
730
- L: 233,
732
+ L: 234,
731
733
  S: this,
732
734
  A: [
733
735
  "!callback",
@@ -760,7 +762,7 @@ var Muxer = class {
760
762
  if (this._destroying) {
761
763
  (0, import_log5.log)("already destroying, ignoring graceful close request", void 0, {
762
764
  F: __dxlog_file4,
763
- L: 266,
765
+ L: 267,
764
766
  S: this,
765
767
  C: (f, a) => f(...a)
766
768
  });
@@ -769,7 +771,7 @@ var Muxer = class {
769
771
  if (this._closing) {
770
772
  (0, import_log5.log)("already closing, ignoring graceful close request", void 0, {
771
773
  F: __dxlog_file4,
772
- L: 270,
774
+ L: 271,
773
775
  S: this,
774
776
  C: (f, a) => f(...a)
775
777
  });
@@ -785,7 +787,7 @@ var Muxer = class {
785
787
  err: err2
786
788
  }, {
787
789
  F: __dxlog_file4,
788
- L: 285,
790
+ L: 286,
789
791
  S: this,
790
792
  C: (f, a) => f(...a)
791
793
  });
@@ -798,7 +800,7 @@ var Muxer = class {
798
800
  if (this._destroying) {
799
801
  (0, import_log5.log)("already destroying, ignoring destroy request", void 0, {
800
802
  F: __dxlog_file4,
801
- L: 298,
803
+ L: 299,
802
804
  S: this,
803
805
  C: (f, a) => f(...a)
804
806
  });
@@ -809,7 +811,7 @@ var Muxer = class {
809
811
  if (this._closing) {
810
812
  (0, import_log5.log)("destroy cancelling graceful close", void 0, {
811
813
  F: __dxlog_file4,
812
- L: 304,
814
+ L: 305,
813
815
  S: this,
814
816
  C: (f, a) => f(...a)
815
817
  });
@@ -824,7 +826,7 @@ var Muxer = class {
824
826
  err: err2
825
827
  }, {
826
828
  F: __dxlog_file4,
827
- L: 317,
829
+ L: 318,
828
830
  S: this,
829
831
  C: (f, a) => f(...a)
830
832
  });
@@ -835,7 +837,7 @@ var Muxer = class {
835
837
  err: err2
836
838
  }, {
837
839
  F: __dxlog_file4,
838
- L: 322,
840
+ L: 323,
839
841
  S: this,
840
842
  C: (f, a) => f(...a)
841
843
  });
@@ -846,7 +848,7 @@ var Muxer = class {
846
848
  if (this._disposed) {
847
849
  (0, import_log5.log)("already destroyed, ignoring dispose request", void 0, {
848
850
  F: __dxlog_file4,
849
- L: 330,
851
+ L: 331,
850
852
  S: this,
851
853
  C: (f, a) => f(...a)
852
854
  });
@@ -869,7 +871,7 @@ var Muxer = class {
869
871
  cmd
870
872
  }, {
871
873
  F: __dxlog_file4,
872
- L: 353,
874
+ L: 354,
873
875
  S: this,
874
876
  C: (f, a) => f(...a)
875
877
  });
@@ -879,7 +881,7 @@ var Muxer = class {
879
881
  if (!this._closing) {
880
882
  (0, import_log5.log)("received peer close, initiating my own graceful close", void 0, {
881
883
  F: __dxlog_file4,
882
- L: 359,
884
+ L: 360,
883
885
  S: this,
884
886
  C: (f, a) => f(...a)
885
887
  });
@@ -887,7 +889,7 @@ var Muxer = class {
887
889
  } else {
888
890
  (0, import_log5.log)("received close from peer, already closing", void 0, {
889
891
  F: __dxlog_file4,
890
- L: 362,
892
+ L: 363,
891
893
  S: this,
892
894
  C: (f, a) => f(...a)
893
895
  });
@@ -916,7 +918,7 @@ var Muxer = class {
916
918
  tag: stream.tag
917
919
  }, {
918
920
  F: __dxlog_file4,
919
- L: 391,
921
+ L: 392,
920
922
  S: this,
921
923
  C: (f, a) => f(...a)
922
924
  });
@@ -971,7 +973,7 @@ var Muxer = class {
971
973
  threshold: MAX_SAFE_FRAME_SIZE
972
974
  }, {
973
975
  F: __dxlog_file4,
974
- L: 441,
976
+ L: 442,
975
977
  S: this,
976
978
  C: (f, a) => f(...a)
977
979
  });
@@ -1651,10 +1653,10 @@ var TestExtension = class {
1651
1653
  contentType: 'application/x-protobuf; messageType="dxos.rpc.Message"'
1652
1654
  }),
1653
1655
  requested: {
1654
- TestService: import_protocols4.schema.getService("example.testing.rpc.TestService")
1656
+ TestService: import_proto3.schema.getService("example.testing.rpc.TestService")
1655
1657
  },
1656
1658
  exposed: {
1657
- TestService: import_protocols4.schema.getService("example.testing.rpc.TestService")
1659
+ TestService: import_proto3.schema.getService("example.testing.rpc.TestService")
1658
1660
  },
1659
1661
  handlers: {
1660
1662
  TestService: {
@@ -1841,10 +1843,10 @@ var TestExtensionWithStreams = class {
1841
1843
  contentType: 'application/x-protobuf; messageType="dxos.rpc.Message"'
1842
1844
  }),
1843
1845
  requested: {
1844
- TestServiceWithStreams: import_protocols5.schema.getService("example.testing.rpc.TestServiceWithStreams")
1846
+ TestServiceWithStreams: import_proto4.schema.getService("example.testing.rpc.TestServiceWithStreams")
1845
1847
  },
1846
1848
  exposed: {
1847
- TestServiceWithStreams: import_protocols5.schema.getService("example.testing.rpc.TestServiceWithStreams")
1849
+ TestServiceWithStreams: import_proto4.schema.getService("example.testing.rpc.TestServiceWithStreams")
1848
1850
  },
1849
1851
  handlers: {
1850
1852
  TestServiceWithStreams: {
@@ -1988,4 +1990,4 @@ var TestExtensionWithStreams = class {
1988
1990
  decodeFrame,
1989
1991
  encodeFrame
1990
1992
  });
1991
- //# sourceMappingURL=chunk-6CFOQWV3.cjs.map
1993
+ //# sourceMappingURL=chunk-OMLDRTR3.cjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/testing/test-builder.ts", "../../../src/teleport.ts", "../../../src/control-extension.ts", "../../../src/muxing/framer.ts", "../../../src/muxing/muxer.ts", "../../../src/muxing/balancer.ts", "../../../src/testing/test-extension.ts", "../../../src/testing/test-extension-with-streams.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Duplex, pipeline } from 'node:stream';\n\nimport { waitForCondition } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nimport { Teleport } from '../teleport';\n\ntype CreatePeerOpts<T extends TestPeer> = {\n factory: () => T;\n};\n\nexport class TestBuilder {\n private readonly _peers = new Set<TestPeer>();\n\n createPeer<T extends TestPeer>(opts: CreatePeerOpts<T>): T {\n const peer = opts.factory();\n this._peers.add(peer);\n return peer;\n }\n\n *createPeers<T extends TestPeer>(opts: CreatePeerOpts<T>): Generator<T> {\n while (true) {\n yield this.createPeer(opts);\n }\n }\n\n async destroy() {\n await Promise.all(Array.from(this._peers).map((agent) => agent.destroy()));\n }\n\n async connect(peer1: TestPeer, peer2: TestPeer) {\n invariant(peer1 !== peer2);\n invariant(this._peers.has(peer1));\n invariant(this._peers.has(peer1));\n\n const connection1 = peer1.createConnection({ initiator: true, remotePeerId: peer2.peerId });\n const connection2 = peer2.createConnection({ initiator: false, remotePeerId: peer1.peerId });\n\n pipeStreams(connection1.teleport.stream, connection2.teleport.stream);\n await Promise.all([peer1.openConnection(connection1), peer2.openConnection(connection2)]);\n\n return [connection1, connection2];\n }\n\n async disconnect(peer1: TestPeer, peer2: TestPeer) {\n invariant(peer1 !== peer2);\n invariant(this._peers.has(peer1));\n invariant(this._peers.has(peer1));\n\n const connection1 = Array.from(peer1.connections).find((connection) =>\n connection.remotePeerId.equals(peer2.peerId),\n );\n const connection2 = Array.from(peer2.connections).find((connection) =>\n connection.remotePeerId.equals(peer1.peerId),\n );\n\n invariant(connection1);\n invariant(connection2);\n\n await Promise.all([peer1.closeConnection(connection1), peer2.closeConnection(connection2)]);\n }\n}\n\nexport class TestPeer {\n public readonly connections = new Set<TestConnection>();\n\n constructor(public readonly peerId: PublicKey = PublicKey.random()) {}\n\n protected async onOpen(connection: TestConnection) {}\n protected async onClose(connection: TestConnection) {}\n\n createConnection({ initiator, remotePeerId }: { initiator: boolean; remotePeerId: PublicKey }) {\n const connection = new TestConnection(this.peerId, remotePeerId, initiator);\n this.connections.add(connection);\n return connection;\n }\n\n async openConnection(connection: TestConnection) {\n invariant(this.connections.has(connection));\n await connection.teleport.open(PublicKey.random());\n await this.onOpen(connection);\n }\n\n async closeConnection(connection: TestConnection) {\n invariant(this.connections.has(connection));\n await this.onClose(connection);\n await connection.teleport.close();\n this.connections.delete(connection);\n }\n\n async destroy() {\n for (const teleport of this.connections) {\n await this.closeConnection(teleport);\n }\n }\n}\n\nconst pipeStreams = (stream1: Duplex, stream2: Duplex) => {\n pipeline(stream1, stream2, (err) => {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n log.catch(err);\n }\n });\n pipeline(stream2, stream1, (err) => {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n log.catch(err);\n }\n });\n};\n\nexport class TestConnection {\n public teleport: Teleport;\n\n constructor(\n public readonly localPeerId: PublicKey,\n public readonly remotePeerId: PublicKey,\n public readonly initiator: boolean,\n ) {\n this.teleport = new Teleport({\n initiator,\n localPeerId,\n remotePeerId,\n });\n }\n\n public whenOpen(open: boolean) {\n return waitForCondition({ condition: () => this.teleport.isOpen === open });\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { type Duplex } from 'node:stream';\n\nimport { runInContextAsync, synchronized, scheduleTask, type Event } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { failUndefined } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { PublicKey } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport { RpcClosedError, TimeoutError } from '@dxos/protocols';\n\nimport { ControlExtension } from './control-extension';\nimport { type CreateChannelOpts, Muxer, type MuxerStats, type RpcPort } from './muxing';\n\nexport type TeleportParams = {\n initiator: boolean;\n localPeerId: PublicKey;\n remotePeerId: PublicKey;\n controlHeartbeatInterval?: number;\n controlHeartbeatTimeout?: number;\n};\n\nconst CONTROL_HEARTBEAT_INTERVAL = 10_000;\nconst CONTROL_HEARTBEAT_TIMEOUT = 60_000;\n\n/**\n * TODO(burdon): Comment: what is this?\n */\nexport class Teleport {\n public readonly initiator: boolean;\n public readonly localPeerId: PublicKey;\n public readonly remotePeerId: PublicKey;\n public _sessionId?: PublicKey;\n\n private readonly _ctx = new Context({\n onError: (err) => {\n void this.destroy(err).catch(() => {\n log.error('Error during destroy', err);\n });\n },\n });\n\n private readonly _muxer = new Muxer();\n\n private readonly _control;\n\n private readonly _extensions = new Map<string, TeleportExtension>();\n private readonly _remoteExtensions = new Set<string>();\n\n private _open = false;\n private _destroying = false;\n private _aborting = false;\n\n public get isOpen() {\n return this._open;\n }\n\n constructor({ initiator, localPeerId, remotePeerId, ...rest }: TeleportParams) {\n invariant(typeof initiator === 'boolean');\n invariant(PublicKey.isPublicKey(localPeerId));\n invariant(PublicKey.isPublicKey(remotePeerId));\n this.initiator = initiator;\n this.localPeerId = localPeerId;\n this.remotePeerId = remotePeerId;\n\n this._control = new ControlExtension(\n {\n heartbeatInterval: rest.controlHeartbeatInterval ?? CONTROL_HEARTBEAT_INTERVAL,\n heartbeatTimeout: rest.controlHeartbeatTimeout ?? CONTROL_HEARTBEAT_TIMEOUT,\n onTimeout: () => {\n if (this._destroying || this._aborting) {\n return;\n }\n log.info('abort teleport due to onTimeout in ControlExtension');\n this.abort(new TimeoutError('control extension')).catch((err) => log.catch(err));\n },\n },\n this.localPeerId,\n this.remotePeerId,\n );\n\n this._control.onExtensionRegistered.set(async (name) => {\n log('remote extension', { name });\n invariant(!this._remoteExtensions.has(name), 'Remote extension already exists');\n this._remoteExtensions.add(name);\n\n if (this._extensions.has(name)) {\n try {\n await this._openExtension(name);\n } catch (err: any) {\n await this.destroy(err);\n }\n }\n });\n\n {\n // Destroy Teleport when the stream is closed.\n this._muxer.stream.on('close', async () => {\n if (this._destroying || this._aborting) {\n log('destroy teleport due to muxer stream close, skipping due to already destroying/aborting');\n return;\n }\n await this.destroy();\n });\n\n this._muxer.stream.on('error', async (err) => {\n await this.destroy(err);\n });\n }\n\n // let last: MuxerStats | undefined;\n this._muxer.statsUpdated.on((stats) => {\n log.trace('dxos.mesh.teleport.stats', {\n localPeerId,\n remotePeerId,\n bytesSent: stats.bytesSent,\n bytesSentRate: stats.bytesSentRate,\n bytesReceived: stats.bytesReceived,\n bytesReceivedRate: stats.bytesReceivedRate,\n channels: stats.channels,\n });\n\n // last = stats;\n });\n }\n\n @logInfo\n get sessionIdString(): string {\n return this._sessionId ? this._sessionId.truncate() : 'none';\n }\n\n get stream(): Duplex {\n return this._muxer.stream;\n }\n\n get stats(): Event<MuxerStats> {\n return this._muxer.statsUpdated;\n }\n\n /**\n * Blocks until the handshake is complete.\n */\n\n async open(sessionId: PublicKey = PublicKey.random()) {\n // invariant(sessionId);\n this._sessionId = sessionId;\n log('open');\n this._setExtension('dxos.mesh.teleport.control', this._control);\n await this._openExtension('dxos.mesh.teleport.control');\n this._open = true;\n this._muxer.setSessionId(sessionId);\n }\n\n async close(err?: Error) {\n // TODO(dmaretskyi): Try soft close.\n await this.destroy(err);\n }\n\n @synchronized\n async abort(err?: Error) {\n if (this._aborting || this._destroying) {\n return;\n }\n this._aborting = true;\n this._open = false;\n\n if (this._ctx.disposed) {\n return;\n }\n\n await this._ctx.dispose();\n\n for (const extension of this._extensions.values()) {\n try {\n await extension.onAbort(err);\n } catch (err: any) {\n log.catch(err);\n }\n }\n\n await this._muxer.destroy(err);\n }\n\n @synchronized\n // TODO(nf): analyze callers and consider abort instead\n async destroy(err?: Error) {\n if (this._destroying || this._aborting) {\n return;\n }\n log('destroying teleport...', { extensionsCount: this._extensions.size });\n this._destroying = true;\n this._open = false;\n\n if (this._ctx.disposed) {\n return;\n }\n\n await this._ctx.dispose();\n\n for (const extension of this._extensions.values()) {\n try {\n log('destroying extension', { name: extension.constructor.name });\n await extension.onClose(err);\n log('destroyed extension', { name: extension.constructor.name });\n } catch (err: any) {\n log.catch(err);\n }\n }\n\n await this._muxer.close();\n log('teleport destroyed');\n }\n\n addExtension(name: string, extension: TeleportExtension) {\n if (!this._open) {\n throw new Error('Not open');\n }\n\n log('addExtension', { name });\n this._setExtension(name, extension);\n\n // Perform the registration in a separate tick as this might block while the remote side is opening the extension.\n scheduleTask(this._ctx, async () => {\n try {\n await this._control.registerExtension(name);\n } catch (err) {\n if (err instanceof RpcClosedError) {\n return;\n }\n throw err;\n }\n });\n\n if (this._remoteExtensions.has(name)) {\n // Open the extension in a separate tick.\n scheduleTask(this._ctx, async () => {\n await this._openExtension(name);\n });\n }\n }\n\n private _setExtension(extensionName: string, extension: TeleportExtension) {\n invariant(!extensionName.includes('/'), 'Invalid extension name');\n invariant(!this._extensions.has(extensionName), 'Extension already exists');\n this._extensions.set(extensionName, extension);\n }\n\n private async _openExtension(extensionName: string) {\n log('open extension', { extensionName });\n const extension = this._extensions.get(extensionName) ?? failUndefined();\n\n const context: ExtensionContext = {\n initiator: this.initiator,\n localPeerId: this.localPeerId,\n remotePeerId: this.remotePeerId,\n createPort: async (channelName: string, opts?: CreateChannelOpts) => {\n invariant(!channelName.includes('/'), 'Invalid channel name');\n return this._muxer.createPort(`${extensionName}/${channelName}`, opts);\n },\n createStream: async (channelName: string, opts?: CreateChannelOpts) => {\n invariant(!channelName.includes('/'), 'Invalid channel name');\n return this._muxer.createStream(`${extensionName}/${channelName}`, opts);\n },\n close: (err) => {\n void runInContextAsync(this._ctx, async () => {\n await this.close(err);\n });\n },\n };\n\n await extension.onOpen(context);\n log('extension opened', { extensionName });\n }\n}\n\nexport type ExtensionContext = {\n /**\n * One of the peers will be designated an initiator.\n */\n initiator: boolean;\n localPeerId: PublicKey;\n remotePeerId: PublicKey;\n createStream(tag: string, opts?: CreateChannelOpts): Promise<Duplex>;\n createPort(tag: string, opts?: CreateChannelOpts): Promise<RpcPort>;\n close(err?: Error): void;\n};\n\nexport interface TeleportExtension {\n onOpen(context: ExtensionContext): Promise<void>;\n onClose(err?: Error): Promise<void>;\n onAbort(err?: Error): Promise<void>;\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport { asyncTimeout, scheduleTaskInterval, TimeoutError as AsyncTimeoutError } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { type PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { RpcClosedError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type ControlService } from '@dxos/protocols/proto/dxos/mesh/teleport/control';\nimport { createProtoRpcPeer, type ProtoRpcPeer } from '@dxos/rpc';\nimport { Callback } from '@dxos/util';\n\nimport { type ExtensionContext, type TeleportExtension } from './teleport';\n\nconst HEARTBEAT_RTT_WARN_THRESH = 10_000;\nconst DEBUG_PRINT_HEARTBEAT = false; // very noisy\n\ntype ControlRpcBundle = {\n Control: ControlService;\n};\n\ntype ControlExtensionOpts = {\n heartbeatInterval: number;\n heartbeatTimeout: number;\n onTimeout: (err: any) => void;\n};\n\nexport class ControlExtension implements TeleportExtension {\n private readonly _ctx = new Context({\n onError: (err) => {\n this._extensionContext.close(err);\n },\n });\n\n public readonly onExtensionRegistered = new Callback<(extensionName: string) => void>();\n\n private _extensionContext!: ExtensionContext;\n private _rpc!: ProtoRpcPeer<{ Control: ControlService }>;\n\n constructor(\n private readonly opts: ControlExtensionOpts,\n private readonly localPeerId: PublicKey,\n private readonly remotePeerId: PublicKey,\n ) {}\n\n async registerExtension(name: string) {\n await this._rpc.rpc.Control.registerExtension({ name });\n }\n\n async onOpen(extensionContext: ExtensionContext): Promise<void> {\n this._extensionContext = extensionContext;\n\n this._rpc = createProtoRpcPeer<ControlRpcBundle, ControlRpcBundle>({\n requested: {\n Control: schema.getService('dxos.mesh.teleport.control.ControlService'),\n },\n exposed: {\n Control: schema.getService('dxos.mesh.teleport.control.ControlService'),\n },\n handlers: {\n Control: {\n registerExtension: async (request) => {\n this.onExtensionRegistered.call(request.name);\n },\n heartbeat: async (request) => {\n if (DEBUG_PRINT_HEARTBEAT) {\n log('received heartbeat request', {\n ts: request.requestTimestamp,\n localPeerId: this.localPeerId.truncate(),\n remotePeerId: this.remotePeerId.truncate(),\n });\n }\n return {\n requestTimestamp: request.requestTimestamp,\n };\n },\n },\n },\n port: await extensionContext.createPort('rpc', {\n contentType: 'application/x-protobuf; messageType=\"dxos.rpc.Message\"',\n }),\n timeout: this.opts.heartbeatTimeout,\n });\n\n await this._rpc.open();\n\n scheduleTaskInterval(\n this._ctx,\n async () => {\n const reqTS = new Date();\n try {\n const resp = await asyncTimeout(\n this._rpc.rpc.Control.heartbeat({ requestTimestamp: reqTS }),\n this.opts.heartbeatTimeout,\n );\n const now = Date.now();\n // TODO(nf): properly instrument\n if (resp.requestTimestamp instanceof Date) {\n if (\n now - resp.requestTimestamp.getTime() >\n (HEARTBEAT_RTT_WARN_THRESH < this.opts.heartbeatTimeout\n ? HEARTBEAT_RTT_WARN_THRESH\n : this.opts.heartbeatTimeout / 2)\n ) {\n log.warn(`heartbeat RTT for Teleport > ${HEARTBEAT_RTT_WARN_THRESH / 1000}s`, {\n rtt: now - resp.requestTimestamp.getTime(),\n localPeerId: this.localPeerId.truncate(),\n remotePeerId: this.remotePeerId.truncate(),\n });\n } else {\n if (DEBUG_PRINT_HEARTBEAT) {\n log('heartbeat RTT', {\n rtt: now - resp.requestTimestamp.getTime(),\n localPeerId: this.localPeerId.truncate(),\n remotePeerId: this.remotePeerId.truncate(),\n });\n }\n }\n }\n } catch (err: any) {\n const now = Date.now();\n if (err instanceof RpcClosedError) {\n // TODO: expose 'closed' event in Rpc peer to close context as soon the the peer gets closed\n log('ignoring RpcClosedError in heartbeat');\n this._extensionContext.close(err);\n return;\n }\n if (err instanceof AsyncTimeoutError) {\n log('timeout waiting for heartbeat response', { err, delay: now - reqTS.getTime() });\n this.opts.onTimeout(err);\n } else {\n log.info('other error waiting for heartbeat response', { err, delay: now - reqTS.getTime() });\n this.opts.onTimeout(err);\n }\n }\n },\n this.opts.heartbeatInterval,\n );\n }\n\n async onClose(err?: Error): Promise<void> {\n await this._ctx.dispose();\n await this._rpc.close();\n }\n\n async onAbort(err?: Error | undefined): Promise<void> {\n await this._ctx.dispose();\n await this._rpc.abort();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Duplex } from 'node:stream';\n\nimport { Event } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { type RpcPort } from './rpc-port';\n\nconst FRAME_LENGTH_SIZE = 2;\n\n/**\n * Converts a stream of binary messages into a framed RpcPort.\n * Buffers are written prefixed by their length encoded as a varint.\n */\nexport class Framer {\n // private readonly _tagBuffer = Buffer.alloc(4)\n private _messageCb?: (msg: Uint8Array) => void = undefined;\n private _subscribeCb?: () => void = undefined;\n private _buffer?: Buffer = undefined; // The rest of the bytes from the previous write call.\n private _sendCallbacks: (() => void)[] = [];\n\n private _bytesSent = 0;\n private _bytesReceived = 0;\n\n private _writable = true;\n\n readonly drain = new Event();\n\n // TODO(egorgripasov): Consider using a Transform stream if it provides better backpressure handling.\n private readonly _stream = new Duplex({\n objectMode: false,\n read: () => {\n this._processResponseQueue();\n },\n write: (chunk, encoding, callback) => {\n invariant(!this._subscribeCb, 'Internal Framer bug. Concurrent writes detected.');\n\n this._bytesReceived += chunk.length;\n\n if (this._buffer && this._buffer.length > 0) {\n this._buffer = Buffer.concat([this._buffer, chunk]);\n } else {\n this._buffer = chunk;\n }\n\n if (this._messageCb) {\n this._popFrames();\n callback();\n } else {\n this._subscribeCb = () => {\n // Schedule the processing of the chunk after the peer subscribes to the messages.\n this._popFrames();\n this._subscribeCb = undefined;\n callback();\n };\n }\n },\n });\n\n public readonly port: RpcPort = {\n send: (message) => {\n // log('write', { len: message.length, frame: Buffer.from(message).toString('hex') })\n return new Promise<void>((resolve) => {\n const frame = encodeFrame(message);\n this._bytesSent += frame.length;\n this._writable = this._stream.push(frame);\n if (!this._writable) {\n this._sendCallbacks.push(resolve);\n } else {\n resolve();\n }\n });\n },\n subscribe: (callback) => {\n invariant(!this._messageCb, 'Rpc port already has a message listener.');\n this._messageCb = callback;\n this._subscribeCb?.();\n return () => {\n this._messageCb = undefined;\n };\n },\n };\n\n get stream(): Duplex {\n return this._stream;\n }\n\n get bytesSent() {\n return this._bytesSent;\n }\n\n get bytesReceived() {\n return this._bytesReceived;\n }\n\n get writable() {\n return this._writable;\n }\n\n private _processResponseQueue() {\n const responseQueue = this._sendCallbacks;\n this._sendCallbacks = [];\n this._writable = true;\n this.drain.emit();\n responseQueue.forEach((cb) => cb());\n }\n\n /**\n * Attempts to pop frames from the buffer and call the message callback.\n */\n private _popFrames() {\n let offset = 0;\n while (offset < this._buffer!.length) {\n const frame = decodeFrame(this._buffer!, offset);\n\n if (!frame) {\n break; // Couldn't read frame but there are still bytes left in the buffer.\n }\n offset += frame.bytesConsumed;\n // TODO(dmaretskyi): Possible bug if the peer unsubscribes while we're reading frames.\n // log('read', { len: frame.payload.length, frame: Buffer.from(frame.payload).toString('hex') })\n this._messageCb!(frame.payload);\n }\n\n if (offset < this._buffer!.length) {\n // Save the rest of the bytes for the next write call.\n this._buffer = this._buffer!.subarray(offset);\n } else {\n this._buffer = undefined;\n }\n }\n\n destroy() {\n // TODO(dmaretskyi): Call stream.end() instead?\n if (this._stream.readableLength > 0) {\n log('framer destroyed while there are still read bytes in the buffer.');\n }\n if (this._stream.writableLength > 0) {\n log.warn('framer destroyed while there are still write bytes in the buffer.');\n }\n this._stream.destroy();\n }\n}\n\n/**\n * Attempts to read a frame from the input buffer.\n */\nexport const decodeFrame = (buffer: Buffer, offset: number): { payload: Buffer; bytesConsumed: number } | undefined => {\n if (buffer.length < offset + FRAME_LENGTH_SIZE) {\n // Not enough bytes to read the frame length.\n return undefined;\n }\n\n const frameLength = buffer.readUInt16BE(offset);\n const bytesConsumed = FRAME_LENGTH_SIZE + frameLength;\n\n if (buffer.length < offset + bytesConsumed) {\n // Not enough bytes to read the frame.\n return undefined;\n }\n\n const payload = buffer.subarray(offset + FRAME_LENGTH_SIZE, offset + bytesConsumed);\n\n return {\n payload,\n bytesConsumed,\n };\n};\n\nexport const encodeFrame = (payload: Uint8Array): Buffer => {\n const frame = Buffer.allocUnsafe(FRAME_LENGTH_SIZE + payload.length);\n frame.writeUInt16BE(payload.length, 0);\n frame.set(payload, FRAME_LENGTH_SIZE);\n return frame;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { Duplex } from 'node:stream';\n\nimport { scheduleTaskInterval, Event, Trigger, asyncTimeout } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { failUndefined } from '@dxos/debug';\nimport { invariant } from '@dxos/invariant';\nimport { type PublicKey } from '@dxos/keys';\nimport { log, logInfo } from '@dxos/log';\nimport { TimeoutError } from '@dxos/protocols';\nimport { schema } from '@dxos/protocols/proto';\nimport { type ConnectionInfo } from '@dxos/protocols/proto/dxos/devtools/swarm';\nimport { type Command } from '@dxos/protocols/proto/dxos/mesh/muxer';\n\nimport { Balancer } from './balancer';\nimport { type RpcPort } from './rpc-port';\n\nconst Command = schema.getCodecForType('dxos.mesh.muxer.Command');\n\nconst DEFAULT_SEND_COMMAND_TIMEOUT = 60_000;\nconst DESTROY_COMMAND_SEND_TIMEOUT = 5_000;\n\nexport type CleanupCb = void | (() => void);\n\nexport type CreateChannelOpts = {\n /**\n * MIME type of the wire content.\n *\n * Examples:\n * - application/octet-stream\n * - application/x-protobuf; messageType=\"dxos.rpc.Message\"\n */\n contentType?: string;\n};\n\nexport type MuxerStats = {\n timestamp: number;\n channels: ConnectionInfo.StreamStats[];\n bytesSent: number;\n bytesReceived: number;\n bytesSentRate?: number;\n bytesReceivedRate?: number;\n readBufferSize?: number;\n writeBufferSize?: number;\n};\n\nconst STATS_INTERVAL = 1_000;\nconst MAX_SAFE_FRAME_SIZE = 1_000_000;\nconst SYSTEM_CHANNEL_ID = 0;\nconst GRACEFUL_CLOSE_TIMEOUT = 3_000;\n\ntype Channel = {\n /**\n * Our local channel ID.\n * Incoming Data commands will have this ID.\n */\n id: number;\n tag: string;\n\n /**\n * Remote id is set when we receive an OpenChannel command.\n * The originating Data commands should carry this id.\n */\n remoteId: null | number;\n\n contentType?: string;\n\n /**\n * Send buffer.\n */\n buffer: Uint8Array[];\n\n /**\n * Set when we initialize a NodeJS stream or an RPC port consuming the channel.\n */\n push: null | ((data: Uint8Array) => void);\n\n destroy: null | ((err?: Error) => void);\n\n stats: {\n bytesSent: number;\n bytesReceived: number;\n };\n};\n\ntype CreateChannelInternalParams = {\n tag: string;\n contentType?: string;\n};\n\n/**\n * Channel based multiplexer.\n *\n * Can be used to open a number of channels represented by streams or RPC ports.\n * Performs framing for RPC ports.\n * Will buffer data until the remote peer opens the channel.\n *\n * The API will not advertise channels that as they are opened by the remote peer.\n * A higher level API (could be build on top of this muxer) for channel discovery is required.\n */\nexport class Muxer {\n private readonly _balancer = new Balancer(SYSTEM_CHANNEL_ID);\n private readonly _channelsByLocalId = new Map<number, Channel>();\n private readonly _channelsByTag = new Map<string, Channel>();\n private readonly _ctx = new Context();\n private _sessionId?: PublicKey;\n\n private _nextId = 1;\n\n private _closing = false;\n private _destroying = false;\n private _disposed = false;\n\n private _lastStats?: MuxerStats = undefined;\n private readonly _lastChannelStats = new Map<number, Channel['stats']>();\n\n public afterClosed = new Event<Error | undefined>();\n public statsUpdated = new Event<MuxerStats>();\n\n public readonly stream = this._balancer.stream;\n\n constructor() {\n // Add a channel for control messages.\n this._balancer.incomingData.on(async (msg) => {\n await this._handleCommand(Command.decode(msg));\n });\n }\n\n setSessionId(sessionId: PublicKey) {\n this._sessionId = sessionId;\n }\n\n @logInfo\n get sessionIdString(): string {\n return this._sessionId ? this._sessionId.truncate() : 'none';\n }\n\n /**\n * Creates a duplex Node.js-style stream.\n * The remote peer is expected to call `createStream` with the same tag.\n * The stream is immediately readable and writable.\n * NOTE: The data will be buffered until the stream is opened remotely with the same tag (may cause a memory leak).\n */\n async createStream(tag: string, opts: CreateChannelOpts = {}): Promise<Duplex> {\n const channel = this._getOrCreateStream({\n tag,\n contentType: opts.contentType,\n });\n invariant(!channel.push, `Channel already open: ${tag}`);\n\n const stream = new Duplex({\n write: (data, encoding, callback) => {\n this._sendData(channel, data)\n .then(() => callback())\n .catch(callback);\n // TODO(dmaretskyi): Should we error if sending data has errored?\n },\n read: () => {}, // No-op. We will push data when we receive it.\n });\n\n channel.push = (data) => {\n channel.stats.bytesReceived += data.length;\n stream.push(data);\n };\n channel.destroy = (err) => {\n // TODO(dmaretskyi): Call stream.end() instead?\n if (err) {\n if (stream.listeners('error').length > 0) {\n stream.destroy(err);\n } else {\n stream.destroy();\n }\n } else {\n stream.destroy();\n }\n };\n\n // NOTE: Make sure channel.push is set before sending the command.\n try {\n await this._sendCommand(\n {\n openChannel: {\n id: channel.id,\n tag: channel.tag,\n contentType: channel.contentType,\n },\n },\n SYSTEM_CHANNEL_ID,\n );\n } catch (err: any) {\n this._destroyChannel(channel, err);\n throw err;\n }\n\n return stream;\n }\n\n /**\n * Creates an RPC port.\n * The remote peer is expected to call `createPort` with the same tag.\n * The port is immediately usable.\n * NOTE: The data will be buffered until the stream is opened remotely with the same tag (may cause a memory leak).\n */\n async createPort(tag: string, opts: CreateChannelOpts = {}): Promise<RpcPort> {\n const channel = this._getOrCreateStream({\n tag,\n contentType: opts.contentType,\n });\n invariant(!channel.push, `Channel already open: ${tag}`);\n\n // We need to buffer incoming data until the port is subscribed to.\n let inboundBuffer: Uint8Array[] = [];\n let callback: ((data: Uint8Array) => void) | undefined;\n\n channel.push = (data) => {\n channel.stats.bytesReceived += data.length;\n if (callback) {\n callback(data);\n } else {\n inboundBuffer.push(data);\n }\n };\n\n const port: RpcPort = {\n send: async (data: Uint8Array, timeout?: number) => {\n await this._sendData(channel, data, timeout);\n // TODO(dmaretskyi): Debugging.\n // appendFileSync('log.json', JSON.stringify(schema.getCodecForType('dxos.rpc.RpcMessage').decode(data), null, 2) + '\\n')\n },\n subscribe: (cb: (data: Uint8Array) => void) => {\n invariant(!callback, 'Only one subscriber is allowed');\n callback = cb;\n for (const data of inboundBuffer) {\n cb(data);\n }\n inboundBuffer = [];\n },\n };\n\n // NOTE: Make sure channel.push is set before sending the command.\n try {\n await this._sendCommand(\n {\n openChannel: {\n id: channel.id,\n tag: channel.tag,\n contentType: channel.contentType,\n },\n },\n SYSTEM_CHANNEL_ID,\n );\n } catch (err: any) {\n this._destroyChannel(channel, err);\n throw err;\n }\n\n return port;\n }\n\n // initiate graceful close\n\n async close(err?: Error) {\n if (this._destroying) {\n log('already destroying, ignoring graceful close request');\n return;\n }\n if (this._closing) {\n log('already closing, ignoring graceful close request');\n return;\n }\n\n this._closing = true;\n\n await this._sendCommand(\n {\n close: {\n error: err?.message,\n },\n },\n SYSTEM_CHANNEL_ID,\n DESTROY_COMMAND_SEND_TIMEOUT,\n ).catch(async (err: any) => {\n log('error sending close command', { err });\n\n await this._dispose(err);\n });\n\n // don't return until close is complete or timeout\n await asyncTimeout(this._dispose(err), GRACEFUL_CLOSE_TIMEOUT, new TimeoutError('gracefully closing muxer'));\n }\n\n // force close without confirmation\n\n async destroy(err?: Error) {\n if (this._destroying) {\n log('already destroying, ignoring destroy request');\n return;\n }\n this._destroying = true;\n void this._ctx.dispose();\n if (this._closing) {\n log('destroy cancelling graceful close');\n this._closing = false;\n } else {\n // as a courtesy to the peer, send destroy command but ignore errors sending\n\n await this._sendCommand(\n {\n close: {\n error: err?.message,\n },\n },\n SYSTEM_CHANNEL_ID,\n ).catch(async (err: any) => {\n log('error sending courtesy close command', { err });\n });\n }\n\n this._dispose(err).catch((err) => {\n log('error disposing after destroy', { err });\n });\n }\n\n // complete the termination, graceful or otherwise\n\n async _dispose(err?: Error) {\n if (this._disposed) {\n log('already destroyed, ignoring dispose request');\n return;\n }\n\n void this._ctx.dispose();\n\n await this._balancer.destroy();\n\n for (const channel of this._channelsByTag.values()) {\n channel.destroy?.(err);\n }\n this._disposed = true;\n await this._emitStats();\n\n this.afterClosed.emit(err);\n\n // Make it easy for GC.\n this._channelsByLocalId.clear();\n this._channelsByTag.clear();\n }\n\n private async _handleCommand(cmd: Command) {\n if (this._disposed) {\n log.warn('Received command after disposed', { cmd });\n return;\n }\n\n if (cmd.close) {\n if (!this._closing) {\n log('received peer close, initiating my own graceful close');\n await this.close(new Error('received peer close'));\n } else {\n log('received close from peer, already closing');\n }\n\n return;\n }\n\n if (cmd.openChannel) {\n const channel = this._getOrCreateStream({\n tag: cmd.openChannel.tag,\n contentType: cmd.openChannel.contentType,\n });\n channel.remoteId = cmd.openChannel.id;\n\n // Flush any buffered data.\n for (const data of channel.buffer) {\n await this._sendCommand(\n {\n data: {\n channelId: channel.remoteId!,\n data,\n },\n },\n channel.id,\n );\n }\n channel.buffer = [];\n } else if (cmd.data) {\n const stream = this._channelsByLocalId.get(cmd.data.channelId) ?? failUndefined();\n if (!stream.push) {\n log.warn('Received data for channel before it was opened', { tag: stream.tag });\n return;\n }\n stream.push(cmd.data.data);\n }\n }\n\n private async _sendCommand(cmd: Command, channelId = -1, timeout = DEFAULT_SEND_COMMAND_TIMEOUT) {\n if (this._disposed) {\n // log.info('ignoring sendCommand after disposed', { cmd });\n return;\n }\n try {\n const trigger = new Trigger<void>();\n this._balancer.pushData(Command.encode(cmd), trigger, channelId);\n await trigger.wait({ timeout });\n } catch (err: any) {\n await this.destroy(err);\n }\n }\n\n private _getOrCreateStream(params: CreateChannelInternalParams): Channel {\n if (this._channelsByTag.size === 0) {\n scheduleTaskInterval(this._ctx, async () => this._emitStats(), STATS_INTERVAL);\n }\n let channel = this._channelsByTag.get(params.tag);\n if (!channel) {\n channel = {\n id: this._nextId++,\n remoteId: null,\n tag: params.tag,\n contentType: params.contentType,\n buffer: [],\n push: null,\n destroy: null,\n stats: {\n bytesSent: 0,\n bytesReceived: 0,\n },\n };\n this._channelsByTag.set(channel.tag, channel);\n this._channelsByLocalId.set(channel.id, channel);\n this._balancer.addChannel(channel.id);\n }\n\n return channel;\n }\n\n private async _sendData(channel: Channel, data: Uint8Array, timeout?: number): Promise<void> {\n if (data.length > MAX_SAFE_FRAME_SIZE) {\n log.warn('frame size exceeds maximum safe value', { size: data.length, threshold: MAX_SAFE_FRAME_SIZE });\n }\n\n channel.stats.bytesSent += data.length;\n if (channel.remoteId === null) {\n // Remote side has not opened the channel yet.\n channel.buffer.push(data);\n return;\n }\n await this._sendCommand(\n {\n data: {\n channelId: channel.remoteId,\n data,\n },\n },\n channel.id,\n timeout,\n );\n }\n\n private _destroyChannel(channel: Channel, err?: Error) {\n if (channel.destroy) {\n channel.destroy(err);\n }\n\n this._channelsByLocalId.delete(channel.id);\n this._channelsByTag.delete(channel.tag);\n }\n\n private async _emitStats() {\n if (this._disposed || this._destroying) {\n if (!this._lastStats) {\n return;\n }\n\n // zero out counting stats to not skew metrics.\n const lastStats = this._lastStats;\n this._lastStats = undefined;\n\n lastStats.readBufferSize = 0;\n lastStats.writeBufferSize = 0;\n for (const c of lastStats.channels) {\n c.writeBufferSize = 0;\n }\n this.statsUpdated.emit(lastStats);\n\n this._lastChannelStats.clear();\n return;\n }\n\n const bytesSent = this._balancer.bytesSent;\n const bytesReceived = this._balancer.bytesReceived;\n\n const now = Date.now();\n const interval = this._lastStats ? (now - this._lastStats.timestamp) / 1_000 : 0;\n const calculateThroughput = (current: Channel['stats'], last: Channel['stats'] | undefined) =>\n last\n ? {\n bytesSentRate: interval ? (current.bytesSent - last.bytesSent) / interval : undefined,\n bytesReceivedRate: interval ? (current.bytesReceived - last.bytesReceived) / interval : undefined,\n }\n : {};\n\n this._lastStats = {\n timestamp: now,\n channels: Array.from(this._channelsByTag.values()).map((channel) => {\n const stats: ConnectionInfo.StreamStats = {\n id: channel.id,\n tag: channel.tag,\n contentType: channel.contentType,\n writeBufferSize: channel.buffer.length,\n bytesSent: channel.stats.bytesSent,\n bytesReceived: channel.stats.bytesReceived,\n ...calculateThroughput(channel.stats, this._lastChannelStats.get(channel.id)),\n };\n\n this._lastChannelStats.set(channel.id, stats);\n return stats;\n }),\n bytesSent,\n bytesReceived,\n ...calculateThroughput({ bytesSent, bytesReceived }, this._lastStats),\n readBufferSize: this._balancer.stream.readableLength,\n writeBufferSize: this._balancer.stream.writableLength,\n };\n\n this.statsUpdated.emit(this._lastStats);\n }\n}\n", "//\n// Copyright 2023 DXOS.org\n//\n\nimport * as varint from 'varint';\n\nimport { type Trigger, Event } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\n\nimport { Framer } from './framer';\n\nconst MAX_CHUNK_SIZE = 8192;\n\ntype Chunk = {\n chunk: Uint8Array;\n channelId: number;\n dataLength?: number;\n};\n\ntype ChunkEnvelope = {\n msg: Buffer;\n trigger?: Trigger;\n};\n\ntype ChannelBuffer = {\n buffer: Buffer;\n msgLength: number;\n};\n\n/**\n * Load balancer for handling asynchronous calls from multiple channels.\n *\n * Manages a queue of calls from different channels and ensures that the calls\n * are processed in a balanced manner in a round-robin fashion.\n */\nexport class Balancer {\n private _lastCallerIndex = 0;\n private _channels: number[] = [];\n\n private readonly _framer = new Framer();\n // TODO(egorgripasov): Will cause a memory leak if channels do not appreciate the backpressure.\n private readonly _sendBuffers: Map<number, ChunkEnvelope[]> = new Map();\n private readonly _receiveBuffers = new Map<number, ChannelBuffer>();\n\n private _sending = false;\n public incomingData = new Event<Uint8Array>();\n public readonly stream = this._framer.stream;\n\n constructor(private readonly _sysChannelId: number) {\n this._channels.push(_sysChannelId);\n\n // Handle incoming messages.\n this._framer.port.subscribe(this._processIncomingMessage.bind(this));\n }\n\n get bytesSent() {\n return this._framer.bytesSent;\n }\n\n get bytesReceived() {\n return this._framer.bytesReceived;\n }\n\n get buffersCount() {\n return this._sendBuffers.size;\n }\n\n addChannel(channel: number) {\n this._channels.push(channel);\n }\n\n pushData(data: Uint8Array, trigger: Trigger, channelId: number) {\n this._enqueueChunk(data, trigger, channelId);\n this._sendChunks().catch((err) => log.catch(err));\n }\n\n destroy() {\n if (this._sendBuffers.size !== 0) {\n log.info('destroying balancer with pending calls');\n }\n this._sendBuffers.clear();\n this._framer.destroy();\n }\n\n private _processIncomingMessage(msg: Uint8Array) {\n const { channelId, dataLength, chunk } = decodeChunk(msg, (channelId) => !this._receiveBuffers.has(channelId));\n if (!this._receiveBuffers.has(channelId)) {\n if (chunk.length < dataLength!) {\n this._receiveBuffers.set(channelId, {\n buffer: Buffer.from(chunk),\n msgLength: dataLength!,\n });\n } else {\n this.incomingData.emit(chunk);\n }\n } else {\n const channelBuffer = this._receiveBuffers.get(channelId)!;\n channelBuffer.buffer = Buffer.concat([channelBuffer.buffer, chunk]);\n if (channelBuffer.buffer.length < channelBuffer.msgLength) {\n return;\n }\n const msg = channelBuffer.buffer;\n this._receiveBuffers.delete(channelId);\n this.incomingData.emit(msg);\n }\n }\n\n private _getNextCallerId() {\n if (this._sendBuffers.has(this._sysChannelId)) {\n return this._sysChannelId;\n }\n\n const index = this._lastCallerIndex;\n this._lastCallerIndex = (this._lastCallerIndex + 1) % this._channels.length;\n\n return this._channels[index];\n }\n\n private _enqueueChunk(data: Uint8Array, trigger: Trigger, channelId: number) {\n if (!this._channels.includes(channelId)) {\n throw new Error(`Unknown channel ${channelId}`);\n }\n\n if (!this._sendBuffers.has(channelId)) {\n this._sendBuffers.set(channelId, []);\n }\n\n const sendBuffer = this._sendBuffers.get(channelId)!;\n\n const chunks = [];\n for (let idx = 0; idx < data.length; idx += MAX_CHUNK_SIZE) {\n chunks.push(data.subarray(idx, idx + MAX_CHUNK_SIZE));\n }\n\n chunks.forEach((chunk, index) => {\n const msg = encodeChunk({\n chunk,\n channelId,\n dataLength: index === 0 ? data.length : undefined,\n });\n sendBuffer.push({ msg, trigger: index === chunks.length - 1 ? trigger : undefined });\n });\n }\n\n // get the next chunk or null if there are no chunks remaining\n\n private _getNextChunk(): ChunkEnvelope | null {\n let chunk;\n while (this._sendBuffers.size > 0) {\n const channelId = this._getNextCallerId();\n const sendBuffer = this._sendBuffers.get(channelId);\n if (!sendBuffer) {\n continue;\n }\n\n chunk = sendBuffer.shift();\n if (!chunk) {\n continue;\n }\n if (sendBuffer.length === 0) {\n this._sendBuffers.delete(channelId);\n }\n return chunk;\n }\n return null;\n }\n\n private async _sendChunks() {\n if (this._sending) {\n return;\n }\n this._sending = true;\n let chunk: ChunkEnvelope | null;\n chunk = this._getNextChunk();\n while (chunk) {\n // TODO(nf): determine whether this is needed since we await the chunk send\n if (!this._framer.writable) {\n log('PAUSE for drain');\n await this._framer.drain.waitForCount(1);\n log('RESUME for drain');\n }\n try {\n await this._framer.port.send(chunk.msg);\n chunk.trigger?.wake();\n } catch (err: any) {\n log('Error sending chunk', { err });\n chunk.trigger?.throw(err);\n }\n chunk = this._getNextChunk();\n }\n invariant(this._sendBuffers.size === 0, 'sendBuffers not empty');\n this._sending = false;\n }\n}\n\nexport const encodeChunk = ({ channelId, dataLength, chunk }: Chunk): Buffer => {\n const channelTagLength = varint.encodingLength(channelId);\n const dataLengthLength = dataLength ? varint.encodingLength(dataLength) : 0;\n const message = Buffer.allocUnsafe(channelTagLength + dataLengthLength + chunk.length);\n varint.encode(channelId, message);\n if (dataLength) {\n varint.encode(dataLength, message, channelTagLength);\n }\n message.set(chunk, channelTagLength + dataLengthLength);\n return message;\n};\n\nexport const decodeChunk = (data: Uint8Array, withLength: (channelId: number) => boolean): Chunk => {\n const channelId = varint.decode(data);\n let dataLength: number | undefined;\n let offset = varint.decode.bytes;\n\n if (withLength(channelId)) {\n dataLength = varint.decode(data, offset);\n offset += varint.decode.bytes;\n }\n\n const chunk = data.subarray(offset);\n\n return { channelId, dataLength, chunk };\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { asyncTimeout, Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols/proto';\nimport { type TestService } from '@dxos/protocols/proto/example/testing/rpc';\nimport { createProtoRpcPeer, type ProtoRpcPeer } from '@dxos/rpc';\n\nimport { type ExtensionContext, type TeleportExtension } from '../teleport';\n\ninterface TestExtensionCallbacks {\n onOpen?: () => Promise<void>;\n onClose?: () => Promise<void>;\n onAbort?: () => Promise<void>;\n}\n\nexport class TestExtension implements TeleportExtension {\n public readonly open = new Trigger();\n public readonly closed = new Trigger();\n public readonly aborted = new Trigger();\n public extensionContext: ExtensionContext | undefined;\n private _rpc!: ProtoRpcPeer<{ TestService: TestService }>;\n\n constructor(public readonly callbacks: TestExtensionCallbacks = {}) {}\n\n get remotePeerId() {\n return this.extensionContext?.remotePeerId;\n }\n\n async onOpen(context: ExtensionContext) {\n log('onOpen', { localPeerId: context.localPeerId, remotePeerId: context.remotePeerId });\n this.extensionContext = context;\n this._rpc = createProtoRpcPeer<{ TestService: TestService }, { TestService: TestService }>({\n port: await context.createPort('rpc', {\n contentType: 'application/x-protobuf; messageType=\"dxos.rpc.Message\"',\n }),\n requested: {\n TestService: schema.getService('example.testing.rpc.TestService'),\n },\n exposed: {\n TestService: schema.getService('example.testing.rpc.TestService'),\n },\n handlers: {\n TestService: {\n voidCall: async (request) => {\n // Ok.\n },\n testCall: async (request) => {\n return {\n data: request.data,\n };\n },\n },\n },\n timeout: 2000,\n });\n\n await this._rpc.open();\n await this.callbacks.onOpen?.();\n\n this.open.wake();\n }\n\n async onClose(err?: Error) {\n log('onClose', { err });\n await this.callbacks.onClose?.();\n this.closed.wake();\n await this._rpc?.close();\n }\n\n async onAbort(err?: Error) {\n log('onAbort', { err });\n await this.callbacks.onAbort?.();\n this.aborted.wake();\n await this._rpc?.abort();\n }\n\n async test(message = 'test') {\n await this.open.wait({ timeout: 2000 });\n const res = await asyncTimeout(this._rpc.rpc.TestService.testCall({ data: message }), 1500);\n invariant(res.data === message);\n }\n\n /**\n * Force-close the connection.\n */\n async closeConnection(err?: Error) {\n this.extensionContext?.close(err);\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport { randomBytes } from 'node:crypto';\nimport { type Duplex } from 'node:stream';\n\nimport { Trigger } from '@dxos/async';\nimport { invariant } from '@dxos/invariant';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols/proto';\nimport { type TestServiceWithStreams } from '@dxos/protocols/proto/example/testing/rpc';\nimport { createProtoRpcPeer, type ProtoRpcPeer } from '@dxos/rpc';\n\nimport { type ExtensionContext, type TeleportExtension } from '../teleport';\n\ninterface TestExtensionWithStreamsCallbacks {\n onOpen?: () => Promise<void>;\n onClose?: () => Promise<void>;\n onAbort?: () => Promise<void>;\n}\n\nexport class TestExtensionWithStreams implements TeleportExtension {\n public readonly open = new Trigger();\n public readonly closed = new Trigger();\n public readonly aborted = new Trigger();\n private readonly _streams = new Map<string, TestStream>();\n\n public extensionContext: ExtensionContext | undefined;\n private _rpc!: ProtoRpcPeer<{ TestServiceWithStreams: TestServiceWithStreams }>;\n\n constructor(public readonly callbacks: TestExtensionWithStreamsCallbacks = {}) {}\n\n get remotePeerId() {\n return this.extensionContext?.remotePeerId;\n }\n\n private async _openStream(streamTag: string, interval = 5, chunkSize = 2048) {\n invariant(!this._streams.has(streamTag), `Stream already exists: ${streamTag}`);\n\n const networkStream = await this.extensionContext!.createStream(streamTag, {\n contentType: 'application/x-test-stream',\n });\n\n const streamEntry: TestStream = {\n networkStream,\n bytesSent: 0,\n bytesReceived: 0,\n sendErrors: 0,\n receiveErrors: 0,\n startTimestamp: Date.now(),\n };\n\n const pushChunk = () => {\n streamEntry.timer = setTimeout(() => {\n const chunk = randomBytes(chunkSize);\n\n if (\n !networkStream.write(chunk, 'binary', (err) => {\n if (!err) {\n streamEntry.bytesSent += chunk.length;\n } else {\n streamEntry.sendErrors += 1;\n }\n })\n ) {\n networkStream.once('drain', pushChunk);\n } else {\n process.nextTick(pushChunk);\n }\n }, interval);\n };\n\n pushChunk();\n\n this._streams.set(streamTag, streamEntry);\n\n networkStream.on('data', (data) => {\n streamEntry.bytesReceived += data.length;\n });\n\n networkStream.on('error', (err) => {\n streamEntry.receiveErrors += 1;\n });\n\n networkStream.on('close', () => {\n networkStream.removeAllListeners();\n });\n\n streamEntry.reportingTimer = setInterval(() => {\n const { bytesSent, bytesReceived, sendErrors, receiveErrors } = streamEntry;\n // log.info('stream stats', { streamTag, bytesSent, bytesReceived, sendErrors, receiveErrors });\n log.trace('dxos.test.stream-stats', {\n streamTag,\n bytesSent,\n bytesReceived,\n sendErrors,\n receiveErrors,\n from: this.extensionContext?.localPeerId,\n to: this.extensionContext?.remotePeerId,\n });\n }, 100);\n }\n\n private _closeStream(streamTag: string): Stats {\n invariant(this._streams.has(streamTag), `Stream does not exist: ${streamTag}`);\n\n const stream = this._streams.get(streamTag)!;\n\n clearTimeout(stream.timer);\n clearTimeout(stream.reportingTimer);\n\n const { bytesSent, bytesReceived, sendErrors, receiveErrors, startTimestamp } = stream;\n\n stream.networkStream.destroy();\n this._streams.delete(streamTag);\n\n return {\n bytesSent,\n bytesReceived,\n sendErrors,\n receiveErrors,\n runningTime: Date.now() - (startTimestamp ?? 0),\n };\n }\n\n async onOpen(context: ExtensionContext) {\n log('onOpen', { localPeerId: context.localPeerId, remotePeerId: context.remotePeerId });\n this.extensionContext = context;\n this._rpc = createProtoRpcPeer<\n { TestServiceWithStreams: TestServiceWithStreams },\n { TestServiceWithStreams: TestServiceWithStreams }\n >({\n port: await context.createPort('rpc', {\n contentType: 'application/x-protobuf; messageType=\"dxos.rpc.Message\"',\n }),\n requested: {\n TestServiceWithStreams: schema.getService('example.testing.rpc.TestServiceWithStreams'),\n },\n exposed: {\n TestServiceWithStreams: schema.getService('example.testing.rpc.TestServiceWithStreams'),\n },\n handlers: {\n TestServiceWithStreams: {\n requestTestStream: async (request) => {\n const { data: streamTag, streamLoadInterval, streamLoadChunkSize } = request;\n\n await this._openStream(streamTag, streamLoadInterval, streamLoadChunkSize);\n\n return {\n data: streamTag,\n };\n },\n closeTestStream: async (request) => {\n const streamTag = request.data;\n const { bytesSent, bytesReceived, sendErrors, receiveErrors, runningTime } = this._closeStream(streamTag);\n\n return {\n data: streamTag,\n bytesSent,\n bytesReceived,\n sendErrors,\n receiveErrors,\n runningTime,\n };\n },\n },\n },\n timeout: 2000,\n });\n\n await this._rpc.open();\n await this.callbacks.onOpen?.();\n\n this.open.wake();\n }\n\n async onClose(err?: Error) {\n log('onClose', { err });\n await this.callbacks.onClose?.();\n this.closed.wake();\n for (const [streamTag, stream] of Object.entries(this._streams)) {\n log('closing stream', { streamTag });\n clearTimeout(stream.interval);\n stream.networkStream.destroy();\n }\n await this._rpc?.close();\n }\n\n async onAbort(err?: Error) {\n log('onAbort', { err });\n await this.callbacks.onAbort?.();\n this.aborted.wake();\n await this._rpc?.abort();\n }\n\n async addNewStream(streamLoadInterval: number, streamLoadChunkSize: number, streamTag?: string): Promise<string> {\n await this.open.wait({ timeout: 1500 });\n if (!streamTag) {\n streamTag = `stream-${randomBytes(4).toString('hex')}`;\n }\n const { data } = await this._rpc.rpc.TestServiceWithStreams.requestTestStream({\n data: streamTag,\n streamLoadInterval,\n streamLoadChunkSize,\n });\n invariant(data === streamTag);\n\n await this._openStream(streamTag, streamLoadInterval, streamLoadChunkSize);\n return streamTag;\n }\n\n async closeStream(streamTag: string): Promise<TestStreamStats> {\n await this.open.wait({ timeout: 1500 });\n const { data, bytesSent, bytesReceived, sendErrors, receiveErrors, runningTime } =\n await this._rpc.rpc.TestServiceWithStreams.closeTestStream({\n data: streamTag,\n });\n\n invariant(data === streamTag);\n\n const local = this._closeStream(streamTag);\n\n return {\n streamTag,\n stats: {\n local,\n remote: {\n bytesSent,\n bytesReceived,\n sendErrors,\n receiveErrors,\n runningTime,\n },\n },\n };\n }\n\n /**\n * Force-close the connection.\n */\n async closeConnection(err?: Error) {\n this.extensionContext?.close(err);\n }\n}\n\ntype Stats = {\n bytesSent: number;\n bytesReceived: number;\n sendErrors: number;\n receiveErrors: number;\n runningTime: number;\n};\n\nexport type TestStreamStats = {\n streamTag: string;\n stats: {\n local: Stats;\n remote: Stats;\n };\n};\n\ntype TestStream = {\n networkStream: Duplex;\n bytesSent: number;\n bytesReceived: number;\n sendErrors: number;\n receiveErrors: number;\n timer?: NodeJS.Timer;\n startTimestamp?: number;\n reportingTimer?: NodeJS.Timer;\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,yBAAsC;AAEtC,mBAAiC;AACjC,uBAA0B;AAC1B,kBAA0B;AAC1B,iBAAoB;ACHpB,IAAAA,gBAA0E;AAC1E,qBAAwB;AACxB,mBAA8B;AAC9B,IAAAC,oBAA0B;AAC1B,IAAAC,eAA0B;AAC1B,IAAAC,cAA6B;AAC7B,uBAA6C;ACR7C,IAAAH,gBAAsF;AACtF,IAAAI,kBAAwB;AAExB,IAAAD,cAAoB;AACpB,IAAAE,oBAA+B;AAC/B,mBAAuB;AAEvB,iBAAsD;AACtD,kBAAyB;ACRzB,IAAAC,sBAAuB;AAEvB,IAAAN,gBAAsB;AACtB,IAAAC,oBAA0B;AAC1B,IAAAE,cAAoB;ACJpB,IAAAG,sBAAuB;AAEvB,IAAAN,gBAAmE;AACnE,IAAAI,kBAAwB;AACxB,IAAAG,gBAA8B;AAC9B,IAAAN,oBAA0B;AAE1B,IAAAE,cAA6B;AAC7B,IAAAE,oBAA6B;AAC7B,IAAAG,gBAAuB;ACTvB,aAAwB;AAExB,IAAAR,gBAAoC;AACpC,IAAAC,oBAA0B;AAC1B,IAAAE,cAAoB;ACJpB,IAAAH,gBAAsC;AACtC,IAAAC,oBAA0B;AAC1B,IAAAE,cAAoB;AACpB,IAAAK,gBAAuB;AAEvB,IAAAC,cAAsD;ACLtD,yBAA4B;AAG5B,IAAAT,gBAAwB;AACxB,IAAAC,oBAA0B;AAC1B,IAAAE,cAAoB;AACpB,IAAAK,gBAAuB;AAEvB,IAAAC,cAAsD;;ALItD,IAAMC,4BAA4B;AAClC,IAAMC,wBAAwB;AAYvB,IAAMC,mBAAN,MAAMA;EAY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uBAAuBC,kBAAkB;MAC5ExM,MAAMkL;MACNuB;MACAC;IACF,CAAA;AACAjQ,0BAAAA,WAAUuD,SAASkL,WAAAA,QAAAA;;;;;;;;;AAEnB,UAAM,KAAKD,YAAYC,WAAWuB,oBAAoBC,mBAAAA;AACtD,WAAOxB;EACT;EAEA,MAAM8B,YAAY9B,WAA6C;AAC7D,UAAM,KAAKhR,KAAKiL,KAAK;MAAEnL,SAAS;IAAK,CAAA;AACrC,UAAM,EAAEgG,MAAMvC,WAAWC,eAAe4N,YAAYC,eAAee,YAAW,IAC5E,MAAM,KAAK3T,KAAKC,IAAI2T,uBAAuBI,gBAAgB;MACzD3M,MAAMkL;IACR,CAAA;AAEFzO,0BAAAA,WAAUuD,SAASkL,WAAAA,QAAAA;;;;;;;;;AAEnB,UAAM+B,QAAQ,KAAKb,aAAalB,SAAAA;AAEhC,WAAO;MACLA;MACA/G,OAAO;QACL8I;QACAC,QAAQ;UACNzP;UACAC;UACA4N;UACAC;UACAe;QACF;MACF;IACF;EACF;;;;EAKA,MAAM1C,gBAAgBxR,KAAa;AACjC,SAAKW,kBAAkBT,MAAMF,GAAAA;EAC/B;AACF;",
6
+ "names": ["import_async", "import_invariant", "import_keys", "import_log", "import_context", "import_protocols", "import_node_stream", "import_debug", "import_proto", "import_rpc", "HEARTBEAT_RTT_WARN_THRESH", "DEBUG_PRINT_HEARTBEAT", "ControlExtension", "constructor", "opts", "localPeerId", "remotePeerId", "_ctx", "Context", "onError", "err", "_extensionContext", "close", "onExtensionRegistered", "Callback", "registerExtension", "name", "_rpc", "rpc", "Control", "onOpen", "extensionContext", "createProtoRpcPeer", "requested", "schema", "getService", "exposed", "handlers", "request", "call", "heartbeat", "log", "ts", "requestTimestamp", "truncate", "port", "createPort", "contentType", "timeout", "heartbeatTimeout", "open", "scheduleTaskInterval", "reqTS", "Date", "resp", "asyncTimeout", "now", "getTime", "warn", "rtt", "RpcClosedError", "AsyncTimeoutError", "delay", "onTimeout", "info", "heartbeatInterval", "onClose", "dispose", "onAbort", "abort", "FRAME_LENGTH_SIZE", "Framer", "undefined", "_subscribeCb", "_buffer", "_sendCallbacks", "_bytesSent", "_bytesReceived", "_writable", "drain", "Event", "Duplex", "objectMode", "read", "_processResponseQueue", "write", "chunk", "encoding", "callback", "invariant", "length", "Buffer", "concat", "_messageCb", "_popFrames", "send", "message", "Promise", "resolve", "frame", "encodeFrame", "_stream", "push", "subscribe", "stream", "bytesSent", "bytesReceived", "writable", "responseQueue", "emit", "forEach", "cb", "offset", "decodeFrame", "bytesConsumed", "payload", "subarray", "destroy", "readableLength", "writableLength", "buffer", "frameLength", "readUInt16BE", "allocUnsafe", "writeUInt16BE", "set", "MAX_CHUNK_SIZE", "Balancer", "_sysChannelId", "_lastCallerIndex", "_channels", "_framer", "_sendBuffers", "Map", "_receiveBuffers", "_sending", "incomingData", "_processIncomingMessage", "bind", "buffersCount", "size", "addChannel", "channel", "pushData", "data", "trigger", "channelId", "_enqueueChunk", "_sendChunks", "catch", "clear", "msg", "dataLength", "decodeChunk", "has", "from", "msgLength", "channelBuffer", "get", "delete", "_getNextCallerId", "index", "includes", "Error", "sendBuffer", "chunks", "idx", "encodeChunk", "_getNextChunk", "shift", "waitForCount", "wake", "throw", "channelTagLength", "encodingLength", "dataLengthLength", "encode", "withLength", "decode", "bytes", "Command", "getCodecForType", "DEFAULT_SEND_COMMAND_TIMEOUT", "DESTROY_COMMAND_SEND_TIMEOUT", "STATS_INTERVAL", "MAX_SAFE_FRAME_SIZE", "SYSTEM_CHANNEL_ID", "GRACEFUL_CLOSE_TIMEOUT", "Muxer", "_balancer", "_channelsByLocalId", "_channelsByTag", "_nextId", "_closing", "_destroying", "_disposed", "_lastStats", "_lastChannelStats", "afterClosed", "statsUpdated", "on", "_handleCommand", "setSessionId", "sessionId", "_sessionId", "sessionIdString", "createStream", "tag", "_getOrCreateStream", "_sendData", "then", "stats", "listeners", "_sendCommand", "openChannel", "id", "_destroyChannel", "inboundBuffer", "error", "_dispose", "TimeoutError", "values", "_emitStats", "cmd", "remoteId", "failUndefined", "Trigger", "wait", "params", "threshold", "lastStats", "readBufferSize", "writeBufferSize", "c", "channels", "interval", "timestamp", "calculateThroughput", "current", "last", "bytesSentRate", "bytesReceivedRate", "Array", "map", "logInfo", "CONTROL_HEARTBEAT_INTERVAL", "CONTROL_HEARTBEAT_TIMEOUT", "Teleport", "initiator", "rest", "_muxer", "_extensions", "_remoteExtensions", "Set", "_open", "_aborting", "PublicKey", "isPublicKey", "_control", "controlHeartbeatInterval", "controlHeartbeatTimeout", "add", "_openExtension", "trace", "isOpen", "random", "_setExtension", "disposed", "extension", "extensionsCount", "addExtension", "scheduleTask", "extensionName", "context", "channelName", "runInContextAsync", "synchronized", "TestBuilder", "_peers", "createPeer", "peer", "factory", "createPeers", "all", "agent", "connect", "peer1", "peer2", "connection1", "createConnection", "peerId", "connection2", "pipeStreams", "teleport", "openConnection", "disconnect", "connections", "find", "connection", "equals", "closeConnection", "TestPeer", "TestConnection", "stream1", "stream2", "pipeline", "code", "whenOpen", "waitForCondition", "condition", "TestExtension", "callbacks", "closed", "aborted", "TestService", "voidCall", "testCall", "test", "res", "TestExtensionWithStreams", "_streams", "_openStream", "streamTag", "chunkSize", "networkStream", "streamEntry", "sendErrors", "receiveErrors", "startTimestamp", "pushChunk", "timer", "setTimeout", "randomBytes", "once", "process", "nextTick", "removeAllListeners", "reportingTimer", "setInterval", "to", "_closeStream", "clearTimeout", "runningTime", "TestServiceWithStreams", "requestTestStream", "streamLoadInterval", "streamLoadChunkSize", "closeTestStream", "Object", "entries", "addNewStream", "toString", "closeStream", "local", "remote"]
7
+ }
@@ -18,20 +18,20 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
  var node_exports = {};
20
20
  __export(node_exports, {
21
- Framer: () => import_chunk_6CFOQWV3.Framer,
22
- Muxer: () => import_chunk_6CFOQWV3.Muxer,
21
+ Framer: () => import_chunk_OMLDRTR3.Framer,
22
+ Muxer: () => import_chunk_OMLDRTR3.Muxer,
23
23
  RpcExtension: () => RpcExtension,
24
- Teleport: () => import_chunk_6CFOQWV3.Teleport,
25
- TestBuilder: () => import_chunk_6CFOQWV3.TestBuilder,
26
- TestConnection: () => import_chunk_6CFOQWV3.TestConnection,
27
- TestExtension: () => import_chunk_6CFOQWV3.TestExtension,
28
- TestExtensionWithStreams: () => import_chunk_6CFOQWV3.TestExtensionWithStreams,
29
- TestPeer: () => import_chunk_6CFOQWV3.TestPeer,
30
- decodeFrame: () => import_chunk_6CFOQWV3.decodeFrame,
31
- encodeFrame: () => import_chunk_6CFOQWV3.encodeFrame
24
+ Teleport: () => import_chunk_OMLDRTR3.Teleport,
25
+ TestBuilder: () => import_chunk_OMLDRTR3.TestBuilder,
26
+ TestConnection: () => import_chunk_OMLDRTR3.TestConnection,
27
+ TestExtension: () => import_chunk_OMLDRTR3.TestExtension,
28
+ TestExtensionWithStreams: () => import_chunk_OMLDRTR3.TestExtensionWithStreams,
29
+ TestPeer: () => import_chunk_OMLDRTR3.TestPeer,
30
+ decodeFrame: () => import_chunk_OMLDRTR3.decodeFrame,
31
+ encodeFrame: () => import_chunk_OMLDRTR3.encodeFrame
32
32
  });
33
33
  module.exports = __toCommonJS(node_exports);
34
- var import_chunk_6CFOQWV3 = require("./chunk-6CFOQWV3.cjs");
34
+ var import_chunk_OMLDRTR3 = require("./chunk-OMLDRTR3.cjs");
35
35
  var import_invariant = require("@dxos/invariant");
36
36
  var import_rpc = require("@dxos/rpc");
37
37
  var __dxlog_file = "/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/rpc-extension.ts";