@dxos/teleport 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +8 -0
  2. package/README.md +0 -0
  3. package/dist/lib/browser/index.mjs +544 -0
  4. package/dist/lib/browser/index.mjs.map +7 -0
  5. package/dist/lib/browser/meta.json +1 -0
  6. package/dist/lib/browser/testing.mjs +621 -0
  7. package/dist/lib/browser/testing.mjs.map +7 -0
  8. package/dist/lib/node/index.cjs +580 -0
  9. package/dist/lib/node/index.cjs.map +7 -0
  10. package/dist/lib/node/meta.json +1 -0
  11. package/dist/lib/node/testing.cjs +653 -0
  12. package/dist/lib/node/testing.cjs.map +7 -0
  13. package/dist/types/src/index.d.ts +3 -0
  14. package/dist/types/src/index.d.ts.map +1 -0
  15. package/dist/types/src/muxing/framer.d.ts +29 -0
  16. package/dist/types/src/muxing/framer.d.ts.map +1 -0
  17. package/dist/types/src/muxing/framer.test.d.ts +2 -0
  18. package/dist/types/src/muxing/framer.test.d.ts.map +1 -0
  19. package/dist/types/src/muxing/index.d.ts +4 -0
  20. package/dist/types/src/muxing/index.d.ts.map +1 -0
  21. package/dist/types/src/muxing/muxer.d.ts +60 -0
  22. package/dist/types/src/muxing/muxer.d.ts.map +1 -0
  23. package/dist/types/src/muxing/muxer.test.d.ts +2 -0
  24. package/dist/types/src/muxing/muxer.test.d.ts.map +1 -0
  25. package/dist/types/src/muxing/rpc-port.d.ts +11 -0
  26. package/dist/types/src/muxing/rpc-port.d.ts.map +1 -0
  27. package/dist/types/src/muxing/rpc-port.test.d.ts +2 -0
  28. package/dist/types/src/muxing/rpc-port.test.d.ts.map +1 -0
  29. package/dist/types/src/teleport.d.ts +47 -0
  30. package/dist/types/src/teleport.d.ts.map +1 -0
  31. package/dist/types/src/teleport.test.d.ts +2 -0
  32. package/dist/types/src/teleport.test.d.ts.map +1 -0
  33. package/dist/types/src/test-extension.d.ts +12 -0
  34. package/dist/types/src/test-extension.d.ts.map +1 -0
  35. package/dist/types/src/testing.d.ts +29 -0
  36. package/dist/types/src/testing.d.ts.map +1 -0
  37. package/package.json +47 -0
  38. package/src/index.ts +6 -0
  39. package/src/muxing/framer.test.ts +160 -0
  40. package/src/muxing/framer.ts +132 -0
  41. package/src/muxing/index.ts +7 -0
  42. package/src/muxing/muxer.test.ts +185 -0
  43. package/src/muxing/muxer.ts +301 -0
  44. package/src/muxing/rpc-port.test.ts +18 -0
  45. package/src/muxing/rpc-port.ts +15 -0
  46. package/src/teleport.test.ts +81 -0
  47. package/src/teleport.ts +277 -0
  48. package/src/test-extension.ts +65 -0
  49. package/src/testing.ts +75 -0
  50. package/testing.d.ts +11 -0
  51. package/testing.js +5 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/testing.ts", "../../../src/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/teleport.ts", "../../../src/muxing/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/framer.ts", "../../../src/muxing/home/runner/work/dxos/dxos/packages/core/mesh/teleport/src/muxing/muxer.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2022 DXOS.org\n//\n\nimport { pipeline } from 'node:stream';\n\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\n\nimport { Teleport } from './teleport';\n\nexport class TestBuilder {\n private readonly _peers = new Array<TestPeer>();\n\n createPeer(peerId?: PublicKey): TestPeer {\n const peer = new TestPeer(peerId);\n this._peers.push(peer);\n return peer;\n }\n\n async destroy() {\n await Promise.all(this._peers.map((agent) => agent.destroy()));\n }\n\n /**\n * Simulates two peers connected via P2P network.\n */\n async createPipedPeers({ peerId1, peerId2 }: { peerId1?: PublicKey; peerId2?: PublicKey } = {}) {\n const peer1 = this.createPeer(peerId1);\n const peer2 = this.createPeer(peerId2);\n\n peer1.initializeTeleport({ initiator: true, remotePeerId: peer2.peerId });\n peer2.initializeTeleport({ initiator: false, remotePeerId: peer1.peerId });\n\n peer1.pipeline(peer2);\n peer2.pipeline(peer1);\n\n await Promise.all([peer1.teleport!.open(), peer2.teleport!.open()]);\n\n return { peer1, peer2 };\n }\n}\n\nexport class TestPeer {\n public teleport?: Teleport;\n\n constructor(public readonly peerId: PublicKey = PublicKey.random()) {}\n\n initializeTeleport({ initiator, remotePeerId }: { initiator: boolean; remotePeerId: PublicKey }) {\n if (this.teleport) {\n return this;\n }\n this.teleport = new Teleport({\n initiator,\n localPeerId: this.peerId,\n remotePeerId\n });\n return this;\n }\n\n pipeline(peer: TestPeer) {\n if (!this.teleport || !peer.teleport) {\n throw new Error('Teleport not initialized');\n }\n pipeline(this.teleport.stream, peer.teleport.stream, (err) => {\n if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {\n log.catch(err);\n }\n });\n }\n\n async destroy() {\n await this.teleport?.destroy();\n }\n}\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\nimport { Duplex } from 'node:stream';\n\nimport { asyncTimeout, scheduleTaskInterval, runInContextAsync, synchronized, scheduleTask } from '@dxos/async';\nimport { Context } from '@dxos/context';\nimport { failUndefined } from '@dxos/debug';\nimport { PublicKey } from '@dxos/keys';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols';\nimport { ControlService } from '@dxos/protocols/proto/dxos/mesh/teleport/control';\nimport { createProtoRpcPeer, ProtoRpcPeer, RpcClosedError } from '@dxos/rpc';\nimport { Callback } from '@dxos/util';\n\nimport { CreateChannelOpts, Muxer, RpcPort } from './muxing';\n\nexport type TeleportParams = {\n initiator: boolean;\n localPeerId: PublicKey;\n remotePeerId: PublicKey;\n};\n\nexport class Teleport {\n public readonly initiator: boolean;\n public readonly localPeerId: PublicKey;\n public readonly remotePeerId: 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 = new ControlExtension({\n heartbeatInterval: 3000,\n heartbeatTimeout: 3000\n });\n\n private readonly _extensions = new Map<string, TeleportExtension>();\n private readonly _remoteExtensions = new Set<string>();\n\n private _open = false;\n\n constructor({ initiator, localPeerId, remotePeerId }: TeleportParams) {\n assert(typeof initiator === 'boolean');\n assert(PublicKey.isPublicKey(localPeerId));\n assert(PublicKey.isPublicKey(remotePeerId));\n assert(typeof initiator === 'boolean');\n this.initiator = initiator;\n this.localPeerId = localPeerId;\n this.remotePeerId = remotePeerId;\n\n this._control.onExtensionRegistered.set(async (name) => {\n log('remote extension', { name });\n assert(!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 await this.destroy();\n });\n\n this._muxer.stream.on('error', async (err) => {\n await this.destroy(err);\n });\n }\n }\n\n get stream(): Duplex {\n return this._muxer.stream;\n }\n\n /**\n * Blocks until the handshake is complete.\n */\n async open() {\n this._setExtension('dxos.mesh.teleport.control', this._control);\n await this._openExtension('dxos.mesh.teleport.control');\n this._open = true;\n }\n\n async close(err?: Error) {\n // TODO(dmaretskyi): Try soft close.\n\n await this.destroy(err);\n }\n\n @synchronized\n async destroy(err?: Error) {\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.onClose(err);\n } catch (err: any) {\n log.catch(err);\n }\n }\n\n this._muxer.destroy(err);\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 assert(!extensionName.includes('/'), 'Invalid extension name');\n assert(!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: (channelName: string, opts?: CreateChannelOpts) => {\n assert(!channelName.includes('/'), 'Invalid channel name');\n return this._muxer.createPort(`${extensionName}/${channelName}`, opts);\n },\n createStream: (channelName: string, opts?: CreateChannelOpts) => {\n assert(!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): Duplex;\n createPort(tag: string, opts?: CreateChannelOpts): RpcPort;\n close(err?: Error): void;\n};\n\nexport interface TeleportExtension {\n onOpen(context: ExtensionContext): Promise<void>;\n onClose(err?: Error): Promise<void>;\n}\n\ntype ControlExtensionOpts = {\n heartbeatInterval: number;\n heartbeatTimeout: number;\n};\n\nclass ControlExtension implements TeleportExtension {\n private readonly _ctx = new Context({\n onError: (err) => {\n this._extensionContext.close(err);\n }\n });\n\n private _extensionContext!: ExtensionContext;\n private _rpc!: ProtoRpcPeer<{ Control: ControlService }>;\n\n public readonly onExtensionRegistered = new Callback<(extensionName: string) => void>();\n public readonly onTimeout = new Callback<() => void>();\n\n constructor(private readonly opts: ControlExtensionOpts) {}\n\n async onOpen(extensionContext: ExtensionContext): Promise<void> {\n this._extensionContext = extensionContext;\n\n // NOTE: Make sure that RPC timeout is greater than the heartbeat timeout.\n // TODO(dmaretskyi): Allow overwriting the timeout on individual RPC calls?\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 // Ok.\n }\n }\n },\n port: extensionContext.createPort('rpc', {\n contentType: 'application/x-protobuf; messageType=\"dxos.rpc.Message\"'\n })\n });\n\n await this._rpc.open();\n\n scheduleTaskInterval(\n this._ctx,\n async () => {\n try {\n await asyncTimeout(this._rpc.rpc.Control.heartbeat(), this.opts.heartbeatTimeout);\n } catch (err: any) {\n this.onTimeout.call();\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 registerExtension(name: string) {\n await this._rpc.rpc.Control.registerExtension({ name });\n }\n}\n\ntype ControlRpcBundle = {\n Control: ControlService;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\nimport { Duplex } from 'node:stream';\nimport * as varint from 'varint';\n\nimport { RpcPort } from './rpc-port';\n\n/**\n * Framer that turns a stream of binary messages into a framed RpcPort.\n *\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;\n private _subscribeCb?: () => void;\n private _buffer?: Buffer; // The rest of the bytes from the previous write call.\n\n private readonly _stream = new Duplex({\n objectMode: false,\n read: () => {},\n write: (chunk, encoding, callback) => {\n assert(!this._subscribeCb, 'Internal Framer bug. Concurrent writes detected.');\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 this._stream.push(encodeLength(message.length));\n this._stream.push(message);\n },\n subscribe: (callback) => {\n assert(!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 /**\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 = readFrame(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 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 this._stream.destroy();\n }\n}\n\n/**\n * Attempts to read a frame from the input buffer.\n */\nexport const readFrame = (buffer: Buffer, offset: number): { payload: Buffer; bytesConsumed: number } | undefined => {\n try {\n const frameLength = varint.decode(buffer, offset);\n const tagLength = varint.decode.bytes;\n\n if (buffer.length < offset + tagLength + frameLength) {\n // Not enough bytes to read the frame.\n return undefined;\n }\n\n const payload = buffer.subarray(offset + tagLength, offset + tagLength + frameLength);\n\n return {\n payload,\n bytesConsumed: tagLength + frameLength\n };\n } catch (err) {\n if (err instanceof RangeError) {\n // Not enough bytes to read the tag.\n return undefined;\n } else {\n throw err;\n }\n }\n};\n\nconst encodeLength = (length: number) => {\n const res = varint.encode(length, Buffer.allocUnsafe(4)).subarray(0, varint.encode.bytes);\n if (varint.encode.bytes > 4) {\n throw new Error('Frame too large');\n }\n return res;\n};\n", "//\n// Copyright 2022 DXOS.org\n//\n\nimport assert from 'node:assert';\nimport { Duplex } from 'node:stream';\n\nimport { Event } from '@dxos/async';\nimport { failUndefined } from '@dxos/debug';\nimport { log } from '@dxos/log';\nimport { schema } from '@dxos/protocols';\nimport { Command } from '@dxos/protocols/proto/dxos/mesh/muxer';\n\nimport { Framer } from './framer';\nimport { RpcPort } from './rpc-port';\n\nconst codec = schema.getCodecForType('dxos.mesh.muxer.Command');\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\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 _framer = new Framer();\n public readonly stream = this._framer.stream;\n\n private readonly _channelsByLocalId = new Map<number, Channel>();\n private readonly _channelsByTag = new Map<string, Channel>();\n\n private _nextId = 0;\n private _destroyed = false;\n private _destroying = false;\n\n public close = new Event<Error | undefined>();\n\n constructor() {\n this._framer.port.subscribe((msg) => {\n this._handleCommand(codec.decode(msg));\n });\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 createStream(tag: string, opts: CreateChannelOpts = {}): Duplex {\n const channel = this._getOrCreateStream({\n tag,\n contentType: opts.contentType\n });\n assert(!channel.push, `Channel already open: ${tag}`);\n\n const stream = new Duplex({\n write: (data, encoding, callback) => {\n this._sendData(channel, data);\n // TODO(dmaretskyi): Should we error if sending data has errored?\n callback();\n },\n read: () => {} // No-op. We will push data when we receive it.\n });\n\n channel.push = (data) => {\n stream.push(data);\n };\n channel.destroy = (err) => {\n // TODO(dmaretskyi): Call stream.end() instead?\n stream.destroy(err);\n };\n\n // NOTE: Make sure channel.push is set before sending the command.\n this._sendCommand({\n openChannel: {\n id: channel.id,\n tag: channel.tag,\n contentType: channel.contentType\n }\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 createPort(tag: string, opts: CreateChannelOpts = {}): RpcPort {\n const channel = this._getOrCreateStream({\n tag,\n contentType: opts.contentType\n });\n assert(!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 if (callback) {\n callback(data);\n } else {\n inboundBuffer.push(data);\n }\n };\n\n const port: RpcPort = {\n send: (data: Uint8Array) => {\n this._sendData(channel, data); // TODO(dmaretskyi): Error propagation?\n\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 assert(!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 this._sendCommand({\n openChannel: {\n id: channel.id,\n tag: channel.tag,\n contentType: channel.contentType\n }\n });\n\n return port;\n }\n\n /**\n * Force-close with optional error.\n */\n destroy(err?: Error) {\n if (this._destroying) {\n return;\n }\n this._destroying = true;\n\n this._sendCommand({\n destroy: {\n error: err?.message\n }\n });\n this._dispose();\n }\n\n private _dispose(err?: Error) {\n if (this._destroyed) {\n return;\n }\n\n this._destroyed = true;\n this._framer.destroy();\n\n for (const channel of this._channelsByTag.values()) {\n channel.destroy?.(err);\n }\n\n this.close.emit(err);\n\n // Make it easy for GC.\n this._channelsByLocalId.clear();\n this._channelsByTag.clear();\n }\n\n private _handleCommand(cmd: Command) {\n log('Received command', { cmd });\n\n if (this._destroyed || this._destroying) {\n log.warn('Received command after destroy');\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 this._sendCommand({\n data: {\n channelId: channel.remoteId,\n data\n }\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 } else if (cmd.destroy) {\n this._dispose();\n }\n }\n\n private _sendCommand(cmd: Command) {\n Promise.resolve(this._framer.port.send(codec.encode(cmd))).catch((err) => {\n this.destroy(err);\n });\n }\n\n private _getOrCreateStream(params: CreateChannelInternalParams): Channel {\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 };\n this._channelsByTag.set(channel.tag, channel);\n this._channelsByLocalId.set(channel.id, channel);\n }\n return channel;\n }\n\n private _sendData(channel: Channel, data: Uint8Array) {\n if (channel.remoteId === null) {\n // Remote side has not opened the channel yet.\n channel.buffer.push(data);\n } else {\n this._sendCommand({\n data: {\n channelId: channel.remoteId,\n data\n }\n });\n }\n }\n}\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\ntype CreateChannelInternalParams = {\n tag: string;\n contentType?: string;\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;AAIA,IAAAA,sBAAyB;AAEzB,IAAAC,eAA0B;AAC1B,IAAAC,cAAoB;;;ACHpB,IAAAC,sBAAmB;AAGnB,IAAAC,gBAAkG;AAClG,qBAAwB;AACxB,IAAAC,gBAA8B;AAC9B,kBAA0B;AAC1B,IAAAC,cAAoB;AACpB,IAAAC,oBAAuB;AAEvB,iBAAiE;AACjE,kBAAyB;;;ACXzB,yBAAmB;AACnB,yBAAuB;AACvB,aAAwB;AASjB,IAAMC,SAAN,MAAMA;EAAN;AAMYC,mBAAU,IAAIC,0BAAO;MACpCC,YAAY;MACZC,MAAM,MAAM;MAAC;MACbC,OAAO,CAACC,OAAOC,UAAUC,aAAa;AACpCC,+BAAAA,SAAO,CAAC,KAAKC,cAAc,kDAAA;AAE3B,YAAI,KAAKC,WAAW,KAAKA,QAAQC,SAAS,GAAG;AAC3C,eAAKD,UAAUE,OAAOC,OAAO;YAAC,KAAKH;YAASL;WAAM;QACpD,OAAO;AACL,eAAKK,UAAUL;QACjB;AAEA,YAAI,KAAKS,YAAY;AACnB,eAAKC,WAAU;AACfR,mBAAAA;QACF,OAAO;AACL,eAAKE,eAAe,MAAM;AAExB,iBAAKM,WAAU;AACf,iBAAKN,eAAeO;AACpBT,qBAAAA;UACF;QACF;MACF;IACF,CAAA;AAEgBU,gBAAgB;MAC9BC,MAAM,CAACC,YAAY;AACjB,aAAKnB,QAAQoB,KAAKC,aAAaF,QAAQR,MAAM,CAAA;AAC7C,aAAKX,QAAQoB,KAAKD,OAAAA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AAQzB,KAAKiB,SAASQ,QAAQ,CAACC,QAAQ;AAC5D,UAAIA,OAAOA,IAAIC,SAAS,8BAA8B;AACpDC,wBAAIC,MAAMH,KAAAA,CAAAA,GAAAA;;;;;;MACZ;IACF,CAAA;EACF;EAEA,MAAMvB,UAAU;AAvElB;AAwEI,YAAM,UAAKc,aAAL,mBAAed;EACvB;AACF;",
