@olane/o-client-limited 0.7.51 → 0.7.52

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 (49) hide show
  1. package/dist/src/connection/o-limited-connection.d.ts +12 -21
  2. package/dist/src/connection/o-limited-connection.d.ts.map +1 -1
  3. package/dist/src/connection/o-limited-connection.js +31 -65
  4. package/dist/src/connection/o-limited.stream-manager.d.ts +79 -0
  5. package/dist/src/connection/o-limited.stream-manager.d.ts.map +1 -0
  6. package/dist/src/connection/o-limited.stream-manager.js +234 -0
  7. package/dist/test/bidirectional-communication.spec.d.ts +2 -0
  8. package/dist/test/bidirectional-communication.spec.d.ts.map +1 -0
  9. package/dist/test/bidirectional-communication.spec.js +265 -0
  10. package/dist/test/helpers/index.d.ts +2 -3
  11. package/dist/test/helpers/index.d.ts.map +1 -1
  12. package/dist/test/helpers/index.js +2 -3
  13. package/dist/test/helpers/limited-test-tool.d.ts +41 -0
  14. package/dist/test/helpers/limited-test-tool.d.ts.map +1 -0
  15. package/dist/test/helpers/limited-test-tool.js +98 -0
  16. package/dist/test/helpers/receiver-test-tool.d.ts +34 -0
  17. package/dist/test/helpers/receiver-test-tool.d.ts.map +1 -0
  18. package/dist/test/helpers/receiver-test-tool.js +67 -0
  19. package/dist/test/limited-connection-lifecycle.spec.d.ts +2 -0
  20. package/dist/test/limited-connection-lifecycle.spec.d.ts.map +1 -0
  21. package/dist/test/limited-connection-lifecycle.spec.js +209 -0
  22. package/dist/test/limited-stream-manager.spec.d.ts +2 -0
  23. package/dist/test/limited-stream-manager.spec.d.ts.map +1 -0
  24. package/dist/test/limited-stream-manager.spec.js +222 -0
  25. package/dist/test/reader-stream-recovery.spec.d.ts +2 -0
  26. package/dist/test/reader-stream-recovery.spec.d.ts.map +1 -0
  27. package/dist/test/reader-stream-recovery.spec.js +188 -0
  28. package/package.json +8 -8
  29. package/dist/test/configuration.spec.d.ts +0 -1
  30. package/dist/test/configuration.spec.d.ts.map +0 -1
  31. package/dist/test/configuration.spec.js +0 -335
  32. package/dist/test/error-handling.spec.d.ts +0 -2
  33. package/dist/test/error-handling.spec.d.ts.map +0 -1
  34. package/dist/test/error-handling.spec.js +0 -378
  35. package/dist/test/helpers/mock-p2p-connection.d.ts +0 -38
  36. package/dist/test/helpers/mock-p2p-connection.d.ts.map +0 -1
  37. package/dist/test/helpers/mock-p2p-connection.js +0 -66
  38. package/dist/test/helpers/mock-stream-handler.d.ts +0 -43
  39. package/dist/test/helpers/mock-stream-handler.d.ts.map +0 -1
  40. package/dist/test/helpers/mock-stream-handler.js +0 -71
  41. package/dist/test/helpers/mock-stream.d.ts +0 -46
  42. package/dist/test/helpers/mock-stream.d.ts.map +0 -1
  43. package/dist/test/helpers/mock-stream.js +0 -59
  44. package/dist/test/method.spec.d.ts +0 -1
  45. package/dist/test/method.spec.d.ts.map +0 -1
  46. package/dist/test/method.spec.js +0 -29
  47. package/dist/test/stream-reuse.spec.d.ts +0 -1
  48. package/dist/test/stream-reuse.spec.d.ts.map +0 -1
  49. package/dist/test/stream-reuse.spec.js +0 -267
@@ -1,40 +1,31 @@
1
1
  import { oNodeConnection } from '@olane/o-node';
