@waku/core 0.0.33-00c3261.0 → 0.0.33-09028e7.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,58 +1,4 @@
1
- import { h as bytesToUtf8, T as Tags, L as Logger, e as pubsubTopicsToShardInfo } from './index-tdQNdKHx.js';
2
-
3
- const decodeRelayShard = (bytes) => {
4
- // explicitly converting to Uint8Array to avoid Buffer
5
- // https://github.com/libp2p/js-libp2p/issues/2146
6
- bytes = new Uint8Array(bytes);
7
- if (bytes.length < 3)
8
- throw new Error("Insufficient data");
9
- const view = new DataView(bytes.buffer);
10
- const clusterId = view.getUint16(0);
11
- const shards = [];
12
- if (bytes.length === 130) {
13
- // rsv format (Bit Vector)
14
- for (let i = 0; i < 1024; i++) {
15
- const byteIndex = Math.floor(i / 8) + 2; // Adjusted for the 2-byte cluster field
16
- const bitIndex = 7 - (i % 8);
17
- if (view.getUint8(byteIndex) & (1 << bitIndex)) {
18
- shards.push(i);
19
- }
20
- }
21
- }
22
- else {
23
- // rs format (Index List)
24
- const numIndices = view.getUint8(2);
25
- for (let i = 0, offset = 3; i < numIndices; i++, offset += 2) {
26
- if (offset + 1 >= bytes.length)
27
- throw new Error("Unexpected end of data");
28
- shards.push(view.getUint16(offset));
29
- }
30
- }
31
- return { clusterId, shards };
32
- };
33
- const encodeRelayShard = (shardInfo) => {
34
- const { clusterId, shards } = shardInfo;
35
- const totalLength = shards.length >= 64 ? 130 : 3 + 2 * shards.length;
36
- const buffer = new ArrayBuffer(totalLength);
37
- const view = new DataView(buffer);
38
- view.setUint16(0, clusterId);
39
- if (shards.length >= 64) {
40
- // rsv format (Bit Vector)
41
- for (const index of shards) {
42
- const byteIndex = Math.floor(index / 8) + 2; // Adjusted for the 2-byte cluster field
43
- const bitIndex = 7 - (index % 8);
44
- view.setUint8(byteIndex, view.getUint8(byteIndex) | (1 << bitIndex));
45
- }
46
- }
47
- else {
48
- // rs format (Index List)
49
- view.setUint8(2, shards.length);
50
- for (let i = 0, offset = 3; i < shards.length; i++, offset += 2) {
51
- view.setUint16(offset, shards[i]);
52
- }
53
- }
54
- return new Uint8Array(buffer);
55
- };
1
+ import { g as bytesToUtf8, T as Tags, L as Logger } from './index-BVysxsMu.js';
56
2
 