6
+ "names": ["import_node_stream", "import_keys", "import_log", "import_node_assert", "import_async", "import_debug", "import_log", "import_protocols", "Framer", "_stream", "Duplex", "objectMode", "read", "write", "chunk", "encoding", "callback", "assert", "_subscribeCb", "_buffer", "length", "Buffer", "concat", "_messageCb", "_popFrames", "undefined", "port", "send", "message", "push", "encodeLength", "subscribe", "stream", "offset", "frame", "readFrame", "bytesConsumed", "payload", "subarray", "destroy", "buffer", "frameLength", "decode", "tagLength", "bytes", "err", "RangeError", "res", "encode", "allocUnsafe", "Error", "import_node_assert", "import_node_stream", "codec", "schema", "getCodecForType", "Muxer", "constructor", "_framer", "Framer", "stream", "_channelsByLocalId", "Map", "_channelsByTag", "_nextId", "_destroyed", "_destroying", "close", "Event", "port", "subscribe", "msg", "_handleCommand", "decode", "createStream", "tag", "opts", "channel", "_getOrCreateStream", "contentType", "assert", "push", "Duplex", "write", "data", "encoding", "callback", "_sendData", "read", "destroy", "err", "_sendCommand", "openChannel", "id", "createPort", "inboundBuffer", "send", "cb", "error", "message", "_dispose", "values", "emit", "clear", "cmd", "log", "warn", "remoteId", "buffer", "channelId", "get", "failUndefined", "Promise", "resolve", "encode", "catch", "params", "set", "Teleport", "constructor", "initiator", "localPeerId", "remotePeerId", "_ctx", "Context", "onError", "err", "destroy", "catch", "log", "error", "_muxer", "Muxer", "_control", "ControlExtension", "heartbeatInterval", "heartbeatTimeout", "_extensions", "Map", "_remoteExtensions", "Set", "_open", "assert", "PublicKey", "isPublicKey", "onExtensionRegistered", "set", "name", "has", "add", "_openExtension", "stream", "on", "open", "_setExtension", "close", "disposed", "dispose", "extension", "values", "onClose", "addExtension", "Error", "scheduleTask", "registerExtension", "RpcClosedError", "extensionName", "includes", "get", "failUndefined", "context", "createPort", "channelName", "opts", "createStream", "runInContextAsync", "onOpen", "synchronized", "_extensionContext", "Callback", "onTimeout", "extensionContext", "_rpc", "createProtoRpcPeer", "requested", "Control", "schema", "getService", "exposed", "handlers", "request", "call", "heartbeat", "port", "contentType", "scheduleTaskInterval", "asyncTimeout", "rpc", "TestBuilder", "_peers", "Array", "createPeer", "peerId", "peer", "TestPeer", "push", "destroy", "Promise", "all", "map", "agent", "createPipedPeers", "peerId1", "peerId2", "peer1", "peer2", "initializeTeleport", "initiator", "remotePeerId", "pipeline", "teleport", "open", "constructor", "PublicKey", "random", "Teleport", "localPeerId", "Error", "stream", "err", "code", "log", "catch"]
7
+ }
@@ -0,0 +1,3 @@
1
+ export * from './muxing';
2
+ export * from './teleport';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC"}
@@ -0,0 +1,29 @@
1
+ /// <reference types="node" />
2
+ import { Duplex } from 'node:stream';
3
+ import { RpcPort } from './rpc-port';
4
+ /**
5
+ * Framer that turns a stream of binary messages into a framed RpcPort.
6
+ *
7
+ * Buffers are written prefixed by their length encoded as a varint.
8
+ */
9
+ export declare class Framer {
10
+ private _messageCb?;
11
+ private _subscribeCb?;
12
+ private _buffer?;
13
+ private readonly _stream;
14
+ readonly port: RpcPort;
15
+ get stream(): Duplex;
16
+ /**
17
+ * Attempts to pop frames from the buffer and call the message callback.
18
+ */
19
+ private _popFrames;
20
+ destroy(): void;
21
+ }
22
+ /**
23
+ * Attempts to read a frame from the input buffer.
24
+ */
25
+ export declare const readFrame: (buffer: Buffer, offset: number) => {
26
+ payload: Buffer;
27
+ bytesConsumed: number;
28
+ } | undefined;
29
+ //# sourceMappingURL=framer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"framer.d.ts","sourceRoot":"","sources":["../../../../src/muxing/framer.ts"],"names":[],"mappings":";AAKA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAGrC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC;;;;GAIG;AACH,qBAAa,MAAM;IAEjB,OAAO,CAAC,UAAU,CAAC,CAA4B;IAC/C,OAAO,CAAC,YAAY,CAAC,CAAa;IAClC,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAwBrB;IAEH,SAAgB,IAAI,EAAE,OAAO,CAa3B;IAEF,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED;;OAEG;IACH,OAAO,CAAC,UAAU;IAqBlB,OAAO;CAIR;AAED;;GAEG;AACH,eAAO,MAAM,SAAS,WAAY,MAAM,UAAU,MAAM,KAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,aAAa,EAAE,MAAM,CAAA;CAAE,GAAG,SAwBvG,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=framer.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"framer.test.d.ts","sourceRoot":"","sources":["../../../../src/muxing/framer.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,4 @@
1
+ export * from './framer';
2
+ export * from './muxer';
3
+ export * from './rpc-port';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/muxing/index.ts"],"names":[],"mappings":"AAIA,cAAc,UAAU,CAAC;AACzB,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC"}
@@ -0,0 +1,60 @@
1
+ /// <reference types="node" />
2
+ import { Duplex } from 'node:stream';
3
+ import { Event } from '@dxos/async';
4
+ import { RpcPort } from './rpc-port';
5
+ export declare type CleanupCb = void | (() => void);
6
+ export declare type CreateChannelOpts = {
7
+ /**
8
+ * MIME type of the wire content.
9
+ *
10
+ * Examples:
11
+ * - application/octet-stream
12
+ * - application/x-protobuf; messageType="dxos.rpc.Message"
13
+ */
14
+ contentType?: string;
15
+ };
16
+ /**
17
+ * Channel based multiplexer.
18
+ *
19
+ * Can be used to open a number of channels represented by streams or RPC ports.
20
+ * Performs framing for RPC ports.
21
+ * Will buffer data until the remote peer opens the channel.
22
+ *
23
+ * The API will not advertise channels that as they are opened by the remote peer.
24
+ * A higher level API (could be build on top of this muxer) for channel discovery is required.
25
+ */
26
+ export declare class Muxer {
27
+ private readonly _framer;
28
+ readonly stream: Duplex;
29
+ private readonly _channelsByLocalId;
30
+ private readonly _channelsByTag;
31
+ private _nextId;
32
+ private _destroyed;
33
+ private _destroying;
34
+ close: Event<Error | undefined>;
35
+ constructor();
36
+ /**
37
+ * Creates a duplex Node.js-style stream.
38
+ * The remote peer is expected to call `createStream` with the same tag.
39
+ * The stream is immediately readable and writable.
40
+ * NOTE: The data will be buffered until the stream is opened remotely with the same tag (may cause a memory leak).
41
+ */
42
+ createStream(tag: string, opts?: CreateChannelOpts): Duplex;
43
+ /**
44
+ * Creates an RPC port.
45
+ * The remote peer is expected to call `createPort` with the same tag.
46
+ * The port is immediately usable.
47
+ * NOTE: The data will be buffered until the stream is opened remotely with the same tag (may cause a memory leak).
48
+ */
49
+ createPort(tag: string, opts?: CreateChannelOpts): RpcPort;
50
+ /**
51
+ * Force-close with optional error.
52
+ */
53
+ destroy(err?: Error): void;
54
+ private _dispose;
55
+ private _handleCommand;
56
+ private _sendCommand;
57
+ private _getOrCreateStream;
58
+ private _sendData;
59
+ }
60
+ //# sourceMappingURL=muxer.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"muxer.d.ts","sourceRoot":"","sources":["../../../../src/muxing/muxer.ts"],"names":[],"mappings":";AAKA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAOpC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAIrC,oBAAY,SAAS,GAAG,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC;AAE5C,oBAAY,iBAAiB,GAAG;IAC9B;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF;;;;;;;;;GASG;AACH,qBAAa,KAAK;IAChB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAgB;IACxC,SAAgB,MAAM,SAAuB;IAE7C,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAA8B;IACjE,OAAO,CAAC,QAAQ,CAAC,cAAc,CAA8B;IAE7D,OAAO,CAAC,OAAO,CAAK;IACpB,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,WAAW,CAAS;IAErB,KAAK,2BAAkC;;IAQ9C;;;;;OAKG;IACH,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE,iBAAsB,GAAG,MAAM;IAoC/D;;;;;OAKG;IACH,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,GAAE,iBAAsB,GAAG,OAAO;IAgD9D;;OAEG;IACH,OAAO,CAAC,GAAG,CAAC,EAAE,KAAK;IAcnB,OAAO,CAAC,QAAQ;IAmBhB,OAAO,CAAC,cAAc;IAqCtB,OAAO,CAAC,YAAY;IAMpB,OAAO,CAAC,kBAAkB;IAkB1B,OAAO,CAAC,SAAS;CAalB"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=muxer.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"muxer.test.d.ts","sourceRoot":"","sources":["../../../../src/muxing/muxer.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,11 @@
1
+ import { MaybePromise } from '@dxos/util';
2
+ /**
3
+ * Interface for a transport-agnostic port to send/receive binary messages.
4
+ *
5
+ * NOTE: Copied from @dxos/rpc to avoid dependency. Structural typing should still work.
6
+ */
7
+ export interface RpcPort {
8
+ send: (msg: Uint8Array) => MaybePromise<void>;
9
+ subscribe: (cb: (msg: Uint8Array) => void) => (() => void) | void;
10
+ }
11
+ //# sourceMappingURL=rpc-port.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-port.d.ts","sourceRoot":"","sources":["../../../../src/muxing/rpc-port.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C;;;;GAIG;AACH,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,CAAC,GAAG,EAAE,UAAU,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC;IAC9C,SAAS,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,EAAE,UAAU,KAAK,IAAI,KAAK,CAAC,MAAM,IAAI,CAAC,GAAG,IAAI,CAAC;CACnE"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=rpc-port.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-port.test.d.ts","sourceRoot":"","sources":["../../../../src/muxing/rpc-port.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,47 @@
1
+ /// <reference types="node" />
2
+ import { Duplex } from 'node:stream';
3
+ import { PublicKey } from '@dxos/keys';
4
+ import { CreateChannelOpts, RpcPort } from './muxing';
5
+ export declare type TeleportParams = {
6
+ initiator: boolean;
7
+ localPeerId: PublicKey;
8
+ remotePeerId: PublicKey;
9
+ };
10
+ export declare class Teleport {
11
+ readonly initiator: boolean;
12
+ readonly localPeerId: PublicKey;
13
+ readonly remotePeerId: PublicKey;
14
+ private readonly _ctx;
15
+ private readonly _muxer;
16
+ private readonly _control;
17
+ private readonly _extensions;
18
+ private readonly _remoteExtensions;
19
+ private _open;
20
+ constructor({ initiator, localPeerId, remotePeerId }: TeleportParams);
21
+ get stream(): Duplex;
22
+ /**
23
+ * Blocks until the handshake is complete.
24
+ */
25
+ open(): Promise<void>;
26
+ close(err?: Error): Promise<void>;
27
+ destroy(err?: Error): Promise<void>;
28
+ addExtension(name: string, extension: TeleportExtension): void;
29
+ private _setExtension;
30
+ private _openExtension;
31
+ }
32
+ export declare type ExtensionContext = {
33
+ /**
34
+ * One of the peers will be designated an initiator.
35
+ */
36
+ initiator: boolean;
37
+ localPeerId: PublicKey;
38
+ remotePeerId: PublicKey;
39
+ createStream(tag: string, opts?: CreateChannelOpts): Duplex;
40
+ createPort(tag: string, opts?: CreateChannelOpts): RpcPort;
41
+ close(err?: Error): void;
42
+ };
43
+ export interface TeleportExtension {
44
+ onOpen(context: ExtensionContext): Promise<void>;
45
+ onClose(err?: Error): Promise<void>;
46
+ }
47
+ //# sourceMappingURL=teleport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"teleport.d.ts","sourceRoot":"","sources":["../../../src/teleport.ts"],"names":[],"mappings":";AAKA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAKrC,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAOvC,OAAO,EAAE,iBAAiB,EAAS,OAAO,EAAE,MAAM,UAAU,CAAC;AAE7D,oBAAY,cAAc,GAAG;IAC3B,SAAS,EAAE,OAAO,CAAC;IACnB,WAAW,EAAE,SAAS,CAAC;IACvB,YAAY,EAAE,SAAS,CAAC;CACzB,CAAC;AAEF,qBAAa,QAAQ;IACnB,SAAgB,SAAS,EAAE,OAAO,CAAC;IACnC,SAAgB,WAAW,EAAE,SAAS,CAAC;IACvC,SAAgB,YAAY,EAAE,SAAS,CAAC;IAExC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAMlB;IAEH,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAe;IAEtC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAGtB;IAEH,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAwC;IACpE,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAqB;IAEvD,OAAO,CAAC,KAAK,CAAS;gBAEV,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,EAAE,cAAc;IAmCpE,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED;;OAEG;IACG,IAAI;IAMJ,KAAK,CAAC,GAAG,CAAC,EAAE,KAAK;IAOjB,OAAO,CAAC,GAAG,CAAC,EAAE,KAAK;IAkBzB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,iBAAiB;IA4BvD,OAAO,CAAC,aAAa;YAMP,cAAc;CA0B7B;AAED,oBAAY,gBAAgB,GAAG;IAC7B;;OAEG;IACH,SAAS,EAAE,OAAO,CAAC;IACnB,WAAW,EAAE,SAAS,CAAC;IACvB,YAAY,EAAE,SAAS,CAAC;IACxB,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,iBAAiB,GAAG,MAAM,CAAC;IAC5D,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC;IAC3D,KAAK,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC;CAC1B,CAAC;AAEF,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjD,OAAO,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACrC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=teleport.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"teleport.test.d.ts","sourceRoot":"","sources":["../../../src/teleport.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,12 @@
1
+ import { Trigger } from '@dxos/async';
2
+ import { ExtensionContext, TeleportExtension } from './teleport';
3
+ export declare class TestExtension implements TeleportExtension {
4
+ readonly closed: Trigger<void>;
5
+ extensionContext: ExtensionContext | undefined;
6
+ private _rpc;
7
+ private _opened;
8
+ onOpen(context: ExtensionContext): Promise<void>;
9
+ onClose(err?: Error): Promise<void>;
10
+ test(): Promise<void>;
11
+ }
12
+ //# sourceMappingURL=test-extension.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test-extension.d.ts","sourceRoot":"","sources":["../../../src/test-extension.ts"],"names":[],"mappings":"AAMA,OAAO,EAAgB,OAAO,EAAE,MAAM,aAAa,CAAC;AAMpD,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEjE,qBAAa,aAAc,YAAW,iBAAiB;IACrD,SAAgB,MAAM,gBAAiB;IAChC,gBAAgB,EAAE,gBAAgB,GAAG,SAAS,CAAC;IACtD,OAAO,CAAC,IAAI,CAA8C;IAC1D,OAAO,CAAC,OAAO,CAAiB;IAE1B,MAAM,CAAC,OAAO,EAAE,gBAAgB;IAiChC,OAAO,CAAC,GAAG,CAAC,EAAE,KAAK;IAMnB,IAAI;CAKX"}
@@ -0,0 +1,29 @@
1
+ import { PublicKey } from '@dxos/keys';
2
+ import { Teleport } from './teleport';
3
+ export declare class TestBuilder {
4
+ private readonly _peers;
5
+ createPeer(peerId?: PublicKey): TestPeer;
6
+ destroy(): Promise<void>;
7
+ /**
8
+ * Simulates two peers connected via P2P network.
9
+ */
10
+ createPipedPeers({ peerId1, peerId2 }?: {
11
+ peerId1?: PublicKey;
12
+ peerId2?: PublicKey;
13
+ }): Promise<{
14
+ peer1: TestPeer;
15
+ peer2: TestPeer;
16
+ }>;
17
+ }
18
+ export declare class TestPeer {
19
+ readonly peerId: PublicKey;
20
+ teleport?: Teleport;
21
+ constructor(peerId?: PublicKey);
22
+ initializeTeleport({ initiator, remotePeerId }: {
23
+ initiator: boolean;
24
+ remotePeerId: PublicKey;
25
+ }): this;
26
+ pipeline(peer: TestPeer): void;
27
+ destroy(): Promise<void>;
28
+ }
29
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../../src/testing.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAGvC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAyB;IAEhD,UAAU,CAAC,MAAM,CAAC,EAAE,SAAS,GAAG,QAAQ;IAMlC,OAAO;IAIb;;OAEG;IACG,gBAAgB,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,GAAE;QAAE,OAAO,CAAC,EAAE,SAAS,CAAC;QAAC,OAAO,CAAC,EAAE,SAAS,CAAA;KAAO;;;;CAc/F;AAED,qBAAa,QAAQ;aAGS,MAAM,EAAE,SAAS;IAFtC,QAAQ,CAAC,EAAE,QAAQ,CAAC;gBAEC,MAAM,GAAE,SAA8B;IAElE,kBAAkB,CAAC,EAAE,SAAS,EAAE,YAAY,EAAE,EAAE;QAAE,SAAS,EAAE,OAAO,CAAC;QAAC,YAAY,EAAE,SAAS,CAAA;KAAE;IAY/F,QAAQ,CAAC,IAAI,EAAE,QAAQ;IAWjB,OAAO;CAGd"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@dxos/teleport",
3
+ "version": "0.1.14",
4
+ "description": "Stream muxer.",
5
+ "homepage": "https://dxos.org",
6
+ "bugs": "https://github.com/dxos/dxos/issues",
7
+ "license": "MIT",
8
+ "author": "DXOS.org",
9
+ "main": "dist/lib/node/index.cjs",
10
+ "browser": {
11
+ "./dist/lib/node/index.cjs": "./dist/lib/browser/index.mjs",
12
+ "./dist/lib/node/testing.cjs": "./dist/lib/browser/index.mjs"
13
+ },
14
+ "types": "dist/types/src/index.d.ts",
15
+ "files": [
16
+ "testing.d.ts",
17
+ "testing.js",
18
+ "dist",
19
+ "src"
20
+ ],
21
+ "dependencies": {
22
+ "debug": "^4.3.3",
23
+ "randombytes": "^2.1.0",
24
+ "varint": "6.0.0",
25
+ "@dxos/context": "0.1.14",
26
+ "@dxos/debug": "0.1.14",
27
+ "@dxos/keys": "0.1.14",
28
+ "@dxos/log": "0.1.14",
29
+ "@dxos/node-std": "0.1.14",
30
+ "@dxos/protocols": "0.1.14",
31
+ "@dxos/rpc": "0.1.14",
32
+ "@dxos/util": "0.1.14"
33
+ },
34
+ "devDependencies": {
35
+ "@types/randombytes": "^2.0.0",
36
+ "@types/varint": "6.0.0",
37
+ "typescript": "^4.8.4",
38
+ "wait-for-expect": "^3.0.2",
39
+ "@dxos/async": "0.1.14"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "check": "true"
46
+ }
47
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ export * from './muxing';
6
+ export * from './teleport';
@@ -0,0 +1,160 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ import { expect } from 'chai';
6
+ import { pipeline } from 'node:stream';
7
+ import randomBytes from 'randombytes';
8
+ import * as varint from 'varint';
9
+ import waitForExpect from 'wait-for-expect';
10
+
11
+ import { sleep } from '@dxos/async';
12
+ import { afterTest, describe, test } from '@dxos/test';
13
+
14
+ import { Framer, readFrame } from './framer';
15
+
16
+ const pipeWithRandomizedChunks = (from: NodeJS.ReadableStream, to: NodeJS.WritableStream): (() => void) => {
17
+ let buffers: Buffer[] = [];
18
+ from.on('data', (data) => {
19
+ buffers.push(data);
20
+ });
21
+
22
+ // Flush data every millisecond.
23
+ const intervalId = setInterval(() => {
24
+ const buffer = Buffer.concat(buffers);
25
+
26
+ // console.log('flushing total', buffer.length)
27
+
28
+ let offset = 0;
29
+ while (offset < buffer.length) {
30
+ const chunkLength = Math.min(Math.floor(Math.random() * buffer.length * 1.2) + 1, buffer.length - offset);
31
+ // console.log('flush', chunkLength)
32
+ to.write(buffer.slice(offset, offset + chunkLength));
33
+ offset += chunkLength;
34
+ }
35
+ buffers = [];
36
+ }, 1);
37
+
38
+ return () => {
39
+ clearInterval(intervalId);
40
+ };
41
+ };
42
+
43
+ const pipe = (a: NodeJS.ReadWriteStream, b: NodeJS.ReadWriteStream): (() => void) => {
44
+ const cleanA = pipeWithRandomizedChunks(a, b);
45
+ const cleanB = pipeWithRandomizedChunks(b, a);
46
+ return () => {
47
+ cleanA();
48
+ cleanB();
49
+ };
50
+ };
51
+
52
+ describe('Framer', () => {
53
+ test('varints', () => {
54
+ const values = [0, 1, 5, 127, 128, 255, 256, 257, 1024, 1024 * 1024];
55
+ for (const value of values) {
56
+ const encoded = varint.encode(value, Buffer.allocUnsafe(4)).slice(0, varint.encode.bytes);
57
+ const length = varint.encode.bytes;
58
+ expect(encoded.length).to.eq(length);
59
+
60
+ const decoded = varint.decode(encoded);
61
+ expect(decoded).to.equal(value);
62
+ expect(varint.decode.bytes).to.equal(length);
63
+ }
64
+ });
65
+
66
+ test('frame encoding', () => {
67
+ const sizes = [0, 1, 5, 127, 128, 255, 256, 257, 1024, 1024 * 1024];
68
+ for (const size of sizes) {
69
+ const tag = varint.encode(size, Buffer.allocUnsafe(4)).slice(0, varint.encode.bytes);
70
+ const payload = randomBytes(size);
71
+ const frame = Buffer.concat([tag, payload]);
72
+ const decoded = readFrame(frame, 0);
73
+ expect(decoded?.bytesConsumed).to.equal(frame.length);
74
+ expect(decoded?.payload).to.deep.equal(payload);
75
+ }
76
+ });
77
+
78
+ // This test is a bit slow because of sleep and flush on interval.
79
+ test('end-to-end stress test', async () => {
80
+ const peer1 = new Framer();
81
+ const peer2 = new Framer();
82
+
83
+ const clean = pipe(peer1.stream, peer2.stream);
84
+ afterTest(clean);
85
+
86
+ // Peer 1 loops messages back to peer 2.
87
+ peer1.port.subscribe((message) => {
88
+ // console.log('lo', message.length)
89
+ void peer1.port.send(message);
90
+ });
91
+
92
+ const framesSent: Buffer[] = [];
93
+ const framesReceived: Buffer[] = [];
94
+ let subscribed = false;
95
+
96
+ // console.log('Start sending frames\n=================\n')
97
+
98
+ const TOTAL_FRAMES = 1000;
99
+ while (framesSent.length < TOTAL_FRAMES) {
100
+ const frame = randomBytes(Math.floor(Math.random() * 400));
101
+ // console.log('wrt', frame.length)
102
+ void peer2.port.send(frame);
103
+ framesSent.push(frame);
104
+
105
+ if (Math.random() < 0.1) {
106
+ // 10% chance to pause and check the messages.
107
+ await sleep(2);
108
+
109
+ if (!subscribed) {
110
+ // Simulate subscription delay
111
+ subscribed = true;
112
+ // console.log("subscribing")
113
+ peer2.port.subscribe((message) => {
114
+ // console.log('rcv', message.length)
115
+ framesReceived.push(Buffer.from(message));
116
+ });
117
+ }
118
+
119
+ await sleep(2); // Must be longer the pipe's flush interval
120
+ expect(framesReceived.length).to.deep.eq(framesSent.length);
121
+ for (const i in framesSent) {
122
+ expect(framesReceived[i]).to.deep.eq(framesSent[i], `Frame ${i} does not match`);
123
+ }
124
+ // console.log('Synced\n=================\n')
125
+ }
126
+ }
127
+ });
128
+
129
+ test('bench', async () => {
130
+ const peer1 = new Framer();
131
+ const peer2 = new Framer();
132
+
133
+ pipeline(peer1.stream, peer2.stream, peer1.stream, () => {});
134
+
135
+ // Peer 1 loops messages back to peer 2.
136
+ peer1.port.subscribe((message) => {
137
+ void peer1.port.send(message);
138
+ });
139
+
140
+ const framesSent: Buffer[] = [];
141
+ const framesReceived: Buffer[] = [];
142
+ peer2.port.subscribe((message) => {
143
+ framesReceived.push(Buffer.from(message));
144
+ });
145
+
146
+ const TOTAL_FRAMES = 1000;
147
+ while (framesSent.length < TOTAL_FRAMES) {
148
+ const frame = randomBytes(Math.floor(Math.random() * 400));
149
+ void peer2.port.send(frame);
150
+ framesSent.push(frame);
151
+ }
152
+
153
+ await waitForExpect(() => {
154
+ expect(framesReceived.length).to.deep.eq(framesSent.length);
155
+ for (const i in framesSent) {
156
+ expect(framesReceived[i]).to.deep.eq(framesSent[i], `Frame ${i} does not match`);
157
+ }
158
+ });
159
+ });
160
+ });