@waku/core 0.0.33-6a2d787.0 → 0.0.33-98208d5.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.
- package/bundle/base_protocol-Dzv-QHPR.js +275 -0
- package/bundle/{index-tdQNdKHx.js → index-BIW3qNYx.js} +19 -450
- package/bundle/index.js +100 -418
- package/bundle/lib/base_protocol.js +2 -2
- package/bundle/lib/message/version_0.js +2 -2
- package/bundle/{version_0-BrbNEwD-.js → version_0-CdmZMfkQ.js} +451 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/index.d.ts +1 -2
- package/dist/index.js +1 -2
- package/dist/index.js.map +1 -1
- package/dist/lib/base_protocol.d.ts +4 -6
- package/dist/lib/base_protocol.js +9 -14
- package/dist/lib/base_protocol.js.map +1 -1
- package/dist/lib/connection_manager.js +1 -1
- package/dist/lib/connection_manager.js.map +1 -1
- package/dist/lib/filter/index.js +2 -2
- package/dist/lib/filter/index.js.map +1 -1
- package/dist/lib/metadata/index.js +1 -1
- package/dist/lib/metadata/index.js.map +1 -1
- package/dist/lib/stream_manager/stream_manager.d.ts +12 -9
- package/dist/lib/stream_manager/stream_manager.js +87 -56
- package/dist/lib/stream_manager/stream_manager.js.map +1 -1
- package/dist/lib/stream_manager/utils.d.ts +1 -1
- package/dist/lib/stream_manager/utils.js +5 -17
- package/dist/lib/stream_manager/utils.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +1 -3
- package/src/lib/base_protocol.ts +12 -29
- package/src/lib/connection_manager.ts +1 -1
- package/src/lib/filter/index.ts +5 -2
- package/src/lib/metadata/index.ts +1 -1
- package/src/lib/stream_manager/stream_manager.ts +124 -66
- package/src/lib/stream_manager/utils.ts +5 -17
- package/bundle/base_protocol-BS9mxaB7.js +0 -336
- package/dist/lib/wait_for_remote_peer.d.ts +0 -22
- package/dist/lib/wait_for_remote_peer.js +0 -142
- package/dist/lib/wait_for_remote_peer.js.map +0 -1
- package/src/lib/wait_for_remote_peer.ts +0 -200
@@ -0,0 +1,275 @@
|
|
1
|
+
import { g as bytesToUtf8, T as Tags, L as Logger } from './index-BIW3qNYx.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
|
+
const STREAM_LOCK_KEY = "consumed";
|
91
|
+
class StreamManager {
|
92
|
+
multicodec;
|
93
|
+
getConnections;
|
94
|
+
addEventListener;
|
95
|
+
log;
|
96
|
+
ongoingCreation = new Set();
|
97
|
+
streamPool = new Map();
|
98
|
+
constructor(multicodec, getConnections, addEventListener) {
|
99
|
+
this.multicodec = multicodec;
|
100
|
+
this.getConnections = getConnections;
|
101
|
+
this.addEventListener = addEventListener;
|
102
|
+
this.log = new Logger(`stream-manager:${multicodec}`);
|
103
|
+
this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
|
104
|
+
}
|
105
|
+
async getStream(peer) {
|
106
|
+
const peerId = peer.id.toString();
|
107
|
+
const scheduledStream = this.streamPool.get(peerId);
|
108
|
+
if (scheduledStream) {
|
109
|
+
this.streamPool.delete(peerId);
|
110
|
+
await scheduledStream;
|
111
|
+
}
|
112
|
+
let stream = this.getOpenStreamForCodec(peer.id);
|
113
|
+
if (stream) {
|
114
|
+
this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
115
|
+
this.lockStream(peer.id.toString(), stream);
|
116
|
+
return stream;
|
117
|
+
}
|
118
|
+
stream = await this.createStream(peer);
|
119
|
+
this.lockStream(peer.id.toString(), stream);
|
120
|
+
return stream;
|
121
|
+
}
|
122
|
+
async createStream(peer, retries = 0) {
|
123
|
+
const connections = this.getConnections(peer.id);
|
124
|
+
const connection = selectOpenConnection(connections);
|
125
|
+
if (!connection) {
|
126
|
+
throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
127
|
+
}
|
128
|
+
let lastError;
|
129
|
+
let stream;
|
130
|
+
for (let i = 0; i < retries + 1; i++) {
|
131
|
+
try {
|
132
|
+
this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
133
|
+
stream = await connection.newStream(this.multicodec);
|
134
|
+
this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
135
|
+
break;
|
136
|
+
}
|
137
|
+
catch (error) {
|
138
|
+
lastError = error;
|
139
|
+
}
|
140
|
+
}
|
141
|
+
if (!stream) {
|
142
|
+
throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +
|
143
|
+
lastError);
|
144
|
+
}
|
145
|
+
return stream;
|
146
|
+
}
|
147
|
+
async createStreamWithLock(peer) {
|
148
|
+
const peerId = peer.id.toString();
|
149
|
+
if (this.ongoingCreation.has(peerId)) {
|
150
|
+
this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);
|
151
|
+
return;
|
152
|
+
}
|
153
|
+
try {
|
154
|
+
this.ongoingCreation.add(peerId);
|
155
|
+
await this.createStream(peer);
|
156
|
+
}
|
157
|
+
catch (error) {
|
158
|
+
this.log.error(`Failed to createStreamWithLock:`, error);
|
159
|
+
}
|
160
|
+
finally {
|
161
|
+
this.ongoingCreation.delete(peerId);
|
162
|
+
}
|
163
|
+
return;
|
164
|
+
}
|
165
|
+
handlePeerUpdateStreamPool = (evt) => {
|
166
|
+
const { peer } = evt.detail;
|
167
|
+
if (!peer.protocols.includes(this.multicodec)) {
|
168
|
+
return;
|
169
|
+
}
|
170
|
+
const stream = this.getOpenStreamForCodec(peer.id);
|
171
|
+
if (stream) {
|
172
|
+
return;
|
173
|
+
}
|
174
|
+
this.scheduleNewStream(peer);
|
175
|
+
};
|
176
|
+
scheduleNewStream(peer) {
|
177
|
+
this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
178
|
+
// abandon previous attempt
|
179
|
+
if (this.streamPool.has(peer.id.toString())) {
|
180
|
+
this.streamPool.delete(peer.id.toString());
|
181
|
+
}
|
182
|
+
this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));
|
183
|
+
}
|
184
|
+
getOpenStreamForCodec(peerId) {
|
185
|
+
const connections = this.getConnections(peerId);
|
186
|
+
const connection = selectOpenConnection(connections);
|
187
|
+
if (!connection) {
|
188
|
+
return;
|
189
|
+
}
|
190
|
+
const stream = connection.streams.find((s) => s.protocol === this.multicodec);
|
191
|
+
if (!stream) {
|
192
|
+
return;
|
193
|
+
}
|
194
|
+
const isStreamUnusable = ["done", "closed", "closing"].includes(stream.writeStatus || "");
|
195
|
+
if (isStreamUnusable || this.isStreamLocked(stream)) {
|
196
|
+
return;
|
197
|
+
}
|
198
|
+
return stream;
|
199
|
+
}
|
200
|
+
lockStream(peerId, stream) {
|
201
|
+
this.log.info(`Locking stream for peerId:${peerId}\tstreamId:${stream.id}`);
|
202
|
+
stream.metadata[STREAM_LOCK_KEY] = true;
|
203
|
+
}
|
204
|
+
isStreamLocked(stream) {
|
205
|
+
return !!stream.metadata[STREAM_LOCK_KEY];
|
206
|
+
}
|
207
|
+
}
|
208
|
+
|
209
|
+
/**
|
210
|
+
* A class with predefined helpers, to be used as a base to implement Waku
|
211
|
+
* Protocols.
|
212
|
+
*/
|
213
|
+
class BaseProtocol {
|
214
|
+
multicodec;
|
215
|
+
components;
|
216
|
+
log;
|
217
|
+
pubsubTopics;
|
218
|
+
addLibp2pEventListener;
|
219
|
+
removeLibp2pEventListener;
|
220
|
+
streamManager;
|
221
|
+
constructor(multicodec, components, log, pubsubTopics) {
|
222
|
+
this.multicodec = multicodec;
|
223
|
+
this.components = components;
|
224
|
+
this.log = log;
|
225
|
+
this.pubsubTopics = pubsubTopics;
|
226
|
+
this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
|
227
|
+
this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
|
228
|
+
this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
|
229
|
+
}
|
230
|
+
async getStream(peer) {
|
231
|
+
return this.streamManager.getStream(peer);
|
232
|
+
}
|
233
|
+
/**
|
234
|
+
* Returns known peers from the address book (`libp2p.peerStore`) that support
|
235
|
+
* the class protocol. Waku may or may not be currently connected to these
|
236
|
+
* peers.
|
237
|
+
*/
|
238
|
+
async allPeers() {
|
239
|
+
return getPeersForProtocol(this.components.peerStore, [this.multicodec]);
|
240
|
+
}
|
241
|
+
async connectedPeers() {
|
242
|
+
const peers = await this.allPeers();
|
243
|
+
return peers.filter((peer) => {
|
244
|
+
const connections = this.components.connectionManager.getConnections(peer.id);
|
245
|
+
return connections.length > 0;
|
246
|
+
});
|
247
|
+
}
|
248
|
+
/**
|
249
|
+
* Retrieves a list of connected peers that support the protocol. The list is sorted by latency.
|
250
|
+
*
|
251
|
+
* @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
|
252
|
+
* @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
|
253
|
+
* @returns A list of peers that support the protocol sorted by latency. By default, returns all peers available, including bootstrap.
|
254
|
+
*/
|
255
|
+
async getPeers({ numPeers, maxBootstrapPeers } = {
|
256
|
+
maxBootstrapPeers: 0,
|
257
|
+
numPeers: 0
|
258
|
+
}) {
|
259
|
+
// Retrieve all connected peers that support the protocol & shard (if configured)
|
260
|
+
const allAvailableConnectedPeers = await this.connectedPeers();
|
261
|
+
// Filter the peers based on discovery & number of peers requested
|
262
|
+
const filteredPeers = filterPeersByDiscovery(allAvailableConnectedPeers, numPeers, maxBootstrapPeers);
|
263
|
+
// Sort the peers by latency
|
264
|
+
const sortedFilteredPeers = await sortPeersByLatency(this.components.peerStore, filteredPeers);
|
265
|
+
if (sortedFilteredPeers.length === 0) {
|
266
|
+
this.log.warn("No peers found. Ensure you have a connection to the network.");
|
267
|
+
}
|
268
|
+
if (sortedFilteredPeers.length < numPeers) {
|
269
|
+
this.log.warn(`Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`);
|
270
|
+
}
|
271
|
+
return sortedFilteredPeers;
|
272
|
+
}
|
273
|
+
}
|
274
|
+
|
275
|
+
export { BaseProtocol as B, StreamManager as S };
|