57
3
  /**
58
4
  * Function to sort peers by latency from lowest to highest
@@ -96,28 +42,6 @@ async function getPeersForProtocol(peerStore, protocols) {
96
42
  });
97
43
  return peers;
98
44
  }
99
- async function getConnectedPeersForProtocolAndShard(connections, peerStore, protocols, shardInfo) {
100
- const openConnections = connections.filter((connection) => connection.status === "open");
101
- const peerPromises = openConnections.map(async (connection) => {
102
- const peer = await peerStore.get(connection.remotePeer);
103
- const supportsProtocol = protocols.some((protocol) => peer.protocols.includes(protocol));
104
- if (supportsProtocol) {
105
- if (shardInfo) {
106
- const encodedPeerShardInfo = peer.metadata.get("shardInfo");
107
- const peerShardInfo = encodedPeerShardInfo && decodeRelayShard(encodedPeerShardInfo);
108
- if (peerShardInfo && shardInfo.clusterId === peerShardInfo.clusterId) {
109
- return peer;
110
- }
111
- }
112
- else {
113
- return peer;
114
- }
115
- }
116
- return null;
117
- });
118
- const peersWithNulls = await Promise.all(peerPromises);
119
- return peersWithNulls.filter((peer) => peer !== null);
120
- }
121
45
 
122
46
  /**
123
47
  * Retrieves a list of peers based on the specified criteria:
@@ -176,29 +100,39 @@ function selectConnection(connections) {
176
100
  }
177
101
 
178
102
  const CONNECTION_TIMEOUT = 5_000;
103
+ const RETRY_BACKOFF_BASE = 1_000;
104
+ const MAX_RETRIES = 3;
179
105
  class StreamManager {
180
106
  multicodec;
181
107
  getConnections;
182
108
  addEventListener;
109
+ streamPool;
183
110
  log;
184
- ongoingCreation = new Set();
185
- streamPool = new Map();
186
111
  constructor(multicodec, getConnections, addEventListener) {
187
112
  this.multicodec = multicodec;
188
113
  this.getConnections = getConnections;
189
114
  this.addEventListener = addEventListener;
190
115
  this.log = new Logger(`stream-manager:${multicodec}`);
116
+ this.streamPool = new Map();
191
117
  this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
192
118
  }
193
119
  async getStream(peer) {
194
- const peerId = peer.id.toString();
195
- const scheduledStream = this.streamPool.get(peerId);
196
- this.streamPool.delete(peerId);
197
- await scheduledStream;
198
- const stream = this.getStreamForCodec(peer.id);
199
- if (stream) {
200
- this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
201
- return stream;
120
+ const peerIdStr = peer.id.toString();
121
+ const streamPromise = this.streamPool.get(peerIdStr);
122
+ if (!streamPromise) {
123
+ return this.createStream(peer);
124
+ }
125
+ this.streamPool.delete(peerIdStr);
126
+ this.prepareStream(peer);
127
+ try {
128
+ const stream = await streamPromise;
129
+ if (stream && stream.status !== "closed") {
130
+ return stream;
131
+ }
132
+ }
133
+ catch (error) {
134
+ this.log.warn(`Failed to get stream for ${peerIdStr} -- `, error);
135
+ this.log.warn("Attempting to create a new stream for the peer");
202
136
  }
203
137
  return this.createStream(peer);
204
138
  }
@@ -206,67 +140,50 @@ class StreamManager {
206
140
  const connections = this.getConnections(peer.id);
207
141
  const connection = selectConnection(connections);
208
142
  if (!connection) {
209
- throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
210
- }
211
- let lastError;
212
- let stream;
213
- for (let i = 0; i < retries + 1; i++) {
214
- try {
215
- this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
216
- stream = await connection.newStream(this.multicodec);
217
- this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
218
- }
219
- catch (error) {
220
- lastError = error;
221
- }
222
- }
223
- if (!stream) {
224
- throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +
225
- lastError);
226
- }
227
- return stream;
228
- }
229
- async createStreamWithLock(peer) {
230
- const peerId = peer.id.toString();
231
- if (this.ongoingCreation.has(peerId)) {
232
- this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);
233
- return;
143
+ throw new Error("Failed to get a connection to the peer");
234
144
  }
235
145
  try {
236
- this.ongoingCreation.add(peerId);
237
- await this.createStream(peer);
146
+ return await connection.newStream(this.multicodec);
238
147
  }
239
- finally {
240
- this.ongoingCreation.delete(peerId);
148
+ catch (error) {
149
+ if (retries < MAX_RETRIES) {
150
+ const backoff = RETRY_BACKOFF_BASE * Math.pow(2, retries);
151
+ await new Promise((resolve) => setTimeout(resolve, backoff));
152
+ return this.createStream(peer, retries + 1);
153
+ }
154
+ throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` + error);
241
155
  }
242
156
  }
243
- handlePeerUpdateStreamPool = (evt) => {
244
- const { peer } = evt.detail;
245
- if (!peer.protocols.includes(this.multicodec)) {
246
- return;
247
- }
248
- const stream = this.getStreamForCodec(peer.id);
249
- if (stream) {
250
- return;
251
- }
252
- this.scheduleNewStream(peer);
253
- };
254
- scheduleNewStream(peer) {
255
- this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
256
- const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(undefined), CONNECTION_TIMEOUT));
157
+ prepareStream(peer) {
158
+ const timeoutPromise = new Promise((resolve) => setTimeout(resolve, CONNECTION_TIMEOUT));
257
159
  const streamPromise = Promise.race([
258
- this.createStreamWithLock(peer),
259
- timeoutPromise
260
- ]);
160
+ this.createStream(peer),
161
+ timeoutPromise.then(() => {
162
+ throw new Error("Connection timeout");
163
+ })
164
+ ]).catch((error) => {
165
+ this.log.error(`Failed to prepare a new stream for ${peer.id.toString()} -- `, error);
166
+ });
261
167
  this.streamPool.set(peer.id.toString(), streamPromise);
262
168
  }
263
- getStreamForCodec(peerId) {
264
- const connection = this.getConnections(peerId).find((c) => c.status === "open");
265
- if (!connection) {
266
- return;
169
+ handlePeerUpdateStreamPool = (evt) => {
170
+ const { peer } = evt.detail;
171
+ if (peer.protocols.includes(this.multicodec)) {
172
+ const isConnected = this.isConnectedTo(peer.id);
173
+ if (isConnected) {
174
+ this.log.info(`Preemptively opening a stream to ${peer.id.toString()}`);
175
+ this.prepareStream(peer);
176
+ }
177
+ else {
178
+ const peerIdStr = peer.id.toString();
179
+ this.streamPool.delete(peerIdStr);
180
+ this.log.info(`Removed pending stream for disconnected peer ${peerIdStr}`);
181
+ }
267
182
  }
268
- const stream = connection.streams.find((s) => s.protocol === this.multicodec);
269
- return stream;
183
+ };
184
+ isConnectedTo(peerId) {
185
+ const connections = this.getConnections(peerId);
186
+ return connections.some((connection) => connection.status === "open");
270
187
  }
271
188
  }
272
189
 
@@ -294,21 +211,23 @@ class BaseProtocol {
294
211
  async getStream(peer) {
295
212
  return this.streamManager.getStream(peer);
296
213
  }
297
- get peerStore() {
298
- return this.components.peerStore;
299
- }
214
+ //TODO: move to SDK
300
215
  /**
301
216
  * Returns known peers from the address book (`libp2p.peerStore`) that support
302
217
  * the class protocol. Waku may or may not be currently connected to these
303
218
  * peers.
304
219
  */
