@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.
@@ -0,0 +1,265 @@
1
+ import { g as bytesToUtf8, T as Tags, L as Logger } from './index-BVysxsMu.js';
2
+
3
+ /**
4
+ * Function to sort peers by latency from lowest to highest
5
+ * @param peerStore - The Libp2p PeerStore
6
+ * @param peers - The list of peers to choose from
7
+ * @returns Sorted array of peers by latency
8
+ */
9
+ async function sortPeersByLatency(peerStore, peers) {
10
+ if (peers.length === 0)
11
+ return [];
12
+ const results = await Promise.all(peers.map(async (peer) => {
13
+ try {
14
+ const pingBytes = (await peerStore.get(peer.id)).metadata.get("ping");
15
+ if (!pingBytes)
16
+ return { peer, ping: Infinity };
17
+ const ping = Number(bytesToUtf8(pingBytes));
18
+ return { peer, ping };
19
+ }
20
+ catch (error) {
21
+ return { peer, ping: Infinity };
22
+ }
23
+ }));
24
+ // filter out null values
25
+ const validResults = results.filter((result) => result !== null);
26
+ return validResults
27
+ .sort((a, b) => a.ping - b.ping)
28
+ .map((result) => result.peer);
29
+ }
30
+ /**
31
+ * Returns the list of peers that supports the given protocol.
32
+ */
33
+ async function getPeersForProtocol(peerStore, protocols) {
34
+ const peers = [];
35
+ await peerStore.forEach((peer) => {
36
+ for (let i = 0; i < protocols.length; i++) {
37
+ if (peer.protocols.includes(protocols[i])) {
38
+ peers.push(peer);
39
+ break;
40
+ }
41
+ }
42
+ });
43
+ return peers;
44
+ }
45
+
46
+ /**
47
+ * Retrieves a list of peers based on the specified criteria:
48
+ * 1. If numPeers is 0, return all peers
49
+ * 2. Bootstrap peers are prioritized
50
+ * 3. Non-bootstrap peers are randomly selected to fill up to numPeers
51
+ *
52
+ * @param peers - The list of peers to filter from.
53
+ * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned, irrespective of `maxBootstrapPeers`.
54
+ * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
55
+ * @returns An array of peers based on the specified criteria.
56
+ */
57
+ function filterPeersByDiscovery(peers, numPeers, maxBootstrapPeers) {
58
+ // Collect the bootstrap peers up to the specified maximum
59
+ let bootstrapPeers = peers
60
+ .filter((peer) => peer.tags.has(Tags.BOOTSTRAP))
61
+ .slice(0, maxBootstrapPeers);
62
+ // If numPeers is less than the number of bootstrap peers, adjust the bootstrapPeers array
63
+ if (numPeers > 0 && numPeers < bootstrapPeers.length) {
64
+ bootstrapPeers = bootstrapPeers.slice(0, numPeers);
65
+ }
66
+ // Collect non-bootstrap peers
67
+ const nonBootstrapPeers = peers.filter((peer) => !peer.tags.has(Tags.BOOTSTRAP));
68
+ // If numPeers is 0, return all peers
69
+ if (numPeers === 0) {
70
+ return [...bootstrapPeers, ...nonBootstrapPeers];
71
+ }
72
+ // Initialize the list of selected peers with the bootstrap peers
73
+ const selectedPeers = [...bootstrapPeers];
74
+ // Fill up to numPeers with remaining random peers if needed
75
+ while (selectedPeers.length < numPeers && nonBootstrapPeers.length > 0) {
76
+ const randomIndex = Math.floor(Math.random() * nonBootstrapPeers.length);
77
+ const randomPeer = nonBootstrapPeers.splice(randomIndex, 1)[0];
78
+ selectedPeers.push(randomPeer);
79
+ }
80
+ return selectedPeers;
81
+ }
82
+
83
+ function selectOpenConnection(connections) {
84
+ return connections
85
+ .filter((c) => c.status === "open")
86
+ .sort((left, right) => right.timeline.open - left.timeline.open)
87
+ .at(0);
88
+ }
89
+
90
+ class StreamManager {
91
+ multicodec;
92
+ getConnections;
93
+ addEventListener;
94
+ log;
95
+ ongoingCreation = new Set();
96
+ streamPool = new Map();
97
+ constructor(multicodec, getConnections, addEventListener) {
98
+ this.multicodec = multicodec;
99
+ this.getConnections = getConnections;
100
+ this.addEventListener = addEventListener;
101
+ this.log = new Logger(`stream-manager:${multicodec}`);
102
+ this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
103
+ }
104
+ async getStream(peer) {
105
+ const peerId = peer.id.toString();
106
+ const scheduledStream = this.streamPool.get(peerId);
107
+ if (scheduledStream) {
108
+ this.streamPool.delete(peerId);
109
+ await scheduledStream;
110
+ }
111
+ const stream = this.getOpenStreamForCodec(peer.id);
112
+ if (stream) {
113
+ this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
114
+ return stream;
115
+ }
116
+ return this.createStream(peer);
117
+ }
118
+ async createStream(peer, retries = 0) {
119
+ const connections = this.getConnections(peer.id);
120
+ const connection = selectOpenConnection(connections);
121
+ if (!connection) {
122
+ throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
123
+ }
124
+ let lastError;
125
+ let stream;
126
+ for (let i = 0; i < retries + 1; i++) {
127
+ try {
128
+ this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
129
+ stream = await connection.newStream(this.multicodec);
130
+ this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
131
+ break;
132
+ }
133
+ catch (error) {
134
+ lastError = error;
135
+ }
136
+ }
137
+ if (!stream) {
138
+ throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +
139
+ lastError);
140
+ }
141
+ return stream;
142
+ }
143
+ async createStreamWithLock(peer) {
144
+ const peerId = peer.id.toString();
145
+ if (this.ongoingCreation.has(peerId)) {
146
+ this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);
147
+ return;
148
+ }
149
+ try {
150
+ this.ongoingCreation.add(peerId);
151
+ await this.createStream(peer);
152
+ }
153
+ catch (error) {
154
+ this.log.error(`Failed to createStreamWithLock:`, error);
155
+ }
156
+ finally {
157
+ this.ongoingCreation.delete(peerId);
158
+ }
159
+ return;
160
+ }
161
+ handlePeerUpdateStreamPool = (evt) => {
162
+ const { peer } = evt.detail;
163
+ if (!peer.protocols.includes(this.multicodec)) {
164
+ return;
165
+ }
166
+ const stream = this.getOpenStreamForCodec(peer.id);
167
+ if (stream) {
168
+ return;
169
+ }
170
+ this.scheduleNewStream(peer);
171
+ };
172
+ scheduleNewStream(peer) {
173
+ this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
174
+ // abandon previous attempt
175
+ if (this.streamPool.has(peer.id.toString())) {
176
+ this.streamPool.delete(peer.id.toString());
177
+ }
178
+ this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));
179
+ }
180
+ getOpenStreamForCodec(peerId) {
181
+ const connections = this.getConnections(peerId);
182
+ const connection = selectOpenConnection(connections);
183
+ if (!connection) {
184
+ return;
185
+ }
186
+ const stream = connection.streams.find((s) => s.protocol === this.multicodec);
187
+ const isStreamUnusable = ["done", "closed", "closing"].includes(stream?.writeStatus || "");
188
+ if (isStreamUnusable) {
189
+ return;
190
+ }
191
+ return stream;
192
+ }
193
+ }
194
+
195
+ /**
196
+ * A class with predefined helpers, to be used as a base to implement Waku
197
+ * Protocols.
198
+ */
199
+ class BaseProtocol {
200
+ multicodec;
201
+ components;
202
+ log;
203
+ pubsubTopics;
204
+ addLibp2pEventListener;
205
+ removeLibp2pEventListener;
206
+ streamManager;
207
+ constructor(multicodec, components, log, pubsubTopics) {
208
+ this.multicodec = multicodec;
209
+ this.components = components;
210
+ this.log = log;
211
+ this.pubsubTopics = pubsubTopics;
212
+ this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
213
+ this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
214
+ this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
215
+ }
216
+ async getStream(peer) {
217
+ return this.streamManager.getStream(peer);
218
+ }
219
+ //TODO: move to SDK
220
+ /**
221
+ * Returns known peers from the address book (`libp2p.peerStore`) that support
222
+ * the class protocol. Waku may or may not be currently connected to these
223
+ * peers.
224
+ */
225
+ async allPeers() {
226
+ return getPeersForProtocol(this.components.peerStore, [this.multicodec]);
227
+ }
228
+ async connectedPeers(withOpenStreams = false) {
229
+ const peers = await this.allPeers();
230
+ return peers.filter((peer) => {
231
+ const connections = this.components.connectionManager.getConnections(peer.id);
232
+ if (withOpenStreams) {
233
+ return connections.some((c) => c.streams.some((s) => s.protocol === this.multicodec));
234
+ }
235
+ return connections.length > 0;
236
+ });
237
+ }
238
+ /**
239
+ * Retrieves a list of connected peers that support the protocol. The list is sorted by latency.
240
+ *
241
+ * @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
242
+ * @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
243
+ * @returns A list of peers that support the protocol sorted by latency. By default, returns all peers available, including bootstrap.
244
+ */
245
+ async getPeers({ numPeers, maxBootstrapPeers } = {
246
+ maxBootstrapPeers: 0,
247
+ numPeers: 0
248
+ }) {
249
+ // Retrieve all connected peers that support the protocol & shard (if configured)
250
+ const allAvailableConnectedPeers = await this.connectedPeers();
251
+ // Filter the peers based on discovery & number of peers requested
252
+ const filteredPeers = filterPeersByDiscovery(allAvailableConnectedPeers, numPeers, maxBootstrapPeers);
253
+ // Sort the peers by latency
254
+ const sortedFilteredPeers = await sortPeersByLatency(this.components.peerStore, filteredPeers);
255
+ if (sortedFilteredPeers.length === 0) {
256
+ this.log.warn("No peers found. Ensure you have a connection to the network.");
257
+ }
258
+ if (sortedFilteredPeers.length < numPeers) {
259
+ this.log.warn(`Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`);
260
+ }
261
+ return sortedFilteredPeers;
262
+ }
263
+ }
264
+
265
+ export { BaseProtocol as B, StreamManager as S };