@waku/core 0.0.29 → 0.0.30-16e9116.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,17 +1,20 @@
1
- import type { Peer } from "@libp2p/interface";
1
+ import type { Peer, Stream } from "@libp2p/interface";
2
2
  import type { IncomingStreamData } from "@libp2p/interface-internal";
3
- import type {
4
- ContentTopic,
5
- IBaseProtocolCore,
6
- Libp2p,
7
- ProtocolCreateOptions,
8
- PubsubTopic
3
+ import {
4
+ type ContentTopic,
5
+ type CoreProtocolResult,
6
+ type IBaseProtocolCore,
7
+ type Libp2p,
8
+ type ProtocolCreateOptions,
9
+ ProtocolError,
10
+ type PubsubTopic
9
11
  } from "@waku/interfaces";
10
12
  import { WakuMessage } from "@waku/proto";
11
13
  import { Logger } from "@waku/utils";
12
14
  import all from "it-all";
13
15
  import * as lp from "it-length-prefixed";
14
16
  import { pipe } from "it-pipe";
17
+ import { Uint8ArrayList } from "uint8arraylist";
15
18
 
16
19
  import { BaseProtocol } from "../base_protocol.js";
17
20
 
@@ -45,9 +48,13 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
45
48
  options
46
49
  );
47
50
 
48
- libp2p.handle(FilterCodecs.PUSH, this.onRequest.bind(this)).catch((e) => {
49
- log.error("Failed to register ", FilterCodecs.PUSH, e);
50
- });
51
+ libp2p
52
+ .handle(FilterCodecs.PUSH, this.onRequest.bind(this), {
53
+ maxInboundStreams: 100
54
+ })
55
+ .catch((e) => {
56
+ log.error("Failed to register ", FilterCodecs.PUSH, e);
57
+ });
51
58
  }
52
59
 