305
220
  async allPeers() {
306
- return getPeersForProtocol(this.peerStore, [this.multicodec]);
221
+ return getPeersForProtocol(this.components.peerStore, [this.multicodec]);
307
222
  }
308
- async connectedPeers() {
223
+ async connectedPeers(withOpenStreams = false) {
309
224
  const peers = await this.allPeers();
310
225
  return peers.filter((peer) => {
311
- return (this.components.connectionManager.getConnections(peer.id).length > 0);
226
+ const connections = this.components.connectionManager.getConnections(peer.id);
227
+ if (withOpenStreams) {
228
+ return connections.some((c) => c.streams.some((s) => s.protocol === this.multicodec));
229
+ }
230
+ return connections.length > 0;
312
231
  });
313
232
  }
314
233
  /**
@@ -316,19 +235,18 @@ class BaseProtocol {
316
235
  *
317
236
  * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
318
237
  * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
319
-
320
- * @returns A list of peers that support the protocol sorted by latency.
321
- */
238
+ * @returns A list of peers that support the protocol sorted by latency. By default, returns all peers available, including bootstrap.
239
+ */
322
240
  async getPeers({ numPeers, maxBootstrapPeers } = {
323
- maxBootstrapPeers: 1,
241
+ maxBootstrapPeers: 0,
324
242
  numPeers: 0
325
243
  }) {
326
244
  // Retrieve all connected peers that support the protocol & shard (if configured)
327
- const connectedPeersForProtocolAndShard = await getConnectedPeersForProtocolAndShard(this.components.connectionManager.getConnections(), this.peerStore, [this.multicodec], pubsubTopicsToShardInfo(this.pubsubTopics));
245
+ const allAvailableConnectedPeers = await this.connectedPeers();
328
246
  // Filter the peers based on discovery & number of peers requested
329
- const filteredPeers = filterPeersByDiscovery(connectedPeersForProtocolAndShard, numPeers, maxBootstrapPeers);
247
+ const filteredPeers = filterPeersByDiscovery(allAvailableConnectedPeers, numPeers, maxBootstrapPeers);
330
248
  // Sort the peers by latency
331
- const sortedFilteredPeers = await sortPeersByLatency(this.peerStore, filteredPeers);
249
+ const sortedFilteredPeers = await sortPeersByLatency(this.components.peerStore, filteredPeers);
332
250
  if (sortedFilteredPeers.length === 0) {
333
251
  this.log.warn("No peers found. Ensure you have a connection to the network.");
334
252
  }
@@ -339,4 +257,4 @@ class BaseProtocol {
339
257
  }
340
258
  }
341
259
 
342
- export { BaseProtocol as B, StreamManager as S, decodeRelayShard as d, encodeRelayShard as e };
260
+ export { BaseProtocol as B, StreamManager as S };