2
2
  import type { oNodeConnectionConfig } from '@olane/o-node';
3
+ import { oLimitedStreamManager } from './o-limited.stream-manager.js';
3
4
  /**
4
- * oLimitedConnection extends oNodeConnection with stream reuse and pool management.
5
+ * oLimitedConnection extends oNodeConnection with stream reuse for limited connections.
5
6
  *
6
7
  * This is optimized for limited connections where creating new streams is expensive
7
8
  * (mobile clients, browsers, resource-constrained environments).
8
9
  *
9
- * Stream Pool Architecture (10 streams total):
10
- * - Stream 0: Dedicated background reader for incoming requests
11
- * - Streams 1-9: Round-robin pool for outgoing request-response cycles
10
+ * Stream Architecture:
11
+ * - 1 dedicated reader stream for receiving requests from receiver
12
+ * - Reuses outbound streams for multiple request-response cycles
12
13
  *
13
14
  * Features:
14
- * - Automatic recovery when dedicated reader fails
15
- * - Health monitoring of all pooled streams
16
- * - Automatic stream replacement on failure
17
- * - Event emission for monitoring (reader-failed, stream-replaced, etc.)
15
+ * - Automatic reader stream creation and maintenance
16
+ * - Single retry on reader failure
17
+ * - Stream reuse for outbound requests
18
+ * - Event emission for monitoring (reader-started, reader-failed, reader-recovered)
18
19
  *
19
20
  * Default Behavior:
20
21
  * - Uses 'reuse' stream policy by default
21
- * - Automatically initializes pool manager on first stream request
22
+ * - Automatically initializes dedicated reader on connection start
22
23
  */
23
24
  export declare class oLimitedConnection extends oNodeConnection {
24
- private streamPoolManager?;
25
- private poolInitialized;
25
+ streamManager: oLimitedStreamManager;
26
26
  constructor(config: oNodeConnectionConfig);
27
27
  /**
28
- * Initialize the stream pool manager
29
- */
30
- private initializePoolManager;
31
- getOrCreateStream(): Promise<any>;
32
- /**
33
- * Get stream pool statistics
34
- */
35
- getPoolStats(): import("@olane/o-node").StreamPoolStats | undefined;
36
- /**
37
- * Override close to cleanup pool manager
28
+ * Override close to cleanup stream manager properly
38
29
  */
39
30
  close(): Promise<void>;
40
31
  }
