@waku/core 0.0.33-6a2d787.0 → 0.0.33-a89e69f.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,22 +1,10 @@
1
1
  import type { Connection } from "@libp2p/interface";
2
2
 
3
- export function selectConnection(
3
+ export function selectOpenConnection(
4
4
  connections: Connection[]
5
5
  ): Connection | undefined {
6
- if (!connections.length) return;
7
- if (connections.length === 1) return connections[0];
8
-
9
- let latestConnection: Connection | undefined;
10
-
11
- connections.forEach((connection) => {
12
- if (connection.status === "open") {
13
- if (!latestConnection) {
14
- latestConnection = connection;
15
- } else if (connection.timeline.open > latestConnection.timeline.open) {
16
- latestConnection = connection;
17
- }
18
- }
19
- });
20
-
21
- return latestConnection;
6
+ return connections
7
+ .filter((c) => c.status === "open")
8
+ .sort((left, right) => right.timeline.open - left.timeline.open)
9
+ .at(0);
22
10
  }
@@ -1,336 +0,0 @@
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
- };
56
-
57
- /**
58
- * Function to sort peers by latency from lowest to highest
59
- * @param peerStore - The Libp2p PeerStore
60
- * @param peers - The list of peers to choose from
61
- * @returns Sorted array of peers by latency
62
- */
63
- async function sortPeersByLatency(peerStore, peers) {
64
- if (peers.length === 0)
65
- return [];
66
- const results = await Promise.all(peers.map(async (peer) => {
67
- try {
68
- const pingBytes = (await peerStore.get(peer.id)).metadata.get("ping");
69
- if (!pingBytes)
70
- return { peer, ping: Infinity };
71
- const ping = Number(bytesToUtf8(pingBytes));
72
- return { peer, ping };
73
- }
74
- catch (error) {
75
- return { peer, ping: Infinity };
76
- }
77
- }));
78
- // filter out null values
79
- const validResults = results.filter((result) => result !== null);
80
- return validResults
81
- .sort((a, b) => a.ping - b.ping)
82
- .map((result) => result.peer);
83
- }
84
- /**
85
- * Returns the list of peers that supports the given protocol.
86
- */
87
- async function getPeersForProtocol(peerStore, protocols) {
88
- const peers = [];
89
- await peerStore.forEach((peer) => {
90
- for (let i = 0; i < protocols.length; i++) {
91
- if (peer.protocols.includes(protocols[i])) {
92
- peers.push(peer);
93
- break;
94
- }
95
- }
96
- });
97
- return peers;
98
- }
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
-
122
- /**
123
- * Retrieves a list of peers based on the specified criteria:
124
- * 1. If numPeers is 0, return all peers
125
- * 2. Bootstrap peers are prioritized
126
- * 3. Non-bootstrap peers are randomly selected to fill up to numPeers
127
- *
128
- * @param peers - The list of peers to filter from.
129
- * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned, irrespective of `maxBootstrapPeers`.
130
- * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
131
- * @returns An array of peers based on the specified criteria.
132
- */
133
- function filterPeersByDiscovery(peers, numPeers, maxBootstrapPeers) {
134
- // Collect the bootstrap peers up to the specified maximum
135
- let bootstrapPeers = peers
136
- .filter((peer) => peer.tags.has(Tags.BOOTSTRAP))
137
- .slice(0, maxBootstrapPeers);
138
- // If numPeers is less than the number of bootstrap peers, adjust the bootstrapPeers array
139
- if (numPeers > 0 && numPeers < bootstrapPeers.length) {
140
- bootstrapPeers = bootstrapPeers.slice(0, numPeers);
141
- }
142
- // Collect non-bootstrap peers
143
- const nonBootstrapPeers = peers.filter((peer) => !peer.tags.has(Tags.BOOTSTRAP));
144
- // If numPeers is 0, return all peers
145
- if (numPeers === 0) {
146
- return [...bootstrapPeers, ...nonBootstrapPeers];
147
- }
148
- // Initialize the list of selected peers with the bootstrap peers
149
- const selectedPeers = [...bootstrapPeers];
150
- // Fill up to numPeers with remaining random peers if needed
151
- while (selectedPeers.length < numPeers && nonBootstrapPeers.length > 0) {
152
- const randomIndex = Math.floor(Math.random() * nonBootstrapPeers.length);
153
- const randomPeer = nonBootstrapPeers.splice(randomIndex, 1)[0];
154
- selectedPeers.push(randomPeer);
155
- }
156
- return selectedPeers;
157
- }
158
-
159
- function selectConnection(connections) {
160
- if (!connections.length)
161
- return;
162
- if (connections.length === 1)
163
- return connections[0];
164
- let latestConnection;
165
- connections.forEach((connection) => {
166
- if (connection.status === "open") {
167
- if (!latestConnection) {
168
- latestConnection = connection;
169
- }
170
- else if (connection.timeline.open > latestConnection.timeline.open) {
171
- latestConnection = connection;
172
- }
173
- }
174
- });
175
- return latestConnection;
176
- }
177
-
178
- const CONNECTION_TIMEOUT = 5_000;
179
- const RETRY_BACKOFF_BASE = 1_000;
180
- const MAX_RETRIES = 3;
181
- class StreamManager {
182
- multicodec;
183
- getConnections;
184
- addEventListener;
185
- streamPool;
186
- log;
187
- constructor(multicodec, getConnections, addEventListener) {
188
- this.multicodec = multicodec;
189
- this.getConnections = getConnections;
190
- this.addEventListener = addEventListener;
191
- this.log = new Logger(`stream-manager:${multicodec}`);
192
- this.streamPool = new Map();
193
- this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
194
- }
195
- async getStream(peer) {
196
- const peerIdStr = peer.id.toString();
197
- const streamPromise = this.streamPool.get(peerIdStr);
198
- if (!streamPromise) {
199
- return this.createStream(peer);
200
- }
201
- this.streamPool.delete(peerIdStr);
202
- this.prepareStream(peer);
203
- try {
204
- const stream = await streamPromise;
205
- if (stream && stream.status !== "closed") {
206
- return stream;
207
- }
208
- }
209
- catch (error) {
210
- this.log.warn(`Failed to get stream for ${peerIdStr} -- `, error);
211
- this.log.warn("Attempting to create a new stream for the peer");
212
- }
213
- return this.createStream(peer);
214
- }
215
- async createStream(peer, retries = 0) {
216
- const connections = this.getConnections(peer.id);
217
- const connection = selectConnection(connections);
218
- if (!connection) {
219
- throw new Error("Failed to get a connection to the peer");
220
- }
221
- try {
222
- return await connection.newStream(this.multicodec);
223
- }
224
- catch (error) {
225
- if (retries < MAX_RETRIES) {
226
- const backoff = RETRY_BACKOFF_BASE * Math.pow(2, retries);
227
- await new Promise((resolve) => setTimeout(resolve, backoff));
228
- return this.createStream(peer, retries + 1);
229
- }
230
- throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` + error);
231
- }
232
- }
233
- prepareStream(peer) {
234
- const timeoutPromise = new Promise((resolve) => setTimeout(resolve, CONNECTION_TIMEOUT));
235
- const streamPromise = Promise.race([
236
- this.createStream(peer),
237
- timeoutPromise.then(() => {
238
- throw new Error("Connection timeout");
239
- })
240
- ]).catch((error) => {
241
- this.log.error(`Failed to prepare a new stream for ${peer.id.toString()} -- `, error);
242
- });
243
- this.streamPool.set(peer.id.toString(), streamPromise);
244
- }
245
- handlePeerUpdateStreamPool = (evt) => {
246
- const { peer } = evt.detail;
247
- if (peer.protocols.includes(this.multicodec)) {
248
- const isConnected = this.isConnectedTo(peer.id);
249
- if (isConnected) {
250
- this.log.info(`Preemptively opening a stream to ${peer.id.toString()}`);
251
- this.prepareStream(peer);
252
- }
253
- else {
254
- const peerIdStr = peer.id.toString();
255
- this.streamPool.delete(peerIdStr);
256
- this.log.info(`Removed pending stream for disconnected peer ${peerIdStr}`);
257
- }
258
- }
259
- };
260
- isConnectedTo(peerId) {
261
- const connections = this.getConnections(peerId);
262
- return connections.some((connection) => connection.status === "open");
263
- }
264
- }
265
-
266
- /**
267
- * A class with predefined helpers, to be used as a base to implement Waku
268
- * Protocols.
269
- */
270
- class BaseProtocol {
271
- multicodec;
272
- components;
273
- log;
274
- pubsubTopics;
275
- addLibp2pEventListener;
276
- removeLibp2pEventListener;
277
- streamManager;
278
- constructor(multicodec, components, log, pubsubTopics) {
279
- this.multicodec = multicodec;
280
- this.components = components;
281
- this.log = log;
282
- this.pubsubTopics = pubsubTopics;
283
- this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
284
- this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
285
- this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
286
- }
287
- async getStream(peer) {
288
- return this.streamManager.getStream(peer);
289
- }
290
- get peerStore() {
291
- return this.components.peerStore;
292
- }
293
- /**
294
- * Returns known peers from the address book (`libp2p.peerStore`) that support
295
- * the class protocol. Waku may or may not be currently connected to these
296
- * peers.
297
- */
298
- async allPeers() {
299
- return getPeersForProtocol(this.peerStore, [this.multicodec]);
300
- }
301
- async connectedPeers() {
302
- const peers = await this.allPeers();
303
- return peers.filter((peer) => {
304
- const connections = this.components.connectionManager.getConnections(peer.id);
305
- return connections.some((c) => c.streams.some((s) => s.protocol === this.multicodec));
306
- });
307
- }
308
- /**
309
- * Retrieves a list of connected peers that support the protocol. The list is sorted by latency.
310
- *
311
- * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
312
- * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
313
-
314
- * @returns A list of peers that support the protocol sorted by latency.
315
- */
316
- async getPeers({ numPeers, maxBootstrapPeers } = {
317
- maxBootstrapPeers: 1,
318
- numPeers: 0
319
- }) {
320
- // Retrieve all connected peers that support the protocol & shard (if configured)
321
- const connectedPeersForProtocolAndShard = await getConnectedPeersForProtocolAndShard(this.components.connectionManager.getConnections(), this.peerStore, [this.multicodec], pubsubTopicsToShardInfo(this.pubsubTopics));
322
- // Filter the peers based on discovery & number of peers requested
323
- const filteredPeers = filterPeersByDiscovery(connectedPeersForProtocolAndShard, numPeers, maxBootstrapPeers);
324
- // Sort the peers by latency
325
- const sortedFilteredPeers = await sortPeersByLatency(this.peerStore, filteredPeers);
326
- if (sortedFilteredPeers.length === 0) {
327
- this.log.warn("No peers found. Ensure you have a connection to the network.");
328
- }
329
- if (sortedFilteredPeers.length < numPeers) {
330
- this.log.warn(`Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`);
331
- }
332
- return sortedFilteredPeers;
333
- }
334
- }
335
-
336
- export { BaseProtocol as B, StreamManager as S, decodeRelayShard as d, encodeRelayShard as e };