@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.
- package/bundle/base_protocol-DtQR2CNC.js +265 -0
- package/bundle/{index-tdQNdKHx.js → index-BVysxsMu.js} +6 -444
- package/bundle/index.js +66 -9
- 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-C5ObpJ_0.js} +445 -2
- package/dist/.tsbuildinfo +1 -1
- package/dist/lib/base_protocol.d.ts +5 -7
- package/dist/lib/base_protocol.js +14 -15
- package/dist/lib/base_protocol.js.map +1 -1
- package/dist/lib/filter/index.d.ts +2 -1
- package/dist/lib/filter/index.js +6 -3
- 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 +10 -9
- package/dist/lib/stream_manager/stream_manager.js +72 -55
- 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/lib/base_protocol.ts +19 -30
- package/src/lib/filter/index.ts +13 -2
- package/src/lib/metadata/index.ts +1 -1
- package/src/lib/stream_manager/stream_manager.ts +105 -66
- package/src/lib/stream_manager/utils.ts +5 -17
- package/bundle/base_protocol-BS9mxaB7.js +0 -336
@@ -1,16 +1,17 @@
|
|
1
|
-
import type { Stream } from "@libp2p/interface";
|
2
|
-
import type {
|
3
|
-
import { Libp2p } from "@waku/interfaces";
|
1
|
+
import type { Peer, Stream } from "@libp2p/interface";
|
2
|
+
import type { Libp2p } from "@waku/interfaces";
|
4
3
|
export declare class StreamManager {
|
5
|
-
multicodec
|
6
|
-
|
7
|
-
|
8
|
-
private readonly streamPool;
|
4
|
+
private multicodec;
|
5
|
+
private getConnections;
|
6
|
+
private addEventListener;
|
9
7
|
private readonly log;
|
8
|
+
private ongoingCreation;
|
9
|
+
private streamPool;
|
10
10
|
constructor(multicodec: string, getConnections: Libp2p["getConnections"], addEventListener: Libp2p["addEventListener"]);
|
11
11
|
getStream(peer: Peer): Promise<Stream>;
|
12
12
|
private createStream;
|
13
|
-
private
|
13
|
+
private createStreamWithLock;
|
14
14
|
private handlePeerUpdateStreamPool;
|
15
|
-
private
|
15
|
+
private scheduleNewStream;
|
16
|
+
private getOpenStreamForCodec;
|
16
17
|
}
|
@@ -1,90 +1,107 @@
|
|
1
1
|
import { Logger } from "@waku/utils";
|
2
|
-
import {
|
3
|
-
const CONNECTION_TIMEOUT = 5_000;
|
4
|
-
const RETRY_BACKOFF_BASE = 1_000;
|
5
|
-
const MAX_RETRIES = 3;
|
2
|
+
import { selectOpenConnection } from "./utils.js";
|
6
3
|
export class StreamManager {
|
7
4
|
multicodec;
|
8
5
|
getConnections;
|
9
6
|
addEventListener;
|
10
|
-
streamPool;
|
11
7
|
log;
|
8
|
+
ongoingCreation = new Set();
|
9
|
+
streamPool = new Map();
|
12
10
|
constructor(multicodec, getConnections, addEventListener) {
|
13
11
|
this.multicodec = multicodec;
|
14
12
|
this.getConnections = getConnections;
|
15
13
|
this.addEventListener = addEventListener;
|
16
14
|
this.log = new Logger(`stream-manager:${multicodec}`);
|
17
|
-
this.streamPool = new Map();
|
18
15
|
this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
|
19
16
|
}
|
20
17
|
async getStream(peer) {
|
21
|
-
const
|
22
|
-
const
|
23
|
-
if (
|
24
|
-
|
18
|
+
const peerId = peer.id.toString();
|
19
|
+
const scheduledStream = this.streamPool.get(peerId);
|
20
|
+
if (scheduledStream) {
|
21
|
+
this.streamPool.delete(peerId);
|
22
|
+
await scheduledStream;
|
25
23
|
}
|
26
|
-
this.
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
if (stream && stream.status !== "closed") {
|
31
|
-
return stream;
|
32
|
-
}
|
33
|
-
}
|
34
|
-
catch (error) {
|
35
|
-
this.log.warn(`Failed to get stream for ${peerIdStr} -- `, error);
|
36
|
-
this.log.warn("Attempting to create a new stream for the peer");
|
24
|
+
const stream = this.getOpenStreamForCodec(peer.id);
|
25
|
+
if (stream) {
|
26
|
+
this.log.info(`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
27
|
+
return stream;
|
37
28
|
}
|
38
29
|
return this.createStream(peer);
|
39
30
|
}
|
40
31
|
async createStream(peer, retries = 0) {
|
41
32
|
const connections = this.getConnections(peer.id);
|
42
|
-
const connection =
|
33
|
+
const connection = selectOpenConnection(connections);
|
43
34
|
if (!connection) {
|
44
|
-
throw new Error(
|
35
|
+
throw new Error(`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
36
|
+
}
|
37
|
+
let lastError;
|
38
|
+
let stream;
|
39
|
+
for (let i = 0; i < retries + 1; i++) {
|
40
|
+
try {
|
41
|
+
this.log.info(`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
42
|
+
stream = await connection.newStream(this.multicodec);
|
43
|
+
this.log.info(`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
44
|
+
break;
|
45
|
+
}
|
46
|
+
catch (error) {
|
47
|
+
lastError = error;
|
48
|
+
}
|
49
|
+
}
|
50
|
+
if (!stream) {
|
51
|
+
throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` +
|
52
|
+
lastError);
|
53
|
+
}
|
54
|
+
return stream;
|
55
|
+
}
|
56
|
+
async createStreamWithLock(peer) {
|
57
|
+
const peerId = peer.id.toString();
|
58
|
+
if (this.ongoingCreation.has(peerId)) {
|
59
|
+
this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);
|
60
|
+
return;
|
45
61
|
}
|
46
62
|
try {
|
47
|
-
|
63
|
+
this.ongoingCreation.add(peerId);
|
64
|
+
await this.createStream(peer);
|
48
65
|
}
|
49
66
|
catch (error) {
|
50
|
-
|
51
|
-
const backoff = RETRY_BACKOFF_BASE * Math.pow(2, retries);
|
52
|
-
await new Promise((resolve) => setTimeout(resolve, backoff));
|
53
|
-
return this.createStream(peer, retries + 1);
|
54
|
-
}
|
55
|
-
throw new Error(`Failed to create a new stream for ${peer.id.toString()} -- ` + error);
|
67
|
+
this.log.error(`Failed to createStreamWithLock:`, error);
|
56
68
|
}
|
57
|
-
|
58
|
-
|
59
|
-
|
60
|
-
|
61
|
-
this.createStream(peer),
|
62
|
-
timeoutPromise.then(() => {
|
63
|
-
throw new Error("Connection timeout");
|
64
|
-
})
|
65
|
-
]).catch((error) => {
|
66
|
-
this.log.error(`Failed to prepare a new stream for ${peer.id.toString()} -- `, error);
|
67
|
-
});
|
68
|
-
this.streamPool.set(peer.id.toString(), streamPromise);
|
69
|
+
finally {
|
70
|
+
this.ongoingCreation.delete(peerId);
|
71
|
+
}
|
72
|
+
return;
|
69
73
|
}
|
70
74
|
handlePeerUpdateStreamPool = (evt) => {
|
71
75
|
const { peer } = evt.detail;
|
72
|
-
if (peer.protocols.includes(this.multicodec)) {
|
73
|
-
|
74
|
-
|
75
|
-
|
76
|
-
|
77
|
-
|
78
|
-
else {
|
79
|
-
const peerIdStr = peer.id.toString();
|
80
|
-
this.streamPool.delete(peerIdStr);
|
81
|
-
this.log.info(`Removed pending stream for disconnected peer ${peerIdStr}`);
|
82
|
-
}
|
76
|
+
if (!peer.protocols.includes(this.multicodec)) {
|
77
|
+
return;
|
78
|
+
}
|
79
|
+
const stream = this.getOpenStreamForCodec(peer.id);
|
80
|
+
if (stream) {
|
81
|
+
return;
|
83
82
|
}
|
83
|
+
this.scheduleNewStream(peer);
|
84
84
|
};
|
85
|
-
|
85
|
+
scheduleNewStream(peer) {
|
86
|
+
this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
87
|
+
// abandon previous attempt
|
88
|
+
if (this.streamPool.has(peer.id.toString())) {
|
89
|
+
this.streamPool.delete(peer.id.toString());
|
90
|
+
}
|
91
|
+
this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));
|
92
|
+
}
|
93
|
+
getOpenStreamForCodec(peerId) {
|
86
94
|
const connections = this.getConnections(peerId);
|
87
|
-
|
95
|
+
const connection = selectOpenConnection(connections);
|
96
|
+
if (!connection) {
|
97
|
+
return;
|
98
|
+
}
|
99
|
+
const stream = connection.streams.find((s) => s.protocol === this.multicodec);
|
100
|
+
const isStreamUnusable = ["done", "closed", "closing"].includes(stream?.writeStatus || "");
|
101
|
+
if (isStreamUnusable) {
|
102
|
+
return;
|
103
|
+
}
|
104
|
+
return stream;
|
88
105
|
}
|
89
106
|
}
|
90
107
|
//# sourceMappingURL=stream_manager.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"stream_manager.js","sourceRoot":"","sources":["../../../src/lib/stream_manager/stream_manager.ts"],"names":[],"mappings":"
|
1
|
+
{"version":3,"file":"stream_manager.js","sourceRoot":"","sources":["../../../src/lib/stream_manager/stream_manager.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAErC,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAElD,MAAM,OAAO,aAAa;IAOd;IACA;IACA;IARO,GAAG,CAAS;IAErB,eAAe,GAAgB,IAAI,GAAG,EAAE,CAAC;IACzC,UAAU,GAA+B,IAAI,GAAG,EAAE,CAAC;IAE3D,YACU,UAAkB,EAClB,cAAwC,EACxC,gBAA4C;QAF5C,eAAU,GAAV,UAAU,CAAQ;QAClB,mBAAc,GAAd,cAAc,CAA0B;QACxC,qBAAgB,GAAhB,gBAAgB,CAA4B;QAEpD,IAAI,CAAC,GAAG,GAAG,IAAI,MAAM,CAAC,kBAAkB,UAAU,EAAE,CAAC,CAAC;QACtD,IAAI,CAAC,gBAAgB,CAAC,aAAa,EA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AM,MAAM,GAAG,UAAU,CAAC,OAAO,CAAC,IAAI,CACpC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,IAAI,CAAC,UAAU,CACtC,CAAC;QAEF,MAAM,gBAAgB,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,CAAC,CAAC,QAAQ,CAC7D,MAAM,EAAE,WAAW,IAAI,EAAE,CAC1B,CAAC;QACF,IAAI,gBAAgB,EAAE,CAAC;YACrB,OAAO;QACT,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF"}
|
@@ -1,2 +1,2 @@
|
|
1
1
|
import type { Connection } from "@libp2p/interface";
|
2
|
-
export declare function
|
2
|
+
export declare function selectOpenConnection(connections: Connection[]): Connection | undefined;
|
@@ -1,19 +1,7 @@
|
|
1
|
-
export function
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
let latestConnection;
|
7
|
-
connections.forEach((connection) => {
|
8
|
-
if (connection.status === "open") {
|
9
|
-
if (!latestConnection) {
|
10
|
-
latestConnection = connection;
|
11
|
-
}
|
12
|
-
else if (connection.timeline.open > latestConnection.timeline.open) {
|
13
|
-
latestConnection = connection;
|
14
|
-
}
|
15
|
-
}
|
16
|
-
});
|
17
|
-
return latestConnection;
|
1
|
+
export function selectOpenConnection(connections) {
|
2
|
+
return connections
|
3
|
+
.filter((c) => c.status === "open")
|
4
|
+
.sort((left, right) => right.timeline.open - left.timeline.open)
|
5
|
+
.at(0);
|
18
6
|
}
|
19
7
|
//# sourceMappingURL=utils.js.map
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/lib/stream_manager/utils.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/lib/stream_manager/utils.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,oBAAoB,CAClC,WAAyB;IAEzB,OAAO,WAAW;SACf,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM,CAAC;SAClC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;SAC/D,EAAE,CAAC,CAAC,CAAC,CAAC;AACX,CAAC"}
|
package/package.json
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"name":"@waku/core","version":"0.0.33-
|
1
|
+
{"name":"@waku/core","version":"0.0.33-a89e69f.0","description":"TypeScript implementation of the Waku v2 protocol","types":"./dist/index.d.ts","module":"./dist/index.js","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js"},"./lib/message/version_0":{"types":"./dist/lib/message/version_0.d.ts","import":"./dist/lib/message/version_0.js"},"./lib/base_protocol":{"types":"./dist/lib/base_protocol.d.ts","import":"./dist/lib/base_protocol.js"}},"typesVersions":{"*":{"lib/*":["dist/lib/*"],"constants/*":["dist/constants/*"]}},"type":"module","homepage":"https://github.com/waku-org/js-waku/tree/master/packages/core#readme","repository":{"type":"git","url":"https://github.com/waku-org/js-waku.git"},"bugs":{"url":"https://github.com/waku-org/js-waku/issues"},"license":"MIT OR Apache-2.0","keywords":["waku","decentralised","communication","web3","ethereum","dapps"],"scripts":{"build":"run-s build:**","build:esm":"tsc","build:bundle":"rollup --config rollup.config.js","fix":"run-s fix:*","fix:lint":"eslint src *.js --fix","check":"run-s check:*","check:tsc":"tsc -p tsconfig.dev.json","check:lint":"eslint src *.js","check:spelling":"cspell \"{README.md,src/**/*.ts}\"","test":"NODE_ENV=test run-s test:*","test:node":"NODE_ENV=test TS_NODE_PROJECT=./tsconfig.dev.json mocha","test:browser":"NODE_ENV=test karma start karma.conf.cjs","watch:build":"tsc -p tsconfig.json -w","watch:test":"mocha --watch","prepublish":"npm run build","reset-hard":"git clean -dfx -e .idea && git reset --hard && npm i && npm run build"},"engines":{"node":">=20"},"dependencies":{"@libp2p/ping":"^1.1.2","@waku/enr":"0.0.27-a89e69f.0","@waku/interfaces":"0.0.28-a89e69f.0","@waku/proto":"0.0.9-a89e69f.0","@waku/utils":"0.0.21-a89e69f.0","debug":"^4.3.4","it-all":"^3.0.4","it-length-prefixed":"^9.0.4","it-pipe":"^3.0.1","p-event":"^6.0.1","uint8arraylist":"^2.4.3","uuid":"^9.0.0"},"devDependencies":{"@multiformats/multiaddr":"^12.0.0","@rollup/plugin-commonjs":"^25.0.7","@rollup/plugin-json":"^6.0.0","@rollup/plugin-node-resolve":"^15.2.3","@types/chai":"^4.3.11","@types/debug":"^4.1.12","@types/mocha":"^10.0.6","@types/uuid":"^9.0.8","@waku/build-utils":"*","chai":"^4.3.10","sinon":"^18.0.0","cspell":"^8.6.1","fast-check":"^3.19.0","ignore-loader":"^0.1.2","isomorphic-fetch":"^3.0.0","mocha":"^10.3.0","npm-run-all":"^4.1.5","process":"^0.11.10","rollup":"^4.12.0"},"peerDependencies":{"@multiformats/multiaddr":"^12.0.0","libp2p":"^1.8.1"},"peerDependenciesMeta":{"@multiformats/multiaddr":{"optional":true},"libp2p":{"optional":true}},"files":["dist","bundle","src/**/*.ts","!**/*.spec.*","!**/*.json","CHANGELOG.md","LICENSE","README.md"]}
|
package/src/lib/base_protocol.ts
CHANGED
@@ -1,16 +1,12 @@
|
|
1
1
|
import type { Libp2p } from "@libp2p/interface";
|
2
|
-
import type { Peer,
|
2
|
+
import type { Peer, Stream } from "@libp2p/interface";
|
3
3
|
import type {
|
4
4
|
IBaseProtocolCore,
|
5
5
|
Libp2pComponents,
|
6
6
|
PubsubTopic
|
7
7
|
} from "@waku/interfaces";
|
8
|
-
import { Logger
|
9
|
-
import {
|
10
|
-
getConnectedPeersForProtocolAndShard,
|
11
|
-
getPeersForProtocol,
|
12
|
-
sortPeersByLatency
|
13
|
-
} from "@waku/utils/libp2p";
|
8
|
+
import { Logger } from "@waku/utils";
|
9
|
+
import { getPeersForProtocol, sortPeersByLatency } from "@waku/utils/libp2p";
|
14
10
|
|
15
11
|
import { filterPeersByDiscovery } from "./filterPeers.js";
|
16
12
|
import { StreamManager } from "./stream_manager/index.js";
|
@@ -26,7 +22,7 @@ export class BaseProtocol implements IBaseProtocolCore {
|
|
26
22
|
|
27
23
|
protected constructor(
|
28
24
|
public multicodec: string,
|
29
|
-
|
25
|
+
protected components: Libp2pComponents,
|
30
26
|
private log: Logger,
|
31
27
|
public readonly pubsubTopics: PubsubTopic[]
|
32
28
|
) {
|
@@ -50,28 +46,28 @@ export class BaseProtocol implements IBaseProtocolCore {
|
|
50
46
|
return this.streamManager.getStream(peer);
|
51
47
|
}
|
52
48
|
|
53
|
-
|
54
|
-
return this.components.peerStore;
|
55
|
-
}
|
56
|
-
|
49
|
+
//TODO: move to SDK
|
57
50
|
/**
|
58
51
|
* Returns known peers from the address book (`libp2p.peerStore`) that support
|
59
52
|
* the class protocol. Waku may or may not be currently connected to these
|
60
53
|
* peers.
|
61
54
|
*/
|
62
55
|
public async allPeers(): Promise<Peer[]> {
|
63
|
-
return getPeersForProtocol(this.peerStore, [this.multicodec]);
|
56
|
+
return getPeersForProtocol(this.components.peerStore, [this.multicodec]);
|
64
57
|
}
|
65
58
|
|
66
|
-
public async connectedPeers(): Promise<Peer[]> {
|
59
|
+
public async connectedPeers(withOpenStreams = false): Promise<Peer[]> {
|
67
60
|
const peers = await this.allPeers();
|
68
61
|
return peers.filter((peer) => {
|
69
62
|
const connections = this.components.connectionManager.getConnections(
|
70
63
|
peer.id
|
71
64
|
);
|
72
|
-
|
73
|
-
|
74
|
-
|
65
|
+
if (withOpenStreams) {
|
66
|
+
return connections.some((c) =>
|
67
|
+
c.streams.some((s) => s.protocol === this.multicodec)
|
68
|
+
);
|
69
|
+
}
|
70
|
+
return connections.length > 0;
|
75
71
|
});
|
76
72
|
}
|
77
73
|
|
@@ -80,9 +76,8 @@ export class BaseProtocol implements IBaseProtocolCore {
|
|
80
76
|
*
|
81
77
|
* @param numPeers - The total number of peers to retrieve. If 0, all peers are returned.
|
82
78
|
* @param maxBootstrapPeers - The maximum number of bootstrap peers to retrieve.
|
83
|
-
|
84
|
-
|
85
|
-
*/
|
79
|
+
* @returns A list of peers that support the protocol sorted by latency. By default, returns all peers available, including bootstrap.
|
80
|
+
*/
|
86
81
|
public async getPeers(
|
87
82
|
{
|
88
83
|
numPeers,
|
@@ -91,29 +86,23 @@ export class BaseProtocol implements IBaseProtocolCore {
|
|
91
86
|
numPeers: number;
|
92
87
|
maxBootstrapPeers: number;
|
93
88
|
} = {
|
94
|
-
maxBootstrapPeers:
|
89
|
+
maxBootstrapPeers: 0,
|
95
90
|
numPeers: 0
|
96
91
|
}
|
97
92
|
): Promise<Peer[]> {
|
98
93
|
// Retrieve all connected peers that support the protocol & shard (if configured)
|
99
|
-
const
|
100
|
-
await getConnectedPeersForProtocolAndShard(
|
101
|
-
this.components.connectionManager.getConnections(),
|
102
|
-
this.peerStore,
|
103
|
-
[this.multicodec],
|
104
|
-
pubsubTopicsToShardInfo(this.pubsubTopics)
|
105
|
-
);
|
94
|
+
const allAvailableConnectedPeers = await this.connectedPeers();
|
106
95
|
|
107
96
|
// Filter the peers based on discovery & number of peers requested
|
108
97
|
const filteredPeers = filterPeersByDiscovery(
|
109
|
-
|
98
|
+
allAvailableConnectedPeers,
|
110
99
|
numPeers,
|
111
100
|
maxBootstrapPeers
|
112
101
|
);
|
113
102
|
|
114
103
|
// Sort the peers by latency
|
115
104
|
const sortedFilteredPeers = await sortPeersByLatency(
|
116
|
-
this.peerStore,
|
105
|
+
this.components.peerStore,
|
117
106
|
filteredPeers
|
118
107
|
);
|
119
108
|
|
package/src/lib/filter/index.ts
CHANGED
@@ -37,6 +37,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
|
|
37
37
|
wakuMessage: WakuMessage,
|
38
38
|
peerIdStr: string
|
39
39
|
) => Promise<void>,
|
40
|
+
private handleError: (error: Error) => Promise<void>,
|
40
41
|
public readonly pubsubTopics: PubsubTopic[],
|
41
42
|
libp2p: Libp2p
|
42
43
|
) {
|
@@ -301,8 +302,18 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
|
|
301
302
|
() => {
|
302
303
|
log.info("Receiving pipe closed.");
|
303
304
|
},
|
304
|
-
(e) => {
|
305
|
-
log.error(
|
305
|
+
async (e) => {
|
306
|
+
log.error(
|
307
|
+
"Error with receiving pipe",
|
308
|
+
e,
|
309
|
+
" -- ",
|
310
|
+
"on peer ",
|
311
|
+
connection.remotePeer.toString(),
|
312
|
+
" -- ",
|
313
|
+
"stream ",
|
314
|
+
stream
|
315
|
+
);
|
316
|
+
await this.handleError(e);
|
306
317
|
}
|
307
318
|
);
|
308
319
|
} catch (e) {
|
@@ -45,7 +45,7 @@ class Metadata extends BaseProtocol implements IMetadata {
|
|
45
45
|
pubsubTopicsToShardInfo(this.pubsubTopics)
|
46
46
|
);
|
47
47
|
|
48
|
-
const peer = await this.peerStore.get(peerId);
|
48
|
+
const peer = await this.libp2pComponents.peerStore.get(peerId);
|
49
49
|
if (!peer) {
|
50
50
|
return {
|
51
51
|
shardInfo: null,
|
@@ -1,47 +1,41 @@
|
|
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 {
|
7
|
-
|
8
|
-
const CONNECTION_TIMEOUT = 5_000;
|
9
|
-
const RETRY_BACKOFF_BASE = 1_000;
|
10
|
-
const MAX_RETRIES = 3;
|
5
|
+
import { selectOpenConnection } from "./utils.js";
|
11
6
|
|
12
7
|
export class StreamManager {
|
13
|
-
private readonly streamPool: Map<string, Promise<Stream | void>>;
|
14
8
|
private readonly log: Logger;
|
15
9
|
|
10
|
+
private ongoingCreation: Set<string> = new Set();
|
11
|
+
private streamPool: Map<string, Promise<void>> = new Map();
|
12
|
+
|
16
13
|
public constructor(
|
17
|
-
|
18
|
-
|
19
|
-
|
14
|
+
private multicodec: string,
|
15
|
+
private getConnections: Libp2p["getConnections"],
|
16
|
+
private addEventListener: Libp2p["addEventListener"]
|
20
17
|
) {
|
21
18
|
this.log = new Logger(`stream-manager:${multicodec}`);
|
22
|
-
this.streamPool = new Map();
|
23
19
|
this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
|
24
20
|
}
|
25
21
|
|
26
22
|
public async getStream(peer: Peer): Promise<Stream> {
|
27
|
-
const
|
28
|
-
|
23
|
+
const peerId = peer.id.toString();
|
24
|
+
|
25
|
+
const scheduledStream = this.streamPool.get(peerId);
|
29
26
|
|
30
|
-
if (
|
31
|
-
|
27
|
+
if (scheduledStream) {
|
28
|
+
this.streamPool.delete(peerId);
|
29
|
+
await scheduledStream;
|
32
30
|
}
|
33
31
|
|
34
|
-
this.
|
35
|
-
this.prepareStream(peer);
|
32
|
+
const stream = this.getOpenStreamForCodec(peer.id);
|
36
33
|
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
} catch (error) {
|
43
|
-
this.log.warn(`Failed to get stream for ${peerIdStr} -- `, error);
|
44
|
-
this.log.warn("Attempting to create a new stream for the peer");
|
34
|
+
if (stream) {
|
35
|
+
this.log.info(
|
36
|
+
`Found existing stream peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
37
|
+
);
|
38
|
+
return stream;
|
45
39
|
}
|
46
40
|
|
47
41
|
return this.createStream(peer);
|
@@ -49,67 +43,112 @@ export class StreamManager {
|
|
49
43
|
|
50
44
|
private async createStream(peer: Peer, retries = 0): Promise<Stream> {
|
51
45
|
const connections = this.getConnections(peer.id);
|
52
|
-
const connection =
|
46
|
+
const connection = selectOpenConnection(connections);
|
53
47
|
|
54
48
|
if (!connection) {
|
55
|
-
throw new Error(
|
49
|
+
throw new Error(
|
50
|
+
`Failed to get a connection to the peer peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
51
|
+
);
|
56
52
|
}
|
57
53
|
|
58
|
-
|
59
|
-
|
60
|
-
|
61
|
-
|
62
|
-
|
63
|
-
|
64
|
-
|
54
|
+
let lastError: unknown;
|
55
|
+
let stream: Stream | undefined;
|
56
|
+
|
57
|
+
for (let i = 0; i < retries + 1; i++) {
|
58
|
+
try {
|
59
|
+
this.log.info(
|
60
|
+
`Attempting to create a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
61
|
+
);
|
62
|
+
stream = await connection.newStream(this.multicodec);
|
63
|
+
this.log.info(
|
64
|
+
`Created stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
65
|
+
);
|
66
|
+
break;
|
67
|
+
} catch (error) {
|
68
|
+
lastError = error;
|
65
69
|
}
|
70
|
+
}
|
71
|
+
|
72
|
+
if (!stream) {
|
66
73
|
throw new Error(
|
67
|
-
`Failed to create a new stream for ${peer.id.toString()} -- ` +
|
74
|
+
`Failed to create a new stream for ${peer.id.toString()} -- ` +
|
75
|
+
lastError
|
68
76
|
);
|
69
77
|
}
|
78
|
+
|
79
|
+
return stream;
|
70
80
|
}
|
71
81
|
|
72
|
-
private
|
73
|
-
const
|
74
|
-
setTimeout(resolve, CONNECTION_TIMEOUT)
|
75
|
-
);
|
82
|
+
private async createStreamWithLock(peer: Peer): Promise<void> {
|
83
|
+
const peerId = peer.id.toString();
|
76
84
|
|
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
|
85
|
+
if (this.ongoingCreation.has(peerId)) {
|
86
|
+
this.log.info(
|
87
|
+
`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`
|
86
88
|
);
|
87
|
-
|
89
|
+
return;
|
90
|
+
}
|
91
|
+
|
92
|
+
try {
|
93
|
+
this.ongoingCreation.add(peerId);
|
94
|
+
await this.createStream(peer);
|
95
|
+
} catch (error) {
|
96
|
+
this.log.error(`Failed to createStreamWithLock:`, error);
|
97
|
+
} finally {
|
98
|
+
this.ongoingCreation.delete(peerId);
|
99
|
+
}
|
88
100
|
|
89
|
-
|
101
|
+
return;
|
90
102
|
}
|
91
103
|
|
92
104
|
private handlePeerUpdateStreamPool = (evt: CustomEvent<PeerUpdate>): void => {
|
93
105
|
const { peer } = evt.detail;
|
94
106
|
|
95
|
-
if (peer.protocols.includes(this.multicodec)) {
|
96
|
-
|
107
|
+
if (!peer.protocols.includes(this.multicodec)) {
|
108
|
+
return;
|
109
|
+
}
|
97
110
|
|
98
|
-
|
99
|
-
|
100
|
-
|
101
|
-
|
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
|
-
}
|
111
|
+
const stream = this.getOpenStreamForCodec(peer.id);
|
112
|
+
|
113
|
+
if (stream) {
|
114
|
+
return;
|
108
115
|
}
|
116
|
+
|
117
|
+
this.scheduleNewStream(peer);
|
109
118
|
};
|
110
119
|
|
111
|
-
private
|
120
|
+
private scheduleNewStream(peer: Peer): void {
|
121
|
+
this.log.info(
|
122
|
+
`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`
|
123
|
+
);
|
124
|
+
|
125
|
+
// abandon previous attempt
|
126
|
+
if (this.streamPool.has(peer.id.toString())) {
|
127
|
+
this.streamPool.delete(peer.id.toString());
|
128
|
+
}
|
129
|
+
|
130
|
+
this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));
|
131
|
+
}
|
132
|
+
|
133
|
+
private getOpenStreamForCodec(peerId: PeerId): Stream | undefined {
|
112
134
|
const connections = this.getConnections(peerId);
|
113
|
-
|
135
|
+
const connection = selectOpenConnection(connections);
|
136
|
+
|
137
|
+
if (!connection) {
|
138
|
+
return;
|
139
|
+
}
|
140
|
+
|
141
|
+
const stream = connection.streams.find(
|
142
|
+
(s) => s.protocol === this.multicodec
|
143
|
+
);
|
144
|
+
|
145
|
+
const isStreamUnusable = ["done", "closed", "closing"].includes(
|
146
|
+
stream?.writeStatus || ""
|
147
|
+
);
|
148
|
+
if (isStreamUnusable) {
|
149
|
+
return;
|
150
|
+
}
|
151
|
+
|
152
|
+
return stream;
|
114
153
|
}
|
115
154
|
}
|