@waku/core 0.0.33-d3301ff.0 → 0.0.33-de10ff4.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 -417
- 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 +10 -14
- package/dist/lib/base_protocol.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 +14 -28
- 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-C47QkJ2o.js +0 -335
- 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
@@ -1,115 +1,173 @@
|
|
1
|
-
import type { PeerUpdate, Stream } from "@libp2p/interface";
|
2
|
-
import type {
|
3
|
-
import { Libp2p } from "@waku/interfaces";
|
1
|
+
import type { Peer, PeerId, PeerUpdate, Stream } from "@libp2p/interface";
|
2
|
+
import type { Libp2p } from "@waku/interfaces";
|
4
3
|
import { Logger } from "@waku/utils";
|
5
4
|
|
6
|
-
import {
|
5
|
+
import { selectOpenConnection } from "./utils.js";
|
7
6
|
|
8
|
-
const
|
9
|
-
const RETRY_BACKOFF_BASE = 1_000;
|
10
|
-
const MAX_RETRIES = 3;
|
7
|
+
const STREAM_LOCK_KEY = "consumed";
|
11
8
|
|
12
9
|
export class StreamManager {
|
13
|
-
private readonly streamPool: Map<string, Promise<Stream | void>>;
|
14
10
|
private readonly log: Logger;
|
15
11
|
|
12
|
+
private ongoingCreation: Set<string> = new Set();
|
13
|
+
private streamPool: Map<string, Promise<void>> = new Map();
|
14
|
+
|
16
15
|
public constructor(
|
17
|
-
|
18
|
-
|
19
|
-
|
16
|
+
private multicodec: string,
|
17
|
+
private getConnections: Libp2p["getConnections"],
|
18
|
+
private addEventListener: Libp2p["addEventListener"]
|
20
19
|
) {
|
21
20
|
this.log = new Logger(`stream-manager:${multicodec}`);
|
22
|
-
this.streamPool = new Map();
|
23
21
|
this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
|
24
22
|
}
|
25
23
|
|
26
24
|
public async getStream(peer: Peer): Promise<Stream> {
|
27
|
-
const
|
28
|
-
|
25
|
+
const peerId = peer.id.toString();
|
26
|
+
|
27
|
+
const scheduledStream = this.streamPool.get(peerId);
|
29
28
|
|
30
|
-
if (
|
31
|
-
|
29
|
+
if (scheduledStream) {
|
30
|
+
this.streamPool.delete(peerId);
|
31
|
+
await scheduledStream;
|
32
32
|
}
|
33
33
|
|
34
|
-
this.
|
35
|
-
this.prepareStream(peer);
|
34
|
+
let stream = this.getOpenStreamForCodec(peer.id);
|
36
35
|
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
|
43
|
-
this.log.warn(`Failed to get stream for ${peerIdStr} -- `, error);
|
44
|
-
this.log.warn("Attempting to create a new stream for the peer");
|
36
|
+
if (stream) {
|
37
|
+
this.log.info(
|
38
|
+
`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
39
|
+
);
|
40
|
+
this.lockStream(peer.id.toString(), stream);
|
41
|
+
return stream;
|
45
42
|
}
|
46
43
|
|
47
|
-
|
44
|
+
stream = await this.createStream(peer);
|
45
|
+
this.lockStream(peer.id.toString(), stream);
|
46
|
+
|
47
|
+
return stream;
|
48
48
|
}
|
49
49
|
|
50
50
|
private async createStream(peer: Peer, retries = 0): Promise<Stream> {
|
51
51
|
const connections = this.getConnections(peer.id);
|
52
|
-
const connection =
|
52
|
+
const connection = selectOpenConnection(connections);
|
53
53
|
|
54
54
|
if (!connection) {
|
55
|
-
throw new Error(
|
55
|
+
throw new Error(
|
56
|
+
`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
57
|
+
);
|
56
58
|
}
|
57
59
|
|
58
|
-
|
59
|
-
|
60
|
-
|
61
|
-
|
62
|
-
|
63
|
-
|
64
|
-
|
60
|
+
let lastError: unknown;
|
61
|
+
let stream: Stream | undefined;
|
62
|
+
|
63
|
+
for (let i = 0; i < retries + 1; i++) {
|
64
|
+
try {
|
65
|
+
this.log.info(
|
66
|
+
`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
67
|
+
);
|
68
|
+
stream = await connection.newStream(this.multicodec);
|
69
|
+
this.log.info(
|
70
|
+
`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
71
|
+
);
|
72
|
+
break;
|
73
|
+
} catch (error) {
|
74
|
+
lastError = error;
|
65
75
|
}
|
76
|
+
}
|
77
|
+
|
78
|
+
if (!stream) {
|
66
79
|
throw new Error(
|
67
|
-
`Failed to create a new stream for ${peer.id.toString()} -- ` +
|
80
|
+
`Failed to create a new stream for ${peer.id.toString()} -- ` +
|
81
|
+
lastError
|
68
82
|
);
|
69
83
|
}
|
84
|
+
|
85
|
+
return stream;
|
70
86
|
}
|
71
87
|
|
72
|
-
private
|
73
|
-
const
|
74
|
-
setTimeout(resolve, CONNECTION_TIMEOUT)
|
75
|
-
);
|
88
|
+
private async createStreamWithLock(peer: Peer): Promise<void> {
|
89
|
+
const peerId = peer.id.toString();
|
76
90
|
|
77
|
-
|
78
|
-
this.
|
79
|
-
|
80
|
-
throw new Error("Connection timeout");
|
81
|
-
})
|
82
|
-
]).catch((error) => {
|
83
|
-
this.log.error(
|
84
|
-
`Failed to prepare a new stream for ${peer.id.toString()} -- `,
|
85
|
-
error
|
91
|
+
if (this.ongoingCreation.has(peerId)) {
|
92
|
+
this.log.info(
|
93
|
+
`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`
|
86
94
|
);
|
87
|
-
|
95
|
+
return;
|
96
|
+
}
|
97
|
+
|
98
|
+
try {
|
99
|
+
this.ongoingCreation.add(peerId);
|
100
|
+
await this.createStream(peer);
|
101
|
+
} catch (error) {
|
102
|
+
this.log.error(`Failed to createStreamWithLock:`, error);
|
103
|
+
} finally {
|
104
|
+
this.ongoingCreation.delete(peerId);
|
105
|
+
}
|
88
106
|
|
89
|
-
|
107
|
+
return;
|
90
108
|
}
|
91
109
|
|
92
110
|
private handlePeerUpdateStreamPool = (evt: CustomEvent<PeerUpdate>): void => {
|
93
111
|
const { peer } = evt.detail;
|
94
112
|
|
95
|
-
if (peer.protocols.includes(this.multicodec)) {
|
96
|
-
|
113
|
+
if (!peer.protocols.includes(this.multicodec)) {
|
114
|
+
return;
|
115
|
+
}
|
116
|
+
|
117
|
+
const stream = this.getOpenStreamForCodec(peer.id);
|
97
118
|
|
98
|
-
|
99
|
-
|
100
|
-
this.prepareStream(peer);
|
101
|
-
} else {
|
102
|
-
const peerIdStr = peer.id.toString();
|
103
|
-
this.streamPool.delete(peerIdStr);
|
104
|
-
this.log.info(
|
105
|
-
`Removed pending stream for disconnected peer ${peerIdStr}`
|
106
|
-
);
|
107
|
-
}
|
119
|
+
if (stream) {
|
120
|
+
return;
|
108
121
|
}
|
122
|
+
|
123
|
+
this.scheduleNewStream(peer);
|
109
124
|
};
|
110
125
|
|
111
|
-
private
|
126
|
+
private scheduleNewStream(peer: Peer): void {
|
127
|
+
this.log.info(
|
128
|
+
`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
129
|
+
);
|
130
|
+
|
131
|
+
// abandon previous attempt
|
132
|
+
if (this.streamPool.has(peer.id.toString())) {
|
133
|
+
this.streamPool.delete(peer.id.toString());
|
134
|
+
}
|
135
|
+
|
136
|
+
this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));
|
137
|
+
}
|
138
|
+
|
139
|
+
private getOpenStreamForCodec(peerId: PeerId): Stream | undefined {
|
112
140
|
const connections = this.getConnections(peerId);
|
113
|
-
|
141
|
+
const connection = selectOpenConnection(connections);
|
142
|
+
|
143
|
+
if (!connection) {
|
144
|
+
return;
|
145
|
+
}
|
146
|
+
|
147
|
+
const stream = connection.streams.find(
|
148
|
+
(s) => s.protocol === this.multicodec
|
149
|
+
);
|
150
|
+
|
151
|
+
if (!stream) {
|
152
|
+
return;
|
153
|
+
}
|
154
|
+
|
155
|
+
const isStreamUnusable = ["done", "closed", "closing"].includes(
|
156
|
+
stream.writeStatus || ""
|
157
|
+
);
|
158
|
+
if (isStreamUnusable || this.isStreamLocked(stream)) {
|
159
|
+
return;
|
160
|
+
}
|
161
|
+
|
162
|
+
return stream;
|
163
|
+
}
|
164
|
+
|
165
|
+
private lockStream(peerId: string, stream: Stream): void {
|
166
|
+
this.log.info(`Locking stream for peerId:${peerId}\tstreamId:${stream.id}`);
|
167
|
+
stream.metadata[STREAM_LOCK_KEY] = true;
|
168
|
+
}
|
169
|
+
|
170
|
+
private isStreamLocked(stream: Stream): boolean {
|
171
|
+
return !!stream.metadata[STREAM_LOCK_KEY];
|
114
172
|
}
|
115
173
|
}
|
@@ -1,22 +1,10 @@
|
|
1
1
|
import type { Connection } from "@libp2p/interface";
|
2
2
|
|
3
|
-
export function
|
3
|
+
export function selectOpenConnection(
|
4
4
|
connections: Connection[]
|
5
5
|
): Connection | undefined {
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
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,335 +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
|
-
return (this.components.connectionManager.getConnections(peer.id).length > 0);
|
305
|
-
});
|
306
|
-
}
|
307
|
-
/**
|
308
|
-
* Retrieves a list of connected peers that support the protocol. The list is sorted by latency.
|
309
|
-
*
|
310
|
-
* @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
|
311
|
-
* @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
|
312
|
-
|
313
|
-
* @returns A list of peers that support the protocol sorted by latency.
|
314
|
-
*/
|
315
|
-
async getPeers({ numPeers, maxBootstrapPeers } = {
|
316
|
-
maxBootstrapPeers: 1,
|
317
|
-
numPeers: 0
|
318
|
-
}) {
|
319
|
-
// Retrieve all connected peers that support the protocol & shard (if configured)
|
320
|
-
const connectedPeersForProtocolAndShard = await getConnectedPeersForProtocolAndShard(this.components.connectionManager.getConnections(), this.peerStore, [this.multicodec], pubsubTopicsToShardInfo(this.pubsubTopics));
|
321
|
-
// Filter the peers based on discovery & number of peers requested
|
322
|
-
const filteredPeers = filterPeersByDiscovery(connectedPeersForProtocolAndShard, numPeers, maxBootstrapPeers);
|
323
|
-
// Sort the peers by latency
|
324
|
-
const sortedFilteredPeers = await sortPeersByLatency(this.peerStore, filteredPeers);
|
325
|
-
if (sortedFilteredPeers.length === 0) {
|
326
|
-
this.log.warn("No peers found. Ensure you have a connection to the network.");
|
327
|
-
}
|
328
|
-
if (sortedFilteredPeers.length < numPeers) {
|
329
|
-
this.log.warn(`Only ${sortedFilteredPeers.length} peers found. Requested ${numPeers}.`);
|
330
|
-
}
|
331
|
-
return sortedFilteredPeers;
|
332
|
-
}
|
333
|
-
}
|
334
|
-
|
335
|
-
export { BaseProtocol as B, StreamManager as S, decodeRelayShard as d, encodeRelayShard as e };
|
@@ -1,22 +0,0 @@
|
|
1
|
-
import type { Waku } from "@waku/interfaces";
|
2
|
-
import { Protocols } from "@waku/interfaces";
|
3
|
-
/**
|
4
|
-
* Wait for a remote peer to be ready given the passed protocols.
|
5
|
-
* Must be used after attempting to connect to nodes, using
|
6
|
-
* {@link @waku/sdk!WakuNode.dial} or a bootstrap method with
|
7
|
-
* {@link @waku/sdk!createLightNode}.
|
8
|
-
*
|
9
|
-
* If the passed protocols is a GossipSub protocol, then it resolves only once
|
10
|
-
* a peer is in a mesh, to help ensure that other peers will send and receive
|
11
|
-
* message to us.
|
12
|
-
*
|
13
|
-
* @param waku The Waku Node
|
14
|
-
* @param protocols The protocols that need to be enabled by remote peers.
|
15
|
-
* @param timeoutMs A timeout value in milliseconds..
|
16
|
-
*
|
17
|
-
* @returns A promise that **resolves** if all desired protocols are fulfilled by
|
18
|
-
* remote nodes, **rejects** if the timeoutMs is reached.
|
19
|
-
* @throws If passing a protocol that is not mounted
|
20
|
-
* @default Wait for remote peers with protocols enabled locally and no time out is applied.
|
21
|
-
*/
|
22
|
-
export declare function waitForRemotePeer(waku: Waku, protocols?: Protocols[], timeoutMs?: number): Promise<void>;
|