@@ -1 +1 @@
1
- {"version":3,"file":"o-limited-connection.d.ts","sourceRoot":"","sources":["../../../src/connection/o-limited-connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAqB,MAAM,eAAe,CAAC;AACnE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAE3D;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,kBAAmB,SAAQ,eAAe;IACrD,OAAO,CAAC,iBAAiB,CAAC,CAAoB;IAC9C,OAAO,CAAC,eAAe,CAAS;gBAEpB,MAAM,EAAE,qBAAqB;IASzC;;OAEG;YACW,qBAAqB;IAqC7B,iBAAiB,IAAI,OAAO,CAAC,GAAG,CAAC;IAevC;;OAEG;IACH,YAAY;IAIZ;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAY7B"}
1
+ {"version":3,"file":"o-limited-connection.d.ts","sourceRoot":"","sources":["../../../src/connection/o-limited-connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAC3D,OAAO,EACL,qBAAqB,EAEtB,MAAM,+BAA+B,CAAC;AAGvC;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,kBAAmB,SAAQ,eAAe;IAC7C,aAAa,EAAE,qBAAqB,CAAC;gBAEjC,MAAM,EAAE,qBAAqB;IAmCzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAK7B"}
@@ -1,94 +1,60 @@
1
- import { oNodeConnection, StreamPoolManager } from '@olane/o-node';
1
+ import { oNodeConnection } from '@olane/o-node';
2
+ import { oLimitedStreamManager, } from './o-limited.stream-manager.js';
3
+ import { StreamManagerEvent } from '@olane/o-node';
2
4
  /**
3
- * oLimitedConnection extends oNodeConnection with stream reuse and pool management.
5
+ * oLimitedConnection extends oNodeConnection with stream reuse for limited connections.
4
6
  *
5
7
  * This is optimized for limited connections where creating new streams is expensive
6
8
  * (mobile clients, browsers, resource-constrained environments).
7
9
  *
8
- * Stream Pool Architecture (10 streams total):
9
- * - Stream 0: Dedicated background reader for incoming requests
10
- * - Streams 1-9: Round-robin pool for outgoing request-response cycles
10
+ * Stream Architecture:
11
+ * - 1 dedicated reader stream for receiving requests from receiver
12
+ * - Reuses outbound streams for multiple request-response cycles
11
13
  *
12
14
  * Features:
13
- * - Automatic recovery when dedicated reader fails
14
- * - Health monitoring of all pooled streams
15
- * - Automatic stream replacement on failure
16
- * - Event emission for monitoring (reader-failed, stream-replaced, etc.)
15
+ * - Automatic reader stream creation and maintenance
16
+ * - Single retry on reader failure
17
+ * - Stream reuse for outbound requests
18
+ * - Event emission for monitoring (reader-started, reader-failed, reader-recovered)
17
19
  *
18
20
  * Default Behavior:
19
21
  * - Uses 'reuse' stream policy by default
20
- * - Automatically initializes pool manager on first stream request
22
+ * - Automatically initializes dedicated reader on connection start
21
23
  */
22
24
  export class oLimitedConnection extends oNodeConnection {
23
25
  constructor(config) {
24
26
  const reusePolicy = config.reusePolicy ?? 'reuse';
25
27
  super({
26
28
  ...config,
27
- reusePolicy: reusePolicy,
29
+ reusePolicy,
28
30
  });
29
- this.poolInitialized = false;
30
- this.reusePolicy = reusePolicy;
31
- }
32
- /**
33
- * Initialize the stream pool manager
34
- */
35
- async initializePoolManager() {
36
- if (this.poolInitialized || this.streamPoolManager) {
37
- return;
38
- }
39
- this.logger.debug('Initializing stream pool manager');
40
- this.streamPoolManager = new StreamPoolManager({
41
- poolSize: 10,
42
- readerStreamIndex: 0,
43
- streamHandler: this.streamHandler,
31
+ // Replace the base streamManager with our limited version
32
+ const protocol = this.nextHopAddress.protocol +
33
+ (reusePolicy === 'reuse' ? '/reuse' : '');
34
+ const limitedConfig = {
44
35
  p2pConnection: this.p2pConnection,
45
- requestHandler: this.config.requestHandler,
46
- createStream: async () => {
47
- return await super.getOrCreateStream();
48
- },
49
- });
36
+ protocol,
37
+ remoteAddress: this.nextHopAddress,
38
+ requestHandler: config.requestHandler,
39
+ };
40
+ this.streamManager = new oLimitedStreamManager(limitedConfig);
50
41
  // Set up event listeners for monitoring
51
- this.streamPoolManager.on('reader-failed', (data) => {
52
- this.logger.warn('Stream pool reader failed', data);
42
+ this.streamManager.on(StreamManagerEvent.ReaderStarted, (data) => {
43
+ this.logger.info('Reader stream started', data);
53
44
  });
54
- this.streamPoolManager.on('reader-recovered', (data) => {
55
- this.logger.info('Stream pool reader recovered', data);
45
+ this.streamManager.on(StreamManagerEvent.ReaderFailed, (data) => {
46
+ this.logger.warn('Reader stream failed', data);
56
47
  });
57
- this.streamPoolManager.on('stream-replaced', (data) => {
58
- this.logger.info('Stream replaced in pool', data);
48
+ this.streamManager.on(StreamManagerEvent.ReaderRecovered, (data) => {
49
+ this.logger.info('Reader stream recovered', data);
59
50
  });
60
- await this.streamPoolManager.initialize();
61
- this.poolInitialized = true;
62
- this.logger.info('Stream pool manager initialized successfully');
63
- }
64
- async getOrCreateStream() {
65
- if (this.reusePolicy === 'reuse') {
66
- // Initialize pool manager on first call
67
- if (!this.poolInitialized) {
68
- await this.initializePoolManager();
69
- }
70
- // Delegate to pool manager for stream selection
71
- return await this.streamPoolManager.getStream();
72
- }
73
- // Fallback to default behavior if reuse is not enabled
74
- return super.getOrCreateStream();
75
- }
76
- /**
77
- * Get stream pool statistics
78
- */
79
- getPoolStats() {
80
- return this.streamPoolManager?.getStats();
81
51
  }
82
52
  /**
83
- * Override close to cleanup pool manager
53
+ * Override close to cleanup stream manager properly
84
54
  */
85
55
  async close() {
86
- this.logger.debug('Closing connection and stream pool manager');
87
- if (this.streamPoolManager) {
88
- await this.streamPoolManager.close();
89
- this.streamPoolManager = undefined;
90
- }
91
- this.poolInitialized = false;
56
+ this.logger.debug('Closing limited connection');
57
+ await this.streamManager.close();
92
58
  await super.close();
93
59
  }
94
60
  }
@@ -0,0 +1,79 @@
1
+ import type { Stream } from '@libp2p/interface';
2
+ import { oNodeStreamManager, oNodeStream, StreamManagerConfig } from '@olane/o-node';
3
+ import type { StreamHandlerConfig } from '@olane/o-node';
4
+ /**
5
+ * Extended configuration for limited stream manager
6
+ */
7
+ export interface oLimitedStreamManagerConfig extends StreamManagerConfig {
8
+ /**
9
+ * Protocol string for creating streams
10
+ */
11
+ protocol: string;
12
+ /**
13
+ * Remote address for the connection
14
+ */
15
+ remoteAddress: any;
16
+ /**
17
+ * Optional request handler for bidirectional communication
18
+ */
19
+ requestHandler?: (request: any, stream: Stream) => Promise<any>;
20
+ }
21
+ /**
22
+ * Limited Stream Manager handles stream lifecycle for limited connections
23
+ * Features:
24
+ * - Maintains dedicated reader stream for receiving requests from receiver
25
+ * - Reuses outbound streams (no close after use)
26
+ * - Single retry on reader failure
27
+ * - No health checks (error handling on use)
28
+ */
29
+ export declare class oLimitedStreamManager extends oNodeStreamManager {
30
+ private readerStream?;
31
+ private isReaderLoopActive;
32
+ private readerLoopAbortController?;
33
+ private outboundStream?;
34
+ private limitedConfig;
35
+ private closing;
36
+ constructor(config: oLimitedStreamManagerConfig);
37
+ /**
38
+ * Initialize the limited stream manager
39
+ * Creates dedicated reader stream and starts background read loop
40
+ */
41
+ initialize(): Promise<void>;
42
+ /**
43
+ * Creates and initializes the dedicated reader stream
44
+ */
45
+ private createReaderStream;
46
+ /**
47
+ * Sends stream initialization message to identify this as a reader stream
48
+ */
49
+ private sendStreamInitMessage;
50
+ /**
51
+ * Starts the background reader loop
52
+ * Continuously listens for incoming requests on the reader stream
53
+ */
54
+ private startReaderLoop;
55
+ /**
56
+ * Background reader loop implementation
57
+ */
58
+ private runReaderLoop;
59
+ /**
60
+ * Attempts to recover the reader stream (single retry)
61
+ */
62
+ private recoverReaderStream;
63
+ /**
64
+ * Override getOrCreateStream to reuse outbound streams
65
+ * Does not create new stream for every request
66
+ * Auto-initializes on first use
67
+ */
68
+ getOrCreateStream(protocol: string, remoteAddress: any, config?: StreamHandlerConfig): Promise<oNodeStream>;
69
+ /**
70
+ * Override releaseStream to NOT close the stream
71
+ * Keep streams open for reuse
72
+ */
73
+ releaseStream(streamId: string): Promise<void>;
74
+ /**
75
+ * Close the stream manager and cleanup all resources
76
+ */
77
+ close(): Promise<void>;
78
+ }
79
+ //# sourceMappingURL=o-limited.stream-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"o-limited.stream-manager.d.ts","sourceRoot":"","sources":["../../../src/connection/o-limited.stream-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EACL,kBAAkB,EAElB,WAAW,EACX,mBAAmB,EAGpB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEzD;;GAEG;AACH,MAAM,WAAW,2BAA4B,SAAQ,mBAAmB;IACtE;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,aAAa,EAAE,GAAG,CAAC;IAEnB;;OAEG;IACH,cAAc,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;CACjE;AAED;;;;;;;GAOG;AACH,qBAAa,qBAAsB,SAAQ,kBAAkB;IAC3D,OAAO,CAAC,YAAY,CAAC,CAAc;IACnC,OAAO,CAAC,kBAAkB,CAAkB;IAC5C,OAAO,CAAC,yBAAyB,CAAC,CAAkB;IACpD,OAAO,CAAC,cAAc,CAAC,CAAc;IACrC,OAAO,CAAC,aAAa,CAA8B;IACnD,OAAO,CAAC,OAAO,CAAkB;gBAErB,MAAM,EAAE,2BAA2B;IAK/C;;;OAGG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAqDjC;;OAEG;YACW,kBAAkB;IA4BhC;;OAEG;YACW,qBAAqB;IAiBnC;;;OAGG;YACW,eAAe;IAe7B;;OAEG;YACW,aAAa;IAwB3B;;OAEG;YACW,mBAAmB;IAgCjC;;;;OAIG;IACG,iBAAiB,CACrB,QAAQ,EAAE,MAAM,EAChB,aAAa,EAAE,GAAG,EAClB,MAAM,GAAE,mBAAwB,GAC/B,OAAO,CAAC,WAAW,CAAC;IA6BvB;;;OAGG;IACG,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAMpD;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;CAqC7B"}
@@ -0,0 +1,234 @@
1
+ import { oError, oErrorCodes } from '@olane/o-core';
2
+ import { oNodeStreamManager, StreamManagerEvent, } from '@olane/o-node';
3
+ /**
4
+ * Limited Stream Manager handles stream lifecycle for limited connections
5
+ * Features:
6
+ * - Maintains dedicated reader stream for receiving requests from receiver
7
+ * - Reuses outbound streams (no close after use)
8
+ * - Single retry on reader failure
9
+ * - No health checks (error handling on use)
10
+ */
11
+ export class oLimitedStreamManager extends oNodeStreamManager {
12
+ constructor(config) {
13
+ super(config);
14
+ this.isReaderLoopActive = false;
15
+ this.closing = false;
16
+ this.limitedConfig = config;
17
+ }
18
+ /**
19
+ * Initialize the limited stream manager
20
+ * Creates dedicated reader stream and starts background read loop
21
+ */
22
+ async initialize() {
23
+ if (this.isInitialized) {
24
+ return;
25
+ }
26
+ await super.initialize();
27
+ // Register InboundRequest listener if requestHandler provided
28
+ // This enables bidirectional communication - receiver can send requests to caller via reader stream
29
+ if (this.limitedConfig.requestHandler) {
30
+ this.eventEmitter.on(StreamManagerEvent.InboundRequest, async (data) => {
31
+ try {
32
+ const result = await this.limitedConfig.requestHandler(data.request, data.stream);
33
+ return result;
34
+ }
35
+ catch (error) {
36
+ this.logger.error('Error in requestHandler for inbound request:', data.request.toString(), error);
37
+ throw error; // StreamManager will handle error response
38
+ }
39
+ });
40
+ this.logger.debug('Registered InboundRequest handler for limited connection');
41
+ }
42
+ try {
43
+ // Create dedicated reader stream
44
+ await this.createReaderStream();
45
+ this.isInitialized = true;
46
+ this.logger.info('Limited stream manager initialized', {
47
+ remotePeer: this.limitedConfig.p2pConnection.remotePeer.toString(),
48
+ });
49
+ }
50
+ catch (error) {
51
+ this.logger.error('Failed to initialize limited stream manager:', error);
52
+ throw new oError(oErrorCodes.INTERNAL_ERROR, `Failed to initialize limited stream manager: ${error.message}`);
53
+ }
54
+ }
55
+ /**
56
+ * Creates and initializes the dedicated reader stream
57
+ */
58
+ async createReaderStream() {
59
+ try {
60
+ // Create reader stream using parent's createStream method
61
+ this.readerStream = await this.createStream(this.limitedConfig.protocol, this.limitedConfig.remoteAddress, {});
62
+ // Send self-identification message
63
+ await this.sendStreamInitMessage(this.readerStream.p2pStream);
64
+ // Start background reader loop
65
+ await this.startReaderLoop();
66
+ this.eventEmitter.emit(StreamManagerEvent.ReaderStarted, {
67
+ streamId: this.readerStream.p2pStream.id,
68
+ });
69
+ this.logger.info('Reader stream created and started', {
70
+ streamId: this.readerStream.p2pStream.id,
71
+ });
72
+ }
73
+ catch (error) {
74
+ this.logger.error('Failed to create reader stream:', error);
75
+ throw error;
76
+ }
77
+ }
78
+ /**
79
+ * Sends stream initialization message to identify this as a reader stream
80
+ */
81
+ async sendStreamInitMessage(stream) {
82
+ const initMessage = {
83
+ type: 'stream-init',
84
+ role: 'reader',
85
+ timestamp: Date.now(),
86
+ connectionId: this.limitedConfig.p2pConnection.id,
87
+ };
88
+ const messageBytes = new TextEncoder().encode(JSON.stringify(initMessage));
89
+ await this.sendLengthPrefixed(stream, messageBytes, {});
90
+ this.logger.debug('Sent stream-init message', {
91
+ streamId: stream.id,
92
+ role: 'reader',
93
+ });
94
+ }
95
+ /**
96
+ * Starts the background reader loop
97
+ * Continuously listens for incoming requests on the reader stream
98
+ */
99
+ async startReaderLoop() {
100
+ if (!this.readerStream || this.isReaderLoopActive) {
101
+ return;
102
+ }
103
+ this.isReaderLoopActive = true;
104
+ this.readerLoopAbortController = new AbortController();
105
+ // Start background task (don't await)
106
+ this.runReaderLoop().catch((error) => {
107
+ this.logger.error('Reader loop failed:', error);
108
+ this.isReaderLoopActive = false;
109
+ });
110
+ }
111
+ /**
112
+ * Background reader loop implementation
113
+ */
114
+ async runReaderLoop() {
115
+ if (!this.readerStream) {
116
+ return;
117
+ }
118
+ const stream = this.readerStream.p2pStream;
119
+ try {
120
+ // Continuous read loop using parent's handleIncomingStream
121
+ // This will process all incoming requests on the reader stream
122
+ await this.handleIncomingStream(stream, this.limitedConfig.p2pConnection);
123
+ }
124
+ catch (error) {
125
+ if (!this.closing) {
126
+ this.logger.error('Reader loop error, attempting recovery:', error);
127
+ await this.recoverReaderStream();
128
+ }
129
+ }
130
+ finally {
131
+ this.isReaderLoopActive = false;
132
+ }
133
+ }
134
+ /**
135
+ * Attempts to recover the reader stream (single retry)
136
+ */
137
+ async recoverReaderStream() {
138
+ try {
139
+ this.logger.info('Attempting to recover reader stream...');
140
+ // Close old stream if it exists
141
+ if (this.readerStream) {
142
+ try {
143
+ await this.readerStream.p2pStream.close();
144
+ }
145
+ catch (e) {
146
+ // Ignore close errors
147
+ }
148
+ this.readerStream = undefined;
149
+ }
150
+ // Try to recreate
151
+ await this.createReaderStream();
152
+ this.eventEmitter.emit(StreamManagerEvent.ReaderRecovered, {
153
+ failureCount: 1,
154
+ });
155
+ this.logger.info('Reader stream recovered successfully');
156
+ }
157
+ catch (error) {
158
+ this.logger.error('Reader stream recovery failed:', error);
159
+ this.eventEmitter.emit(StreamManagerEvent.ReaderFailed, {
160
+ error: error.message,
161
+ failureCount: 1,
162
+ });
163
+ }
164
+ }
165
+ /**
166
+ * Override getOrCreateStream to reuse outbound streams
167
+ * Does not create new stream for every request
168
+ * Auto-initializes on first use
169
+ */
170
+ async getOrCreateStream(protocol, remoteAddress, config = {}) {
171
+ // Auto-initialize on first use
172
+ if (!this.isInitialized) {
173
+ await this.initialize();
174
+ }
175
+ // Check if we have an existing outbound stream that's still valid
176
+ if (this.outboundStream &&
177
+ this.outboundStream.p2pStream.status === 'open' &&
178
+ this.outboundStream.p2pStream.writeStatus === 'writable') {
179
+ this.logger.debug('Reusing existing outbound stream', {
180
+ streamId: this.outboundStream.p2pStream.id,
181
+ });
182
+ return this.outboundStream;
183
+ }
184
+ // Create new outbound stream if none exists or current is invalid
185
+ this.logger.debug('Creating new outbound stream (no valid stream to reuse)');
186
+ this.outboundStream = await this.createStream(protocol, remoteAddress, config);
187
+ return this.outboundStream;
188
+ }
189
+ /**
190
+ * Override releaseStream to NOT close the stream
191
+ * Keep streams open for reuse
192
+ */
193
+ async releaseStream(streamId) {
194
+ // Don't close the stream - just log that we're keeping it open
195
+ this.logger.debug('Keeping stream open for reuse', { streamId });
196
+ // Do NOT call super.releaseStream() as that would close the stream
197
+ }
198
+ /**
199
+ * Close the stream manager and cleanup all resources
200
+ */
201
+ async close() {
202
+ if (this.closing) {
203
+ return;
204
+ }
205
+ this.closing = true;
206
+ this.logger.info('Closing limited stream manager');
207
+ // Stop reader loop
208
+ if (this.readerLoopAbortController) {
209
+ this.readerLoopAbortController.abort();
210
+ }
211
+ this.isReaderLoopActive = false;
212
+ // Close reader stream
213
+ if (this.readerStream) {
214
+ try {
215
+ await this.readerStream.p2pStream.close();
216
+ }
217
+ catch (error) {
218
+ this.logger.warn('Error closing reader stream:', error);
219
+ }
220
+ this.readerStream = undefined;
221
+ }
222
+ // Close outbound stream
223
+ if (this.outboundStream) {
224
+ try {
225
+ await this.outboundStream.p2pStream.close();
226
+ }
227
+ catch (error) {
228
+ this.logger.warn('Error closing outbound stream:', error);
229
+ }
230
+ this.outboundStream = undefined;
231
+ }
232
+ this.eventEmitter.emit(StreamManagerEvent.ManagerClosed, undefined);
233
+ }
234
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=bidirectional-communication.spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bidirectional-communication.spec.d.ts","sourceRoot":"","sources":["../../test/bidirectional-communication.spec.ts"],"names":[],"mappings":""}