starpc 0.40.1 → 0.41.0

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.
@@ -1,27 +1,26 @@
1
1
  import { YamuxMuxerInit } from '@chainsafe/libp2p-yamux';
2
- import type { MessageStreamDirection, Stream, StreamMuxer, StreamMuxerFactory } from '@libp2p/interface';
3
- import type { Duplex, Source } from 'it-stream-types';
2
+ import type { ComponentLogger, Direction, Stream, StreamMuxer, StreamMuxerFactory } from '@libp2p/interface';
3
+ import type { Duplex } from 'it-stream-types';
4
4
  import { Uint8ArrayList } from 'uint8arraylist';
5
5
  import { type OpenStreamFunc, type PacketStream } from './stream.js';
6
6
  import { Client } from './client.js';
7
7
  export interface StreamConnParams {
8
- loggerName?: string;
8
+ logger?: ComponentLogger;
9
9
  muxerFactory?: StreamMuxerFactory;
10
- direction?: MessageStreamDirection;
10
+ direction?: Direction;
11
11
  yamuxParams?: YamuxMuxerInit;
12
12
  }
13
13
  export interface StreamHandler {
14
14
  handlePacketStream(strm: PacketStream): void;
15
15
  }
16
- export declare class StreamConn implements Duplex<AsyncIterable<Uint8Array | Uint8ArrayList>, Source<Uint8Array | Uint8ArrayList>, Promise<void>> {
16
+ export declare class StreamConn implements Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>> {
17
17
  private _muxer;
18
- private _messageStream;
19
18
  private _server?;
20
19
  constructor(server?: StreamHandler, connParams?: StreamConnParams);
21
- get sink(): (source: Source<Uint8Array | Uint8ArrayList>) => Promise<void>;
22
- get source(): AsyncIterable<Uint8Array | Uint8ArrayList>;
20
+ get sink(): import("it-stream-types").Sink<AsyncGenerator<Uint8Array<ArrayBufferLike> | Uint8ArrayList, any, any>, unknown>;
21
+ get source(): AsyncGenerator<Uint8Array<ArrayBufferLike> | Uint8ArrayList, any, any>;
23
22
  get streams(): Stream[];
24
- get muxer(): StreamMuxer<Stream>;
23
+ get muxer(): StreamMuxer;
25
24
  get server(): StreamHandler | undefined;
26
25
  buildClient(): Client;
27
26
  openStream(): Promise<PacketStream>;
package/dist/srpc/conn.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { yamux } from '@chainsafe/libp2p-yamux';
2
2
  import { streamToPacketStream, } from './stream.js';
3
3
  import { Client } from './client.js';
4
- import { createDuplexMessageStream, } from './duplex-message-stream.js';
4
+ import { createDisabledComponentLogger } from './log.js';
5
5
  // StreamConn implements a generic connection with a two-way stream.
6
6
  // The stream is not expected to manage packet boundaries.
7
7
  // Packets will be sent with uint32le length prefixes.
@@ -13,37 +13,28 @@ import { createDuplexMessageStream, } from './duplex-message-stream.js';
13
13
  export class StreamConn {
14
14
  // muxer is the stream muxer.
15
15
  _muxer;
16
- // messageStream wraps the duplex as a MessageStream for the muxer.
17
- _messageStream;
18
16
  // server is the server side, if set.
19
17
  _server;
20
18
  constructor(server, connParams) {
21
19
  if (server) {
22
20
  this._server = server;
23
21
  }
24
- // Create the MessageStream adapter
25
- const direction = connParams?.direction || 'outbound';
26
- this._messageStream = createDuplexMessageStream({
27
- loggerName: connParams?.loggerName,
28
- direction,
29
- });
30
- // Create the muxer factory - yamux(init)() returns a StreamMuxerFactory
31
22
  const muxerFactory = connParams?.muxerFactory ??
32
- yamux({ enableKeepAlive: false, ...connParams?.yamuxParams })();
33
- // Create the muxer with the MessageStream
34
- this._muxer = muxerFactory.createStreamMuxer(this._messageStream);
35
- // Listen for incoming streams
36
- this._muxer.addEventListener('stream', (evt) => {
37
- this.handleIncomingStream(evt.detail);
23
+ yamux({ enableKeepAlive: false, ...connParams?.yamuxParams })({
24
+ logger: connParams?.logger ?? createDisabledComponentLogger(),
25
+ });
26
+ this._muxer = muxerFactory.createStreamMuxer({
27
+ onIncomingStream: this.handleIncomingStream.bind(this),
28
+ direction: connParams?.direction || 'outbound',
38
29
  });
39
30
  }
40
31
  // sink returns the message sink.
41
32
  get sink() {
42
- return this._messageStream.sink;
33
+ return this._muxer.sink;
43
34
  }
44
35
  // source returns the outgoing message source.
45
36
  get source() {
46
- return this._messageStream.source;
37
+ return this._muxer.source;
47
38
  }
48
39
  // streams returns the set of all ongoing streams.
49
40
  get streams() {
@@ -63,7 +54,7 @@ export class StreamConn {
63
54
  }
64
55
  // openStream implements the client open stream function.
65
56
  async openStream() {
66
- const strm = await this.muxer.createStream();
57
+ const strm = await this.muxer.newStream();
67
58
  return streamToPacketStream(strm);
68
59
  }
69
60
  // buildOpenStreamFunc returns openStream bound to this conn.
@@ -20,4 +20,3 @@ export { HandleStreamCtr } from './handle-stream-ctr.js';
20
20
  export { writeToPushable, buildPushableSink, messagePushable, } from './pushable.js';
21
21
  export { Watchdog } from './watchdog.js';
22
22
  export { ProtoRpc } from './proto-rpc.js';
23
- export { DuplexMessageStream, DuplexMessageStreamInit, createDuplexMessageStream, } from './duplex-message-stream.js';
@@ -18,4 +18,3 @@ export { OpenStreamCtr } from './open-stream-ctr.js';
18
18
  export { HandleStreamCtr } from './handle-stream-ctr.js';
19
19
  export { writeToPushable, buildPushableSink, messagePushable, } from './pushable.js';
20
20
  export { Watchdog } from './watchdog.js';
21
- export { DuplexMessageStream, createDuplexMessageStream, } from './duplex-message-stream.js';
@@ -0,0 +1,3 @@
1
+ import type { ComponentLogger, Logger } from '@libp2p/interface';
2
+ export declare function createDisabledLogger(namespace: string): Logger;
3
+ export declare function createDisabledComponentLogger(): ComponentLogger;
@@ -0,0 +1,22 @@
1
+ // https://github.com/libp2p/js-libp2p/issues/2276
2
+ // https://github.com/libp2p/js-libp2p/blob/bca8d6e689b47d85dda74082ed72e671139391de/packages/logger/src/index.ts#L86
3
+ // https://github.com/libp2p/js-libp2p/issues/2275
4
+ // https://github.com/ChainSafe/js-libp2p-yamux/issues/69
5
+ export function createDisabledLogger(namespace) {
6
+ const logger = () => { };
7
+ logger.enabled = false;
8
+ logger.color = '';
9
+ logger.diff = 0;
10
+ logger.log = () => { };
11
+ logger.namespace = namespace;
12
+ logger.destroy = () => true;
13
+ logger.extend = () => logger;
14
+ logger.debug = logger;
15
+ logger.error = logger;
16
+ logger.trace = logger;
17
+ logger.newScope = () => logger;
18
+ return logger;
19
+ }
20
+ export function createDisabledComponentLogger() {
21
+ return { forComponent: createDisabledLogger };
22
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Duplex, Source } from 'it-stream-types';
2
- import type { Stream } from '@libp2p/interface';
2
+ import { Stream } from '@libp2p/interface';
3
3
  import type { Packet } from './rpcproto.pb.js';
4
4
  export type PacketHandler = (packet: Packet) => Promise<void>;
5
5
  export type PacketStream = Duplex<AsyncGenerator<Uint8Array>, Source<Uint8Array>, Promise<void>>;
@@ -8,17 +8,9 @@ export function streamToPacketStream(stream) {
8
8
  return {
9
9
  source: pipe(stream, parseLengthPrefixTransform(), combineUint8ArrayListTransform()),
10
10
  sink: async (source) => {
11
- try {
12
- for await (const data of pipe(source, prependLengthPrefixTransform())) {
13
- stream.send(data);
14
- }
15
- await stream.close();
16
- }
17
- catch {
18
- await stream
19
- .close({ signal: AbortSignal.timeout(1000) })
20
- .catch(() => { });
21
- }
11
+ await pipe(source, prependLengthPrefixTransform(), stream)
12
+ .catch((err) => stream.close(err))
13
+ .then(() => stream.close());
22
14
  },
23
15
  };
24
16
  }
@@ -1,9 +1,9 @@
1
- import type { MessageStreamDirection } from '@libp2p/interface';
1
+ import { Direction } from '@libp2p/interface';
2
2
  import type WebSocket from '@aptre/it-ws/web-socket';
3
3
  import { StreamConn } from './conn.js';
4
4
  import { Server } from './server.js';
5
5
  export declare class WebSocketConn extends StreamConn {
6
6
  private socket;
7
- constructor(socket: WebSocket, direction: MessageStreamDirection, server?: Server);
7
+ constructor(socket: WebSocket, direction: Direction, server?: Server);
8
8
  getSocket(): WebSocket;
9
9
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starpc",
3
- "version": "0.40.1",
3
+ "version": "0.41.0",
4
4
  "description": "Streaming protobuf RPC service protocol over any two-way channel.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -85,27 +85,26 @@
85
85
  "./{srpc,echo,e2e,integration,rpcstream,cmd}/**/(*.ts|*.tsx|*.html|*.css)": "prettier --config .prettierrc.yaml --write"
86
86
  },
87
87
  "devDependencies": {
88
- "@typescript-eslint/eslint-plugin": "^8.39.1",
89
- "@typescript-eslint/parser": "^8.39.1",
88
+ "@typescript-eslint/eslint-plugin": "^8.48.0",
89
+ "@typescript-eslint/parser": "^8.48.0",
90
90
  "depcheck": "^1.4.6",
91
91
  "esbuild": "^0.27.0",
92
- "eslint": "^9.33.0",
92
+ "eslint": "^9.39.1",
93
93
  "eslint-config-prettier": "^10.0.2",
94
+ "happy-dom": "^20.0.10",
94
95
  "husky": "^9.1.7",
95
- "lint-staged": "^16.1.5",
96
+ "lint-staged": "^16.2.7",
96
97
  "prettier": "^3.5.3",
97
- "rimraf": "^6.0.1",
98
+ "rimraf": "^6.1.2",
98
99
  "tsx": "^4.20.4",
99
100
  "typescript": "^5.8.2",
100
- "vitest": "^4.0.0"
101
+ "vitest": "^4.0.14"
101
102
  },
102
103
  "dependencies": {
103
104
  "@aptre/it-ws": "^1.1.2",
104
105
  "@aptre/protobuf-es-lite": "^0.5.2",
105
- "@chainsafe/libp2p-yamux": "^8.0.0",
106
- "@libp2p/interface": "^3.0.0",
107
- "@libp2p/logger": "^6.2.2",
108
- "@libp2p/utils": "^7.0.9",
106
+ "@chainsafe/libp2p-yamux": "^7.0.1",
107
+ "@libp2p/interface": "^2.6.1",
109
108
  "event-iterator": "^2.0.0",
110
109
  "isomorphic-ws": "^5.0.0",
111
110
  "it-first": "^3.0.6",
package/srpc/conn.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { YamuxMuxerInit, yamux } from '@chainsafe/libp2p-yamux'
2
2
  import type {
3
- MessageStreamDirection,
3
+ ComponentLogger,
4
+ Direction,
4
5
  Stream,
5
6
  StreamMuxer,
6
7
  StreamMuxerFactory,
7
8
  } from '@libp2p/interface'
8
- import type { Duplex, Source } from 'it-stream-types'
9
+ import type { Duplex } from 'it-stream-types'
9
10
  import { Uint8ArrayList } from 'uint8arraylist'
10
11
 
11
12
  import {
@@ -14,20 +15,17 @@ import {
14
15
  type PacketStream,
15
16
  } from './stream.js'
16
17
  import { Client } from './client.js'
17
- import {
18
- DuplexMessageStream,
19
- createDuplexMessageStream,
20
- } from './duplex-message-stream.js'
18
+ import { createDisabledComponentLogger } from './log.js'
21
19
 
22
20
  // ConnParams are parameters that can be passed to the StreamConn constructor.
23
21
  export interface StreamConnParams {
24
- // loggerName is the debug-style logger name (e.g. 'starpc:conn').
25
- loggerName?: string
22
+ // logger is the logger to use, defaults to disabled logger.
23
+ logger?: ComponentLogger
26
24
  // muxerFactory overrides using the default yamux factory.
27
25
  muxerFactory?: StreamMuxerFactory
28
26
  // direction is the muxer connection direction.
29
27
  // defaults to outbound (client).
30
- direction?: MessageStreamDirection
28
+ direction?: Direction
31
29
  // yamuxParams are parameters to pass to yamux.
32
30
  // only used if muxerFactory is unset
33
31
  yamuxParams?: YamuxMuxerInit
@@ -50,17 +48,10 @@ export interface StreamHandler {
50
48
  // Implements the server by handling incoming streams.
51
49
  // If the server is unset, rejects any incoming streams.
52
50
  export class StreamConn
53
- implements
54
- Duplex<
55
- AsyncIterable<Uint8Array | Uint8ArrayList>,
56
- Source<Uint8Array | Uint8ArrayList>,
57
- Promise<void>
58
- >
51
+ implements Duplex<AsyncGenerator<Uint8Array | Uint8ArrayList>>
59
52
  {
60
53
  // muxer is the stream muxer.
61
54
  private _muxer: StreamMuxer
62
- // messageStream wraps the duplex as a MessageStream for the muxer.
63
- private _messageStream: DuplexMessageStream
64
55
  // server is the server side, if set.
65
56
  private _server?: StreamHandler
66
57
 
@@ -68,36 +59,25 @@ export class StreamConn
68
59
  if (server) {
69
60
  this._server = server
70
61
  }
71
-
72
- // Create the MessageStream adapter
73
- const direction = connParams?.direction || 'outbound'
74
- this._messageStream = createDuplexMessageStream({
75
- loggerName: connParams?.loggerName,
76
- direction,
77
- })
78
-
79
- // Create the muxer factory - yamux(init)() returns a StreamMuxerFactory
80
62
  const muxerFactory =
81
63
  connParams?.muxerFactory ??
82
- yamux({ enableKeepAlive: false, ...connParams?.yamuxParams })()
83
-
84
- // Create the muxer with the MessageStream
85
- this._muxer = muxerFactory.createStreamMuxer(this._messageStream)
86
-
87
- // Listen for incoming streams
88
- this._muxer.addEventListener('stream', (evt) => {
89
- this.handleIncomingStream(evt.detail)
64
+ yamux({ enableKeepAlive: false, ...connParams?.yamuxParams })({
65
+ logger: connParams?.logger ?? createDisabledComponentLogger(),
66
+ })
67
+ this._muxer = muxerFactory.createStreamMuxer({
68
+ onIncomingStream: this.handleIncomingStream.bind(this),
69
+ direction: connParams?.direction || 'outbound',
90
70
  })
91
71
  }
92
72
 
93
73
  // sink returns the message sink.
94
- get sink(): (source: Source<Uint8Array | Uint8ArrayList>) => Promise<void> {
95
- return this._messageStream.sink
74
+ get sink() {
75
+ return this._muxer.sink
96
76
  }
97
77
 
98
78
  // source returns the outgoing message source.
99
- get source(): AsyncIterable<Uint8Array | Uint8ArrayList> {
100
- return this._messageStream.source
79
+ get source() {
80
+ return this._muxer.source
101
81
  }
102
82
 
103
83
  // streams returns the set of all ongoing streams.
@@ -122,7 +102,7 @@ export class StreamConn
122
102
 
123
103
  // openStream implements the client open stream function.
124
104
  public async openStream(): Promise<PacketStream> {
125
- const strm = await this.muxer.createStream()
105
+ const strm = await this.muxer.newStream()
126
106
  return streamToPacketStream(strm)
127
107
  }
128
108
 
package/srpc/index.ts CHANGED
@@ -81,8 +81,3 @@ export {
81
81
  } from './pushable.js'
82
82
  export { Watchdog } from './watchdog.js'
83
83
  export { ProtoRpc } from './proto-rpc.js'
84
- export {
85
- DuplexMessageStream,
86
- DuplexMessageStreamInit,
87
- createDuplexMessageStream,
88
- } from './duplex-message-stream.js'
package/srpc/log.ts ADDED
@@ -0,0 +1,26 @@
1
+ import type { ComponentLogger, Logger } from '@libp2p/interface'
2
+
3
+ // https://github.com/libp2p/js-libp2p/issues/2276
4
+ // https://github.com/libp2p/js-libp2p/blob/bca8d6e689b47d85dda74082ed72e671139391de/packages/logger/src/index.ts#L86
5
+ // https://github.com/libp2p/js-libp2p/issues/2275
6
+ // https://github.com/ChainSafe/js-libp2p-yamux/issues/69
7
+ export function createDisabledLogger(namespace: string): Logger {
8
+ const logger = (): void => {}
9
+ logger.enabled = false
10
+ logger.color = ''
11
+ logger.diff = 0
12
+ logger.log = (): void => {}
13
+ logger.namespace = namespace
14
+ logger.destroy = () => true
15
+ logger.extend = () => logger
16
+ logger.debug = logger
17
+ logger.error = logger
18
+ logger.trace = logger
19
+ logger.newScope = () => logger
20
+
21
+ return logger
22
+ }
23
+
24
+ export function createDisabledComponentLogger(): ComponentLogger {
25
+ return { forComponent: createDisabledLogger }
26
+ }
package/srpc/stream.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Duplex, Source } from 'it-stream-types'
2
2
  import { pipe } from 'it-pipe'
3
- import type { Stream } from '@libp2p/interface'
3
+ import { Stream } from '@libp2p/interface'
4
4
 
5
5
  import type { Packet } from './rpcproto.pb.js'
6
6
  import { combineUint8ArrayListTransform } from './array-list.js'
@@ -38,16 +38,9 @@ export function streamToPacketStream(stream: Stream): PacketStream {
38
38
  combineUint8ArrayListTransform(),
39
39
  ),
40
40
  sink: async (source: Source<Uint8Array>): Promise<void> => {
41
- try {
42
- for await (const data of pipe(source, prependLengthPrefixTransform())) {
43
- stream.send(data)
44
- }
45
- await stream.close()
46
- } catch {
47
- await stream
48
- .close({ signal: AbortSignal.timeout(1000) })
49
- .catch(() => {})
50
- }
41
+ await pipe(source, prependLengthPrefixTransform(), stream)
42
+ .catch((err) => stream.close(err))
43
+ .then(() => stream.close())
51
44
  },
52
45
  }
53
46
  }
package/srpc/websocket.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { pipe } from 'it-pipe'
2
- import type { MessageStreamDirection } from '@libp2p/interface'
2
+ import { Direction } from '@libp2p/interface'
3
3
 
4
4
  import duplex from '@aptre/it-ws/duplex'
5
5
  import type WebSocket from '@aptre/it-ws/web-socket'
@@ -13,11 +13,7 @@ export class WebSocketConn extends StreamConn {
13
13
  // socket is the web socket
14
14
  private socket: WebSocket
15
15
 
16
- constructor(
17
- socket: WebSocket,
18
- direction: MessageStreamDirection,
19
- server?: Server,
20
- ) {
16
+ constructor(socket: WebSocket, direction: Direction, server?: Server) {
21
17
  super(server, { direction })
22
18
  this.socket = socket
23
19
  const socketDuplex = duplex(socket)
@@ -1,23 +0,0 @@
1
- import type { AbortOptions, MessageStreamDirection } from '@libp2p/interface';
2
- import { AbstractMessageStream, type SendResult } from '@libp2p/utils';
3
- import type { Duplex, Source } from 'it-stream-types';
4
- import { Uint8ArrayList } from 'uint8arraylist';
5
- export interface DuplexMessageStreamInit {
6
- direction?: MessageStreamDirection;
7
- loggerName?: string;
8
- inactivityTimeout?: number;
9
- maxReadBufferLength?: number;
10
- }
11
- export declare class DuplexMessageStream extends AbstractMessageStream {
12
- private readonly _outgoing;
13
- private readonly _sink;
14
- constructor(init?: DuplexMessageStreamInit);
15
- get source(): AsyncIterable<Uint8Array | Uint8ArrayList>;
16
- get sink(): (source: Source<Uint8Array | Uint8ArrayList>) => Promise<void>;
17
- sendData(data: Uint8ArrayList): SendResult;
18
- sendReset(_err: Error): void;
19
- sendPause(): void;
20
- sendResume(): void;
21
- close(_options?: AbortOptions): Promise<void>;
22
- }
23
- export declare function createDuplexMessageStream(init?: DuplexMessageStreamInit): DuplexMessageStream & Duplex<AsyncIterable<Uint8Array | Uint8ArrayList>>;
@@ -1,98 +0,0 @@
1
- import { logger } from '@libp2p/logger';
2
- import { AbstractMessageStream, } from '@libp2p/utils';
3
- import { pushable } from 'it-pushable';
4
- // DuplexMessageStream wraps a Duplex stream as a MessageStream.
5
- // This allows using duplex streams with the new libp2p StreamMuxer API.
6
- //
7
- // Extends AbstractMessageStream to get proper read/write buffer management,
8
- // backpressure handling, and event semantics from libp2p.
9
- export class DuplexMessageStream extends AbstractMessageStream {
10
- // _outgoing is a pushable that collects data to be sent out.
11
- _outgoing;
12
- // _sink is the bound sink function
13
- _sink;
14
- constructor(init) {
15
- // Create the MessageStreamInit required by AbstractMessageStream
16
- const streamInit = {
17
- log: logger(init?.loggerName ?? 'starpc:duplex-message-stream'),
18
- direction: init?.direction ?? 'outbound',
19
- inactivityTimeout: init?.inactivityTimeout,
20
- maxReadBufferLength: init?.maxReadBufferLength,
21
- };
22
- super(streamInit);
23
- this._outgoing = pushable();
24
- this._sink = async (source) => {
25
- try {
26
- for await (const data of source) {
27
- if (this.status === 'closed' ||
28
- this.status === 'aborted' ||
29
- this.status === 'reset') {
30
- break;
31
- }
32
- // Use the parent's onData method which handles buffering and events
33
- this.onData(data);
34
- }
35
- // Remote closed their write side
36
- this.onRemoteCloseWrite();
37
- }
38
- catch (err) {
39
- this.abort(err);
40
- }
41
- };
42
- }
43
- // source returns an async iterable that yields data to be sent to the remote.
44
- get source() {
45
- return this._outgoing;
46
- }
47
- // sink consumes data from the remote and feeds it into the stream.
48
- // This is the receiving end of the duplex.
49
- get sink() {
50
- return this._sink;
51
- }
52
- // sendData implements AbstractMessageStream.sendData
53
- // Called by the parent class when processing the write queue.
54
- sendData(data) {
55
- // Push data to the outgoing pushable
56
- this._outgoing.push(data);
57
- return {
58
- sentBytes: data.byteLength,
59
- canSendMore: true, // Our pushable can always accept more
60
- };
61
- }
62
- // sendReset implements AbstractMessageStream.sendReset
63
- // Called when the stream is aborted locally.
64
- sendReset(_err) {
65
- // End the outgoing pushable - we can't send a reset over a generic duplex
66
- this._outgoing.end();
67
- }
68
- // sendPause implements AbstractMessageStream.sendPause
69
- // Called when the stream is paused.
70
- sendPause() {
71
- // No-op: generic duplex streams don't support pause signaling
72
- this.log.trace('pause requested (no-op for duplex stream)');
73
- }
74
- // sendResume implements AbstractMessageStream.sendResume
75
- // Called when the stream is resumed.
76
- sendResume() {
77
- // No-op: generic duplex streams don't support resume signaling
78
- this.log.trace('resume requested (no-op for duplex stream)');
79
- }
80
- // close gracefully closes the stream.
81
- async close(_options) {
82
- if (this.status === 'closed' || this.status === 'closing') {
83
- return;
84
- }
85
- this.status = 'closing';
86
- this.writeStatus = 'closing';
87
- // End the outgoing pushable to signal we're done writing
88
- this._outgoing.end();
89
- this.writeStatus = 'closed';
90
- if (this.readStatus === 'closed') {
91
- this.onTransportClosed();
92
- }
93
- }
94
- }
95
- // createDuplexMessageStream creates a new DuplexMessageStream.
96
- export function createDuplexMessageStream(init) {
97
- return new DuplexMessageStream(init);
98
- }
@@ -1,137 +0,0 @@
1
- import type { AbortOptions, MessageStreamDirection } from '@libp2p/interface'
2
- import { logger } from '@libp2p/logger'
3
- import {
4
- AbstractMessageStream,
5
- type MessageStreamInit,
6
- type SendResult,
7
- } from '@libp2p/utils'
8
- import type { Duplex, Source } from 'it-stream-types'
9
- import { pushable, type Pushable } from 'it-pushable'
10
- import { Uint8ArrayList } from 'uint8arraylist'
11
-
12
- // DuplexMessageStreamInit are parameters for DuplexMessageStream.
13
- export interface DuplexMessageStreamInit {
14
- // direction is the stream direction.
15
- direction?: MessageStreamDirection
16
- // loggerName is the name to use for the logger.
17
- loggerName?: string
18
- // inactivityTimeout is the inactivity timeout in ms.
19
- inactivityTimeout?: number
20
- // maxReadBufferLength is the max read buffer length.
21
- maxReadBufferLength?: number
22
- }
23
-
24
- // DuplexMessageStream wraps a Duplex stream as a MessageStream.
25
- // This allows using duplex streams with the new libp2p StreamMuxer API.
26
- //
27
- // Extends AbstractMessageStream to get proper read/write buffer management,
28
- // backpressure handling, and event semantics from libp2p.
29
- export class DuplexMessageStream extends AbstractMessageStream {
30
- // _outgoing is a pushable that collects data to be sent out.
31
- private readonly _outgoing: Pushable<Uint8Array | Uint8ArrayList>
32
- // _sink is the bound sink function
33
- private readonly _sink: (
34
- source: Source<Uint8Array | Uint8ArrayList>,
35
- ) => Promise<void>
36
-
37
- constructor(init?: DuplexMessageStreamInit) {
38
- // Create the MessageStreamInit required by AbstractMessageStream
39
- const streamInit: MessageStreamInit = {
40
- log: logger(init?.loggerName ?? 'starpc:duplex-message-stream'),
41
- direction: init?.direction ?? 'outbound',
42
- inactivityTimeout: init?.inactivityTimeout,
43
- maxReadBufferLength: init?.maxReadBufferLength,
44
- }
45
- super(streamInit)
46
- this._outgoing = pushable<Uint8Array | Uint8ArrayList>()
47
- this._sink = async (
48
- source: Source<Uint8Array | Uint8ArrayList>,
49
- ): Promise<void> => {
50
- try {
51
- for await (const data of source) {
52
- if (
53
- this.status === 'closed' ||
54
- this.status === 'aborted' ||
55
- this.status === 'reset'
56
- ) {
57
- break
58
- }
59
- // Use the parent's onData method which handles buffering and events
60
- this.onData(data)
61
- }
62
- // Remote closed their write side
63
- this.onRemoteCloseWrite()
64
- } catch (err) {
65
- this.abort(err as Error)
66
- }
67
- }
68
- }
69
-
70
- // source returns an async iterable that yields data to be sent to the remote.
71
- get source(): AsyncIterable<Uint8Array | Uint8ArrayList> {
72
- return this._outgoing
73
- }
74
-
75
- // sink consumes data from the remote and feeds it into the stream.
76
- // This is the receiving end of the duplex.
77
- get sink(): (source: Source<Uint8Array | Uint8ArrayList>) => Promise<void> {
78
- return this._sink
79
- }
80
-
81
- // sendData implements AbstractMessageStream.sendData
82
- // Called by the parent class when processing the write queue.
83
- sendData(data: Uint8ArrayList): SendResult {
84
- // Push data to the outgoing pushable
85
- this._outgoing.push(data)
86
- return {
87
- sentBytes: data.byteLength,
88
- canSendMore: true, // Our pushable can always accept more
89
- }
90
- }
91
-
92
- // sendReset implements AbstractMessageStream.sendReset
93
- // Called when the stream is aborted locally.
94
- sendReset(_err: Error): void {
95
- // End the outgoing pushable - we can't send a reset over a generic duplex
96
- this._outgoing.end()
97
- }
98
-
99
- // sendPause implements AbstractMessageStream.sendPause
100
- // Called when the stream is paused.
101
- sendPause(): void {
102
- // No-op: generic duplex streams don't support pause signaling
103
- this.log.trace('pause requested (no-op for duplex stream)')
104
- }
105
-
106
- // sendResume implements AbstractMessageStream.sendResume
107
- // Called when the stream is resumed.
108
- sendResume(): void {
109
- // No-op: generic duplex streams don't support resume signaling
110
- this.log.trace('resume requested (no-op for duplex stream)')
111
- }
112
-
113
- // close gracefully closes the stream.
114
- async close(_options?: AbortOptions): Promise<void> {
115
- if (this.status === 'closed' || this.status === 'closing') {
116
- return
117
- }
118
- this.status = 'closing'
119
- this.writeStatus = 'closing'
120
-
121
- // End the outgoing pushable to signal we're done writing
122
- this._outgoing.end()
123
-
124
- this.writeStatus = 'closed'
125
- if (this.readStatus === 'closed') {
126
- this.onTransportClosed()
127
- }
128
- }
129
- }
130
-
131
- // createDuplexMessageStream creates a new DuplexMessageStream.
132
- export function createDuplexMessageStream(
133
- init?: DuplexMessageStreamInit,
134
- ): DuplexMessageStream & Duplex<AsyncIterable<Uint8Array | Uint8ArrayList>> {
135
- return new DuplexMessageStream(init) as DuplexMessageStream &
136
- Duplex<AsyncIterable<Uint8Array | Uint8ArrayList>>
137
- }