53
60
  private onRequest(streamData: IncomingStreamData): void {
@@ -90,7 +97,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
90
97
  pubsubTopic: PubsubTopic,
91
98
  peer: Peer,
92
99
  contentTopics: ContentTopic[]
93
- ): Promise<void> {
100
+ ): Promise<CoreProtocolResult> {
94
101
  const stream = await this.getStream(peer);
95
102
 
96
103
  const request = FilterSubscribeRpc.createSubscribeRequest(
@@ -98,45 +105,98 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
98
105
  contentTopics
99
106
  );
100
107
 
101
- const res = await pipe(
102
- [request.encode()],
103
- lp.encode,
104
- stream,
105
- lp.decode,
106
- async (source) => await all(source)
107
- );
108
-
109
- if (!res || !res.length) {
110
- throw Error(
111
- `No response received for request ${request.requestId}: ${res}`
108
+ let res: Uint8ArrayList[] | undefined;
109
+ try {
110
+ res = await pipe(
111
+ [request.encode()],
112
+ lp.encode,
113
+ stream,
114
+ lp.decode,
115
+ async (source) => await all(source)
112
116
  );
117
+ } catch (error) {
118
+ log.error("Failed to send subscribe request", error);
119
+ return {
120
+ success: null,
121
+ failure: {
122
+ error: ProtocolError.GENERIC_FAIL,
123
+ peerId: peer.id
124
+ }
125
+ };
113
126
  }
114
127
 
115
128
  const { statusCode, requestId, statusDesc } =
116
129
  FilterSubscribeResponse.decode(res[0].slice());
117
130
 
118
131
  if (statusCode < 200 || statusCode >= 300) {
119
- throw new Error(
132
+ log.error(
120
133
  `Filter subscribe request ${requestId} failed with status code ${statusCode}: ${statusDesc}`
121
134
  );
135
+ return {
136
+ failure: {
137
+ error: ProtocolError.REMOTE_PEER_REJECTED,
138
+ peerId: peer.id
139
+ },
140
+ success: null
141
+ };
122
142
  }
143
+
144
+ return {
145
+ failure: null,
146
+ success: peer.id
147
+ };
123
148
  }
124
149
 
125
150
  async unsubscribe(
126
151
  pubsubTopic: PubsubTopic,
127
152
  peer: Peer,
128
153
  contentTopics: ContentTopic[]
129
- ): Promise<void> {
130
- const stream = await this.getStream(peer);
154
+ ): Promise<CoreProtocolResult> {
155
+ let stream: Stream | undefined;
156
+ try {
157
+ stream = await this.getStream(peer);
158
+ } catch (error) {
159
+ log.error(
160
+ `Failed to get a stream for remote peer${peer.id.toString()}`,
161
+ error
162
+ );
163
+ return {
164
+ success: null,
165
+ failure: {
166
+ error: ProtocolError.REMOTE_PEER_FAULT,
167
+ peerId: peer.id
168
+ }
169
+ };
170
+ }
171
+
131
172
  const unsubscribeRequest = FilterSubscribeRpc.createUnsubscribeRequest(
132
173
  pubsubTopic,
133
174
  contentTopics
134
175
  );
135
176
 
136
- await pipe([unsubscribeRequest.encode()], lp.encode, stream.sink);
177
+ try {
178
+ await pipe([unsubscribeRequest.encode()], lp.encode, stream.sink);
179
+ } catch (error) {
180
+ log.error("Failed to send unsubscribe request", error);
181
+ return {
182
+ success: null,
183
+ failure: {
184
+ error: ProtocolError.GENERIC_FAIL,
185
+ peerId: peer.id
186
+ }
187
+ };
188
+ }
189
+
190
+ return {
191
+ success: peer.id,
192
+ failure: null
193
+ };
137
194
  }
138
195
 
139
- async unsubscribeAll(pubsubTopic: PubsubTopic, peer: Peer): Promise<void> {
196
+ async unsubscribeAll(
197
+ pubsubTopic: PubsubTopic,
198
+ peer: Peer
199
+ ): Promise<CoreProtocolResult> {
140
200
  const stream = await this.getStream(peer);
141
201
 
142
202
  const request = FilterSubscribeRpc.createUnsubscribeAllRequest(pubsubTopic);
@@ -150,53 +210,105 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
150
210
  );
151
211
 
152
212
  if (!res || !res.length) {
153
- throw Error(
154
- `No response received for request ${request.requestId}: ${res}`
155
- );
213
+ return {
214
+ failure: {
215
+ error: ProtocolError.REMOTE_PEER_FAULT,
216
+ peerId: peer.id
217
+ },
218
+ success: null
219
+ };
156
220
  }
157
221
 
158
222
  const { statusCode, requestId, statusDesc } =
159
223
  FilterSubscribeResponse.decode(res[0].slice());
160
224
 
161
225
  if (statusCode < 200 || statusCode >= 300) {
162
- throw new Error(
226
+ log.error(
163
227
  `Filter unsubscribe all request ${requestId} failed with status code ${statusCode}: ${statusDesc}`
164
228
  );
229
+ return {
230
+ failure: {
231
+ error: ProtocolError.REMOTE_PEER_REJECTED,
232
+ peerId: peer.id
233
+ },
234
+ success: null
235
+ };
165
236
  }
237
+
238
+ return {
239
+ failure: null,
240
+ success: peer.id
241
+ };
166
242
  }
167
243
 
168
- async ping(peer: Peer): Promise<void> {
169
- const stream = await this.getStream(peer);
244
+ async ping(peer: Peer): Promise<CoreProtocolResult> {
245
+ let stream: Stream | undefined;
246
+ try {
247
+ stream = await this.getStream(peer);
248
+ } catch (error) {
249
+ log.error(
250
+ `Failed to get a stream for remote peer${peer.id.toString()}`,
251
+ error
252
+ );
253
+ return {
254
+ success: null,
255
+ failure: {
256
+ error: ProtocolError.REMOTE_PEER_FAULT,
257
+ peerId: peer.id
258
+ }
259
+ };
260
+ }
170
261
 
171
262
  const request = FilterSubscribeRpc.createSubscriberPingRequest();
172
263
 
264
+ let res: Uint8ArrayList[] | undefined;
173
265
  try {
174
- const res = await pipe(
266
+ res = await pipe(
175
267
  [request.encode()],
176
268
  lp.encode,
177
269
  stream,
178
270
  lp.decode,
179
271
  async (source) => await all(source)
180
272
  );
181
-
182
- if (!res || !res.length) {
183
- throw Error(
184
- `No response received for request ${request.requestId}: ${res}`
185
- );
186
- }
187
-
188
- const { statusCode, requestId, statusDesc } =
189
- FilterSubscribeResponse.decode(res[0].slice());
190
-
191
- if (statusCode < 200 || statusCode >= 300) {
192
- throw new Error(
193
- `Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`
194
- );
195
- }
196
- log.info(`Ping successful for peer ${peer.id.toString()}`);
197
273
  } catch (error) {
198
- log.error("Error pinging: ", error);
199
- throw error; // Rethrow the actual error instead of wrapping it
274
+ log.error("Failed to send ping request", error);
275
+ return {
276
+ success: null,
277
+ failure: {
278
+ error: ProtocolError.GENERIC_FAIL,
279
+ peerId: peer.id
280
+ }
281
+ };
282
+ }
283
+
284
+ if (!res || !res.length) {
285
+ return {
286
+ success: null,
287
+ failure: {
288
+ error: ProtocolError.REMOTE_PEER_FAULT,
289
+ peerId: peer.id
290
+ }
291
+ };
292
+ }
293
+
294
+ const { statusCode, requestId, statusDesc } =
295
+ FilterSubscribeResponse.decode(res[0].slice());
296
+
297
+ if (statusCode < 200 || statusCode >= 300) {
298
+ log.error(
299
+ `Filter ping request ${requestId} failed with status code ${statusCode}: ${statusDesc}`
300
+ );
301
+ return {
302
+ success: null,
303
+ failure: {
304
+ error: ProtocolError.REMOTE_PEER_REJECTED,
305
+ peerId: peer.id
306
+ }
307
+ };
200
308
  }
309
+ return {
310
+ success: peer.id,
311
+ failure: null
312
+ };
201
313
  }
202
314
  }
@@ -1,13 +1,13 @@
1
- import type { Peer, PeerId, Stream } from "@libp2p/interface";
1
+ import type { Peer, Stream } from "@libp2p/interface";
2
2
  import {
3
- Failure,
4
- IBaseProtocolCore,
5
- IEncoder,
6
- IMessage,
7
- Libp2p,
8
- ProtocolCreateOptions,
3
+ type CoreProtocolResult,
4
+ type IBaseProtocolCore,
5
+ type IEncoder,
6
+ type IMessage,
7
+ type Libp2p,
8
+ type ProtocolCreateOptions,
9
9
  ProtocolError,
10
- ProtocolResult
10
+ type ThisOrThat
11
11
  } from "@waku/interfaces";
12
12
  import { PushResponse } from "@waku/proto";
13
13
  import { isMessageSizeUnderCap } from "@waku/utils";
@@ -26,9 +26,7 @@ const log = new Logger("light-push");
26
26
  export const LightPushCodec = "/vac/waku/lightpush/2.0.0-beta1";
27
27
  export { PushResponse };
28
28
 
29
- type PreparePushMessageResult = ProtocolResult<"query", PushRpc>;
30
-
31
- type CoreSendResult = ProtocolResult<"success", PeerId, "failure", Failure>;
29
+ type PreparePushMessageResult = ThisOrThat<"query", PushRpc>;
32
30
 
33
31
  /**
34
32
  * Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).
@@ -84,7 +82,7 @@ export class LightPushCore extends BaseProtocol implements IBaseProtocolCore {
84
82
  encoder: IEncoder,
85
83
  message: IMessage,
86
84
  peer: Peer
87
- ): Promise<CoreSendResult> {
85
+ ): Promise<CoreProtocolResult> {
88
86
  const { query, error: preparationError } = await this.preparePushMessage(
89
87
  encoder,
90
88
  message
@@ -100,18 +98,15 @@ export class LightPushCore extends BaseProtocol implements IBaseProtocolCore {
100
98
  };
101
99
  }
102
100
 
103
- let stream: Stream | undefined;
101
+ let stream: Stream;
104
102
  try {
105
103
  stream = await this.getStream(peer);
106
- } catch (err) {
107
- log.error(
108
- `Failed to get a stream for remote peer${peer.id.toString()}`,
109
- err
110
- );
104
+ } catch (error) {
105
+ log.error("Failed to get stream", error);
111
106
  return {
112
107
  success: null,
113
108
  failure: {
114
- error: ProtocolError.REMOTE_PEER_FAULT,
109
+ error: ProtocolError.NO_STREAM_AVAILABLE,
115
110
  peerId: peer.id
116
111
  }
117
112
  };
@@ -3,9 +3,9 @@ import { IncomingStreamData } from "@libp2p/interface";
3
3
  import {
4
4
  type IMetadata,
5
5
  type Libp2pComponents,
6
+ type MetadataQueryResult,
6
7
  type PeerIdStr,
7
8
  ProtocolError,
8
- QueryResult,
9
9
  type ShardInfo
10
10
  } from "@waku/interfaces";
11
11
  import { proto_metadata } from "@waku/proto";
@@ -74,7 +74,7 @@ class Metadata extends BaseProtocol implements IMetadata {
74
74
  /**
75
75
  * Make a metadata query to a peer
76
76
  */
77
- async query(peerId: PeerId): Promise<QueryResult> {
77
+ async query(peerId: PeerId): Promise<MetadataQueryResult> {
78
78
  const request = proto_metadata.WakuMetadataRequest.encode(this.shardInfo);
79
79
 
80
80
  const peer = await this.peerStore.get(peerId);
@@ -85,7 +85,16 @@ class Metadata extends BaseProtocol implements IMetadata {
85
85
  };
86
86
  }
87
87
 
88
- const stream = await this.getStream(peer);
88
+ let stream;
89
+ try {
90
+ stream = await this.getStream(peer);
91
+ } catch (error) {
92
+ log.error("Failed to get stream", error);
93
+ return {
94
+ shardInfo: null,
95
+ error: ProtocolError.NO_STREAM_AVAILABLE
96
+ };
97
+ }
89
98
 
90
99
  const encodedResponse = await pipe(
91
100
  [request],
@@ -112,7 +121,9 @@ class Metadata extends BaseProtocol implements IMetadata {
112
121
  };
113
122
  }
114
123
 
115
- public async confirmOrAttemptHandshake(peerId: PeerId): Promise<QueryResult> {
124
+ public async confirmOrAttemptHandshake(
125
+ peerId: PeerId
126
+ ): Promise<MetadataQueryResult> {
116
127
  const shardInfo = this.handshakesConfirmed.get(peerId.toString());
117
128
  if (shardInfo) {
118
129
  return {
@@ -126,7 +137,7 @@ class Metadata extends BaseProtocol implements IMetadata {
126
137
 
127
138
  private decodeMetadataResponse(
128
139
  encodedResponse: Uint8ArrayList[]
129
- ): QueryResult {
140
+ ): MetadataQueryResult {
130
141
  const bytes = new Uint8ArrayList();
131
142
 
132
143
  encodedResponse.forEach((chunk) => {
@@ -92,7 +92,13 @@ export class StoreCore extends BaseProtocol implements IStoreCore {
92
92
 
93
93
  const historyRpcQuery = HistoryRpc.createQuery(queryOpts);
94
94
 
95
- const stream = await this.getStream(peer);
95
+ let stream;
96
+ try {
97
+ stream = await this.getStream(peer);
98
+ } catch (e) {
99
+ log.error("Failed to get stream", e);
100
+ break;
101
+ }
96
102
 
97
103
  const res = await pipe(
98
104
  [historyRpcQuery.encode()],
@@ -1,11 +1,15 @@
1
1
  import type { PeerUpdate, Stream } from "@libp2p/interface";
2
- import { Peer } from "@libp2p/interface";
2
+ import type { Peer, PeerId } from "@libp2p/interface";
3
3
  import { Libp2p } from "@waku/interfaces";
4
4
  import { Logger } from "@waku/utils";
5
5
  import { selectConnection } from "@waku/utils/libp2p";
6
6
 
7
+ const CONNECTION_TIMEOUT = 5_000;
8
+ const RETRY_BACKOFF_BASE = 1_000;
9
+ const MAX_RETRIES = 3;
10
+
7
11
  export class StreamManager {
8
- private streamPool: Map<string, Promise<Stream | void>>;
12
+ private readonly streamPool: Map<string, Promise<Stream | void>>;
9
13
  private readonly log: Logger;
10
14
 
11
15
  constructor(
@@ -14,12 +18,8 @@ export class StreamManager {
14
18
  public addEventListener: Libp2p["addEventListener"]
15
19
  ) {
16
20
  this.log = new Logger(`stream-manager:${multicodec}`);
17
- this.addEventListener(
18
- "peer:update",
19
- this.handlePeerUpdateStreamPool.bind(this)
20
- );
21
- this.getStream = this.getStream.bind(this);
22
21
  this.streamPool = new Map();
22
+ this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
23
23
  }
24
24
 
25
25
  public async getStream(peer: Peer): Promise<Stream> {
@@ -27,47 +27,88 @@ export class StreamManager {
27
27
  const streamPromise = this.streamPool.get(peerIdStr);
28
28
 
29
29
  if (!streamPromise) {
30
- return this.newStream(peer); // fallback by creating a new stream on the spot
30
+ return this.createStream(peer);
31
31
  }
32
32
 
33
- // We have the stream, let's remove it from the map
34
33
  this.streamPool.delete(peerIdStr);
34
+ this.prepareStream(peer);
35
35
 
36
- this.prepareNewStream(peer);
37
-
38
- const stream = await streamPromise;
39
-
40
- if (!stream || stream.status === "closed") {
41
- return this.newStream(peer); // fallback by creating a new stream on the spot
36
+ try {
37
+ const stream = await streamPromise;
38
+ if (stream && stream.status !== "closed") {
39
+ return stream;
40
+ }
41
+ } catch (error) {
42
+ this.log.warn(`Failed to get stream for ${peerIdStr} -- `, error);
43
+ this.log.warn("Attempting to create a new stream for the peer");
42
44
  }
43
45
 
44
- return stream;
46
+ return this.createStream(peer);
45
47
  }
46
48
 
47
- private async newStream(peer: Peer): Promise<Stream> {
49
+ private async createStream(peer: Peer, retries = 0): Promise<Stream> {
48
50
  const connections = this.getConnections(peer.id);
49
51
  const connection = selectConnection(connections);
52
+
50
53
  if (!connection) {
51
54
  throw new Error("Failed to get a connection to the peer");
52
55
  }
53
- return connection.newStream(this.multicodec);
56
+
57
+ try {
58
+ return await connection.newStream(this.multicodec);
59
+ } catch (error) {
60
+ if (retries < MAX_RETRIES) {
61
+ const backoff = RETRY_BACKOFF_BASE * Math.pow(2, retries);
62
+ await new Promise((resolve) => setTimeout(resolve, backoff));
63
+ return this.createStream(peer, retries + 1);
64
+ }
65
+ throw new Error(
66
+ `Failed to create a new stream for ${peer.id.toString()} -- ` + error
67
+ );
68
+ }
54
69
  }
55
70
 
56
- private prepareNewStream(peer: Peer): void {
57
- const streamPromise = this.newStream(peer).catch(() => {
58
- // No error thrown as this call is not triggered by the user
71
+ private prepareStream(peer: Peer): void {
72
+ const timeoutPromise = new Promise<void>((resolve) =>
73
+ setTimeout(resolve, CONNECTION_TIMEOUT)
74
+ );
75
+
76
+ const streamPromise = Promise.race([
77
+ this.createStream(peer),
78
+ timeoutPromise.then(() => {
79
+ throw new Error("Connection timeout");
80
+ })
81
+ ]).catch((error) => {
59
82
  this.log.error(
60
- `Failed to prepare a new stream for ${peer.id.toString()}`
83
+ `Failed to prepare a new stream for ${peer.id.toString()} -- `,
84
+ error
61
85
  );
62
86
  });
87
+
63
88
  this.streamPool.set(peer.id.toString(), streamPromise);
64
89
  }
65
90
 
66
91
  private handlePeerUpdateStreamPool = (evt: CustomEvent<PeerUpdate>): void => {
67
- const peer = evt.detail.peer;
92
+ const { peer } = evt.detail;
93
+
68
94
  if (peer.protocols.includes(this.multicodec)) {
69
- this.log.info(`Preemptively opening a stream to ${peer.id.toString()}`);
70
- this.prepareNewStream(peer);
95
+ const isConnected = this.isConnectedTo(peer.id);
96
+
97
+ if (isConnected) {
98
+ this.log.info(`Preemptively opening a stream to ${peer.id.toString()}`);
99
+ this.prepareStream(peer);
100
+ } else {
101
+ const peerIdStr = peer.id.toString();
102
+ this.streamPool.delete(peerIdStr);
103
+ this.log.info(
104
+ `Removed pending stream for disconnected peer ${peerIdStr}`
105
+ );
106
+ }
71
107
  }
72
108
  };
109
+
110
+ private isConnectedTo(peerId: PeerId): boolean {
111
+ const connections = this.getConnections(peerId);
112
+ return connections.some((connection) => connection.status === "open");
113
+ }
73
114
  }