@waku/core 0.0.36-383e0b2.0 → 0.0.36-4c18ca2.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/index.js +1098 -593
- package/bundle/lib/message/version_0.js +1 -2
- package/bundle/{version_0-4TwtF5aQ.js → version_0-9DPFjcJG.js} +1661 -65
- package/dist/.tsbuildinfo +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/lib/filter/filter.d.ts +8 -5
- package/dist/lib/filter/filter.js +30 -10
- package/dist/lib/filter/filter.js.map +1 -1
- package/dist/lib/light_push/light_push.d.ts +4 -3
- package/dist/lib/light_push/light_push.js +6 -4
- package/dist/lib/light_push/light_push.js.map +1 -1
- package/dist/lib/message/version_0.d.ts +3 -4
- package/dist/lib/message/version_0.js +1 -4
- package/dist/lib/message/version_0.js.map +1 -1
- package/dist/lib/message_hash/index.d.ts +1 -0
- package/dist/lib/message_hash/index.js +2 -0
- package/dist/lib/message_hash/index.js.map +1 -0
- package/dist/lib/message_hash/message_hash.d.ts +52 -0
- package/dist/lib/message_hash/message_hash.js +84 -0
- package/dist/lib/message_hash/message_hash.js.map +1 -0
- package/dist/lib/metadata/metadata.js +6 -4
- package/dist/lib/metadata/metadata.js.map +1 -1
- package/dist/lib/store/rpc.js +0 -4
- package/dist/lib/store/rpc.js.map +1 -1
- package/dist/lib/store/store.d.ts +4 -3
- package/dist/lib/store/store.js +6 -4
- package/dist/lib/store/store.js.map +1 -1
- package/dist/lib/stream_manager/stream_manager.d.ts +3 -4
- package/dist/lib/stream_manager/stream_manager.js +6 -8
- package/dist/lib/stream_manager/stream_manager.js.map +1 -1
- package/package.json +1 -1
- package/src/index.ts +2 -0
- package/src/lib/filter/filter.ts +46 -14
- package/src/lib/light_push/light_push.ts +8 -5
- package/src/lib/message/version_0.ts +3 -7
- package/src/lib/message_hash/index.ts +1 -0
- package/src/lib/message_hash/message_hash.ts +106 -0
- package/src/lib/metadata/metadata.ts +8 -5
- package/src/lib/store/rpc.ts +0 -4
- package/src/lib/store/store.ts +8 -5
- package/src/lib/stream_manager/stream_manager.ts +8 -6
- package/bundle/base_protocol-DvQrudwy.js +0 -152
- package/bundle/index-CTo1my9M.js +0 -1543
- package/bundle/lib/base_protocol.js +0 -2
- package/dist/lib/base_protocol.d.ts +0 -18
- package/dist/lib/base_protocol.js +0 -25
- package/dist/lib/base_protocol.js.map +0 -1
- package/src/lib/base_protocol.ts +0 -44
package/src/lib/filter/filter.ts
CHANGED
@@ -3,7 +3,6 @@ import type { IncomingStreamData } from "@libp2p/interface-internal";
|
|
3
3
|
import {
|
4
4
|
type ContentTopic,
|
5
5
|
type CoreProtocolResult,
|
6
|
-
type IBaseProtocolCore,
|
7
6
|
type Libp2p,
|
8
7
|
ProtocolError,
|
9
8
|
type PubsubTopic
|
@@ -15,7 +14,7 @@ import * as lp from "it-length-prefixed";
|
|
15
14
|
import { pipe } from "it-pipe";
|
16
15
|
import { Uint8ArrayList } from "uint8arraylist";
|
17
16
|
|
18
|
-
import {
|
17
|
+
import { StreamManager } from "../stream_manager/index.js";
|
19
18
|
|
20
19
|
import {
|
21
20
|
FilterPushRpc,
|
@@ -30,17 +29,50 @@ export const FilterCodecs = {
|
|
30
29
|
PUSH: "/vac/waku/filter-push/2.0.0-beta1"
|
31
30
|
};
|
32
31
|
|
33
|
-
|
32
|
+
type IncomingMessageHandler = (
|
33
|
+
pubsubTopic: PubsubTopic,
|
34
|
+
wakuMessage: WakuMessage,
|
35
|
+
peerIdStr: string
|
36
|
+
) => Promise<void>;
|
37
|
+
|
38
|
+
export class FilterCore {
|
39
|
+
private streamManager: StreamManager;
|
40
|
+
private static handleIncomingMessage?: IncomingMessageHandler;
|
41
|
+
|
42
|
+
public readonly multicodec = FilterCodecs.SUBSCRIBE;
|
43
|
+
|
34
44
|
public constructor(
|
35
|
-
|
36
|
-
pubsubTopic: PubsubTopic,
|
37
|
-
wakuMessage: WakuMessage,
|
38
|
-
peerIdStr: string
|
39
|
-
) => Promise<void>,
|
45
|
+
handleIncomingMessage: IncomingMessageHandler,
|
40
46
|
public readonly pubsubTopics: PubsubTopic[],
|
41
47
|
libp2p: Libp2p
|
42
48
|
) {
|
43
|
-
|
49
|
+
this.streamManager = new StreamManager(
|
50
|
+
FilterCodecs.SUBSCRIBE,
|
51
|
+
libp2p.components
|
52
|
+
);
|
53
|
+
|
54
|
+
// TODO(weboko): remove when @waku/sdk 0.0.33 is released
|
55
|
+
const prevHandler = FilterCore.handleIncomingMessage;
|
56
|
+
FilterCore.handleIncomingMessage = !prevHandler
|
57
|
+
? handleIncomingMessage
|
58
|
+
: async (pubsubTopic, message, peerIdStr): Promise<void> => {
|
59
|
+
try {
|
60
|
+
await prevHandler(pubsubTopic, message, peerIdStr);
|
61
|
+
} catch (e) {
|
62
|
+
log.error(
|
63
|
+
"Previous FilterCore incoming message handler failed ",
|
64
|
+
e
|
65
|
+
);
|
66
|
+
}
|
67
|
+
|
68
|
+
try {
|
69
|
+
await handleIncomingMessage(pubsubTopic, message, peerIdStr);
|
70
|
+
} catch (e) {
|
71
|
+
log.error("Present FilterCore incoming message handler failed ", e);
|
72
|
+
}
|
73
|
+
|
74
|
+
return;
|
75
|
+
};
|
44
76
|
|
45
77
|
libp2p
|
46
78
|
.handle(FilterCodecs.PUSH, this.onRequest.bind(this), {
|
@@ -56,7 +88,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
|
|
56
88
|
peerId: PeerId,
|
57
89
|
contentTopics: ContentTopic[]
|
58
90
|
): Promise<CoreProtocolResult> {
|
59
|
-
const stream = await this.getStream(peerId);
|
91
|
+
const stream = await this.streamManager.getStream(peerId);
|
60
92
|
|
61
93
|
const request = FilterSubscribeRpc.createSubscribeRequest(
|
62
94
|
pubsubTopic,
|
@@ -112,7 +144,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
|
|
112
144
|
): Promise<CoreProtocolResult> {
|
113
145
|
let stream: Stream | undefined;
|
114
146
|
try {
|
115
|
-
stream = await this.getStream(peerId);
|
147
|
+
stream = await this.streamManager.getStream(peerId);
|
116
148
|
} catch (error) {
|
117
149
|
log.error(
|
118
150
|
`Failed to get a stream for remote peer${peerId.toString()}`,
|
@@ -155,7 +187,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
|
|
155
187
|
pubsubTopic: PubsubTopic,
|
156
188
|
peerId: PeerId
|
157
189
|
): Promise<CoreProtocolResult> {
|
158
|
-
const stream = await this.getStream(peerId);
|
190
|
+
const stream = await this.streamManager.getStream(peerId);
|
159
191
|
|
160
192
|
const request = FilterSubscribeRpc.createUnsubscribeAllRequest(pubsubTopic);
|
161
193
|
|
@@ -202,7 +234,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
|
|
202
234
|
public async ping(peerId: PeerId): Promise<CoreProtocolResult> {
|
203
235
|
let stream: Stream | undefined;
|
204
236
|
try {
|
205
|
-
stream = await this.getStream(peerId);
|
237
|
+
stream = await this.streamManager.getStream(peerId);
|
206
238
|
} catch (error) {
|
207
239
|
log.error(
|
208
240
|
`Failed to get a stream for remote peer${peerId.toString()}`,
|
@@ -291,7 +323,7 @@ export class FilterCore extends BaseProtocol implements IBaseProtocolCore {
|
|
291
323
|
return;
|
292
324
|
}
|
293
325
|
|
294
|
-
await
|
326
|
+
await FilterCore.handleIncomingMessage?.(
|
295
327
|
pubsubTopic,
|
296
328
|
wakuMessage,
|
297
329
|
connection.remotePeer.toString()
|
@@ -1,7 +1,6 @@
|
|
1
1
|
import type { PeerId, Stream } from "@libp2p/interface";
|
2
2
|
import {
|
3
3
|
type CoreProtocolResult,
|
4
|
-
type IBaseProtocolCore,
|
5
4
|
type IEncoder,
|
6
5
|
type IMessage,
|
7
6
|
type Libp2p,
|
@@ -17,7 +16,7 @@ import * as lp from "it-length-prefixed";
|
|
17
16
|
import { pipe } from "it-pipe";
|
18
17
|
import { Uint8ArrayList } from "uint8arraylist";
|
19
18
|
|
20
|
-
import {
|
19
|
+
import { StreamManager } from "../stream_manager/index.js";
|
21
20
|
|
22
21
|
import { PushRpc } from "./push_rpc.js";
|
23
22
|
import { isRLNResponseError } from "./utils.js";
|
@@ -32,12 +31,16 @@ type PreparePushMessageResult = ThisOrThat<"query", PushRpc>;
|
|
32
31
|
/**
|
33
32
|
* Implements the [Waku v2 Light Push protocol](https://rfc.vac.dev/spec/19/).
|
34
33
|
*/
|
35
|
-
export class LightPushCore
|
34
|
+
export class LightPushCore {
|
35
|
+
private readonly streamManager: StreamManager;
|
36
|
+
|
37
|
+
public readonly multicodec = LightPushCodec;
|
38
|
+
|
36
39
|
public constructor(
|
37
40
|
public readonly pubsubTopics: PubsubTopic[],
|
38
41
|
libp2p: Libp2p
|
39
42
|
) {
|
40
|
-
|
43
|
+
this.streamManager = new StreamManager(LightPushCodec, libp2p.components);
|
41
44
|
}
|
42
45
|
|
43
46
|
private async preparePushMessage(
|
@@ -98,7 +101,7 @@ export class LightPushCore extends BaseProtocol implements IBaseProtocolCore {
|
|
98
101
|
|
99
102
|
let stream: Stream;
|
100
103
|
try {
|
101
|
-
stream = await this.getStream(peerId);
|
104
|
+
stream = await this.streamManager.getStream(peerId);
|
102
105
|
} catch (error) {
|
103
106
|
log.error("Failed to get stream", error);
|
104
107
|
return {
|
@@ -22,7 +22,7 @@ export { proto };
|
|
22
22
|
export class DecodedMessage implements IDecodedMessage {
|
23
23
|
public constructor(
|
24
24
|
public pubsubTopic: string,
|
25
|
-
|
25
|
+
private proto: proto.WakuMessage
|
26
26
|
) {}
|
27
27
|
|
28
28
|
public get ephemeral(): boolean {
|
@@ -37,10 +37,6 @@ export class DecodedMessage implements IDecodedMessage {
|
|
37
37
|
return this.proto.contentTopic;
|
38
38
|
}
|
39
39
|
|
40
|
-
public get _rawTimestamp(): bigint | undefined {
|
41
|
-
return this.proto.timestamp;
|
42
|
-
}
|
43
|
-
|
44
40
|
public get timestamp(): Date | undefined {
|
45
41
|
// In the case we receive a value that is bigger than JS's max number,
|
46
42
|
// we catch the error and return undefined.
|
@@ -63,7 +59,7 @@ export class DecodedMessage implements IDecodedMessage {
|
|
63
59
|
public get version(): number {
|
64
60
|
// https://rfc.vac.dev/spec/14/
|
65
61
|
// > If omitted, the value SHOULD be interpreted as version 0.
|
66
|
-
return this.proto.version ??
|
62
|
+
return this.proto.version ?? Version;
|
67
63
|
}
|
68
64
|
|
69
65
|
public get rateLimitProof(): IRateLimitProof | undefined {
|
@@ -160,7 +156,7 @@ export class Decoder implements IDecoder<IDecodedMessage> {
|
|
160
156
|
public async fromProtoObj(
|
161
157
|
pubsubTopic: string,
|
162
158
|
proto: IProtoMessage
|
163
|
-
): Promise<
|
159
|
+
): Promise<IDecodedMessage | undefined> {
|
164
160
|
// https://rfc.vac.dev/spec/14/
|
165
161
|
// > If omitted, the value SHOULD be interpreted as version 0.
|
166
162
|
if (proto.version ?? 0 !== Version) {
|
@@ -0,0 +1 @@
|
|
1
|
+
export { messageHash, messageHashStr } from "./message_hash.js";
|
@@ -0,0 +1,106 @@
|
|
1
|
+
import { sha256 } from "@noble/hashes/sha256";
|
2
|
+
import type { IDecodedMessage, IProtoMessage } from "@waku/interfaces";
|
3
|
+
import { isDefined } from "@waku/utils";
|
4
|
+
import {
|
5
|
+
bytesToHex,
|
6
|
+
concat,
|
7
|
+
numberToBytes,
|
8
|
+
utf8ToBytes
|
9
|
+
} from "@waku/utils/bytes";
|
10
|
+
|
11
|
+
/**
|
12
|
+
* Deterministic Message Hashing as defined in
|
13
|
+
* [14/WAKU2-MESSAGE](https://rfc.vac.dev/spec/14/#deterministic-message-hashing)
|
14
|
+
*
|
15
|
+
* Computes a SHA-256 hash of the concatenation of pubsub topic, payload, content topic, meta, and timestamp.
|
16
|
+
*
|
17
|
+
* @param pubsubTopic - The pubsub topic string
|
18
|
+
* @param message - The message to be hashed
|
19
|
+
* @returns A Uint8Array containing the SHA-256 hash
|
20
|
+
*
|
21
|
+
* @example
|
22
|
+
* ```typescript
|
23
|
+
* import { messageHash } from "@waku/core";
|
24
|
+
*
|
25
|
+
* const pubsubTopic = "/waku/2/default-waku/proto";
|
26
|
+
* const message = {
|
27
|
+
* payload: new Uint8Array([1, 2, 3, 4]),
|
28
|
+
* contentTopic: "/waku/2/default-content/proto",
|
29
|
+
* meta: new Uint8Array([5, 6, 7, 8]),
|
30
|
+
* timestamp: new Date()
|
31
|
+
* };
|
32
|
+
*
|
33
|
+
* const hash = messageHash(pubsubTopic, message);
|
34
|
+
* ```
|
35
|
+
*/
|
36
|
+
export function messageHash(
|
37
|
+
pubsubTopic: string,
|
38
|
+
message: IProtoMessage | IDecodedMessage
|
39
|
+
): Uint8Array {
|
40
|
+
const pubsubTopicBytes = utf8ToBytes(pubsubTopic);
|
41
|
+
const contentTopicBytes = utf8ToBytes(message.contentTopic);
|
42
|
+
const timestampBytes = tryConvertTimestampToBytes(message.timestamp);
|
43
|
+
|
44
|
+
const bytes = concat(
|
45
|
+
[
|
46
|
+
pubsubTopicBytes,
|
47
|
+
message.payload,
|
48
|
+
contentTopicBytes,
|
49
|
+
message.meta,
|
50
|
+
timestampBytes
|
51
|
+
].filter(isDefined)
|
52
|
+
);
|
53
|
+
|
54
|
+
return sha256(bytes);
|
55
|
+
}
|
56
|
+
|
57
|
+
function tryConvertTimestampToBytes(
|
58
|
+
timestamp: Date | number | bigint | undefined
|
59
|
+
): undefined | Uint8Array {
|
60
|
+
if (!timestamp) {
|
61
|
+
return;
|
62
|
+
}
|
63
|
+
|
64
|
+
let bigIntTimestamp: bigint;
|
65
|
+
|
66
|
+
if (typeof timestamp === "bigint") {
|
67
|
+
bigIntTimestamp = timestamp;
|
68
|
+
} else {
|
69
|
+
bigIntTimestamp = BigInt(timestamp.valueOf()) * 1000000n;
|
70
|
+
}
|
71
|
+
|
72
|
+
return numberToBytes(bigIntTimestamp);
|
73
|
+
}
|
74
|
+
|
75
|
+
/**
|
76
|
+
* Computes a deterministic message hash and returns it as a hexadecimal string.
|
77
|
+
* This is a convenience wrapper around messageHash that converts the result to a hex string.
|
78
|
+
*
|
79
|
+
* @param pubsubTopic - The pubsub topic string
|
80
|
+
* @param message - The message to be hashed
|
81
|
+
* @returns A string containing the hex representation of the SHA-256 hash
|
82
|
+
*
|
83
|
+
* @example
|
84
|
+
* ```typescript
|
85
|
+
* import { messageHashStr } from "@waku/core";
|
86
|
+
*
|
87
|
+
* const pubsubTopic = "/waku/2/default-waku/proto";
|
88
|
+
* const message = {
|
89
|
+
* payload: new Uint8Array([1, 2, 3, 4]),
|
90
|
+
* contentTopic: "/waku/2/default-content/proto",
|
91
|
+
* meta: new Uint8Array([5, 6, 7, 8]),
|
92
|
+
* timestamp: new Date()
|
93
|
+
* };
|
94
|
+
*
|
95
|
+
* const hashString = messageHashStr(pubsubTopic, message);
|
96
|
+
* console.log(hashString); // e.g. "a1b2c3d4..."
|
97
|
+
* ```
|
98
|
+
*/
|
99
|
+
export function messageHashStr(
|
100
|
+
pubsubTopic: string,
|
101
|
+
message: IProtoMessage | IDecodedMessage
|
102
|
+
): string {
|
103
|
+
const hash = messageHash(pubsubTopic, message);
|
104
|
+
const hashStr = bytesToHex(hash);
|
105
|
+
return hashStr;
|
106
|
+
}
|
@@ -16,21 +16,24 @@ import * as lp from "it-length-prefixed";
|
|
16
16
|
import { pipe } from "it-pipe";
|
17
17
|
import { Uint8ArrayList } from "uint8arraylist";
|
18
18
|
|
19
|
-
import {
|
19
|
+
import { StreamManager } from "../stream_manager/index.js";
|
20
20
|
|
21
21
|
const log = new Logger("metadata");
|
22
22
|
|
23
23
|
export const MetadataCodec = "/vac/waku/metadata/1.0.0";
|
24
24
|
|
25
|
-
class Metadata
|
26
|
-
private
|
25
|
+
class Metadata implements IMetadata {
|
26
|
+
private readonly streamManager: StreamManager;
|
27
|
+
private readonly libp2pComponents: Libp2pComponents;
|
27
28
|
protected handshakesConfirmed: Map<PeerIdStr, ShardInfo> = new Map();
|
28
29
|
|
30
|
+
public readonly multicodec = MetadataCodec;
|
31
|
+
|
29
32
|
public constructor(
|
30
33
|
public pubsubTopics: PubsubTopic[],
|
31
34
|
libp2p: Libp2pComponents
|
32
35
|
) {
|
33
|
-
|
36
|
+
this.streamManager = new StreamManager(MetadataCodec, libp2p);
|
34
37
|
this.libp2pComponents = libp2p;
|
35
38
|
void libp2p.registrar.handle(MetadataCodec, (streamData) => {
|
36
39
|
void this.onRequest(streamData);
|
@@ -55,7 +58,7 @@ class Metadata extends BaseProtocol implements IMetadata {
|
|
55
58
|
|
56
59
|
let stream;
|
57
60
|
try {
|
58
|
-
stream = await this.getStream(peerId);
|
61
|
+
stream = await this.streamManager.getStream(peerId);
|
59
62
|
} catch (error) {
|
60
63
|
log.error("Failed to get stream", error);
|
61
64
|
return {
|
package/src/lib/store/rpc.ts
CHANGED
@@ -28,22 +28,18 @@ export class StoreQueryRequest {
|
|
28
28
|
: undefined
|
29
29
|
});
|
30
30
|
|
31
|
-
// Validate request parameters based on RFC
|
32
31
|
const isHashQuery = params.messageHashes && params.messageHashes.length > 0;
|
33
32
|
const hasContentTopics =
|
34
33
|
params.contentTopics && params.contentTopics.length > 0;
|
35
34
|
const hasTimeFilter = params.timeStart || params.timeEnd;
|
36
35
|
|
37
36
|
if (isHashQuery) {
|
38
|
-
// Message hash lookup queries cannot include content topics or time filters
|
39
|
-
// but pubsubTopic is allowed/required
|
40
37
|
if (hasContentTopics || hasTimeFilter) {
|
41
38
|
throw new Error(
|
42
39
|
"Message hash lookup queries cannot include content filter criteria (contentTopics, timeStart, or timeEnd)"
|
43
40
|
);
|
44
41
|
}
|
45
42
|
} else {
|
46
|
-
// Content-filtered queries require both pubsubTopic and contentTopics to be set together
|
47
43
|
if (
|
48
44
|
(params.pubsubTopic &&
|
49
45
|
(!params.contentTopics || params.contentTopics.length === 0)) ||
|
package/src/lib/store/store.ts
CHANGED
@@ -2,7 +2,6 @@ import type { PeerId } from "@libp2p/interface";
|
|
2
2
|
import {
|
3
3
|
IDecodedMessage,
|
4
4
|
IDecoder,
|
5
|
-
IStoreCore,
|
6
5
|
Libp2p,
|
7
6
|
PubsubTopic,
|
8
7
|
QueryRequestParams
|
@@ -13,7 +12,7 @@ import * as lp from "it-length-prefixed";
|
|
13
12
|
import { pipe } from "it-pipe";
|
14
13
|
import { Uint8ArrayList } from "uint8arraylist";
|
15
14
|
|
16
|
-
import {
|
15
|
+
import { StreamManager } from "../stream_manager/index.js";
|
17
16
|
import { toProtoMessage } from "../to_proto_message.js";
|
18
17
|
|
19
18
|
import {
|
@@ -27,12 +26,16 @@ const log = new Logger("store");
|
|
27
26
|
|
28
27
|
export const StoreCodec = "/vac/waku/store-query/3.0.0";
|
29
28
|
|
30
|
-
export class StoreCore
|
29
|
+
export class StoreCore {
|
30
|
+
private readonly streamManager: StreamManager;
|
31
|
+
|
32
|
+
public readonly multicodec = StoreCodec;
|
33
|
+
|
31
34
|
public constructor(
|
32
35
|
public readonly pubsubTopics: PubsubTopic[],
|
33
36
|
libp2p: Libp2p
|
34
37
|
) {
|
35
|
-
|
38
|
+
this.streamManager = new StreamManager(StoreCodec, libp2p.components);
|
36
39
|
}
|
37
40
|
|
38
41
|
public async *queryPerPage<T extends IDecodedMessage>(
|
@@ -70,7 +73,7 @@ export class StoreCore extends BaseProtocol implements IStoreCore {
|
|
70
73
|
|
71
74
|
let stream;
|
72
75
|
try {
|
73
|
-
stream = await this.getStream(peerId);
|
76
|
+
stream = await this.streamManager.getStream(peerId);
|
74
77
|
} catch (e) {
|
75
78
|
log.error("Failed to get stream", e);
|
76
79
|
break;
|
@@ -1,5 +1,5 @@
|
|
1
1
|
import type { Peer, PeerId, PeerUpdate, Stream } from "@libp2p/interface";
|
2
|
-
import type {
|
2
|
+
import type { Libp2pComponents } from "@waku/interfaces";
|
3
3
|
import { Logger } from "@waku/utils";
|
4
4
|
|
5
5
|
import { selectOpenConnection } from "./utils.js";
|
@@ -14,11 +14,13 @@ export class StreamManager {
|
|
14
14
|
|
15
15
|
public constructor(
|
16
16
|
private multicodec: string,
|
17
|
-
private
|
18
|
-
private addEventListener: Libp2p["addEventListener"]
|
17
|
+
private readonly libp2p: Libp2pComponents
|
19
18
|
) {
|
20
19
|
this.log = new Logger(`stream-manager:${multicodec}`);
|
21
|
-
this.addEventListener(
|
20
|
+
this.libp2p.events.addEventListener(
|
21
|
+
"peer:update",
|
22
|
+
this.handlePeerUpdateStreamPool
|
23
|
+
);
|
22
24
|
}
|
23
25
|
|
24
26
|
public async getStream(peerId: PeerId): Promise<Stream> {
|
@@ -47,7 +49,7 @@ export class StreamManager {
|
|
47
49
|
}
|
48
50
|
|
49
51
|
private async createStream(peerId: PeerId, retries = 0): Promise<Stream> {
|
50
|
-
const connections = this.getConnections(peerId);
|
52
|
+
const connections = this.libp2p.connectionManager.getConnections(peerId);
|
51
53
|
const connection = selectOpenConnection(connections);
|
52
54
|
|
53
55
|
if (!connection) {
|
@@ -135,7 +137,7 @@ export class StreamManager {
|
|
135
137
|
}
|
136
138
|
|
137
139
|
private getOpenStreamForCodec(peerId: PeerId): Stream | undefined {
|
138
|
-
const connections = this.getConnections(peerId);
|
140
|
+
const connections = this.libp2p.connectionManager.getConnections(peerId);
|
139
141
|
const connection = selectOpenConnection(connections);
|
140
142
|
|
141
143
|
if (!connection) {
|
@@ -1,152 +0,0 @@
|
|
1
|
-
import { L as Logger } from './index-CTo1my9M.js';
|
2
|
-
|
3
|
-
function selectOpenConnection(connections) {
|
4
|
-
return connections
|
5
|
-
.filter((c) => c.status === "open")
|
6
|
-
.sort((left, right) => right.timeline.open - left.timeline.open)
|
7
|
-
.at(0);
|
8
|
-
}
|
9
|
-
|
10
|
-
const STREAM_LOCK_KEY = "consumed";
|
11
|
-
class StreamManager {
|
12
|
-
multicodec;
|
13
|
-
getConnections;
|
14
|
-
addEventListener;
|
15
|
-
log;
|
16
|
-
ongoingCreation = new Set();
|
17
|
-
streamPool = new Map();
|
18
|
-
constructor(multicodec, getConnections, addEventListener) {
|
19
|
-
this.multicodec = multicodec;
|
20
|
-
this.getConnections = getConnections;
|
21
|
-
this.addEventListener = addEventListener;
|
22
|
-
this.log = new Logger(`stream-manager:${multicodec}`);
|
23
|
-
this.addEventListener("peer:update", this.handlePeerUpdateStreamPool);
|
24
|
-
}
|
25
|
-
async getStream(peerId) {
|
26
|
-
const peerIdStr = peerId.toString();
|
27
|
-
const scheduledStream = this.streamPool.get(peerIdStr);
|
28
|
-
if (scheduledStream) {
|
29
|
-
this.streamPool.delete(peerIdStr);
|
30
|
-
await scheduledStream;
|
31
|
-
}
|
32
|
-
let stream = this.getOpenStreamForCodec(peerId);
|
33
|
-
if (stream) {
|
34
|
-
this.log.info(`Found existing stream peerId=${peerIdStr} multicodec=${this.multicodec}`);
|
35
|
-
this.lockStream(peerIdStr, stream);
|
36
|
-
return stream;
|
37
|
-
}
|
38
|
-
stream = await this.createStream(peerId);
|
39
|
-
this.lockStream(peerIdStr, stream);
|
40
|
-
return stream;
|
41
|
-
}
|
42
|
-
async createStream(peerId, retries = 0) {
|
43
|
-
const connections = this.getConnections(peerId);
|
44
|
-
const connection = selectOpenConnection(connections);
|
45
|
-
if (!connection) {
|
46
|
-
throw new Error(`Failed to get a connection to the peer peerId=${peerId.toString()} multicodec=${this.multicodec}`);
|
47
|
-
}
|
48
|
-
let lastError;
|
49
|
-
let stream;
|
50
|
-
for (let i = 0; i < retries + 1; i++) {
|
51
|
-
try {
|
52
|
-
this.log.info(`Attempting to create a stream for peerId=${peerId.toString()} multicodec=${this.multicodec}`);
|
53
|
-
stream = await connection.newStream(this.multicodec);
|
54
|
-
this.log.info(`Created stream for peerId=${peerId.toString()} multicodec=${this.multicodec}`);
|
55
|
-
break;
|
56
|
-
}
|
57
|
-
catch (error) {
|
58
|
-
lastError = error;
|
59
|
-
}
|
60
|
-
}
|
61
|
-
if (!stream) {
|
62
|
-
throw new Error(`Failed to create a new stream for ${peerId.toString()} -- ` + lastError);
|
63
|
-
}
|
64
|
-
return stream;
|
65
|
-
}
|
66
|
-
async createStreamWithLock(peer) {
|
67
|
-
const peerId = peer.id.toString();
|
68
|
-
if (this.ongoingCreation.has(peerId)) {
|
69
|
-
this.log.info(`Skipping creation of a stream due to lock for peerId=${peerId} multicodec=${this.multicodec}`);
|
70
|
-
return;
|
71
|
-
}
|
72
|
-
try {
|
73
|
-
this.ongoingCreation.add(peerId);
|
74
|
-
await this.createStream(peer.id);
|
75
|
-
}
|
76
|
-
catch (error) {
|
77
|
-
this.log.error(`Failed to createStreamWithLock:`, error);
|
78
|
-
}
|
79
|
-
finally {
|
80
|
-
this.ongoingCreation.delete(peerId);
|
81
|
-
}
|
82
|
-
return;
|
83
|
-
}
|
84
|
-
handlePeerUpdateStreamPool = (evt) => {
|
85
|
-
const { peer } = evt.detail;
|
86
|
-
if (!peer.protocols.includes(this.multicodec)) {
|
87
|
-
return;
|
88
|
-
}
|
89
|
-
const stream = this.getOpenStreamForCodec(peer.id);
|
90
|
-
if (stream) {
|
91
|
-
return;
|
92
|
-
}
|
93
|
-
this.scheduleNewStream(peer);
|
94
|
-
};
|
95
|
-
scheduleNewStream(peer) {
|
96
|
-
this.log.info(`Scheduling creation of a stream for peerId=${peer.id.toString()} multicodec=${this.multicodec}`);
|
97
|
-
// abandon previous attempt
|
98
|
-
if (this.streamPool.has(peer.id.toString())) {
|
99
|
-
this.streamPool.delete(peer.id.toString());
|
100
|
-
}
|
101
|
-
this.streamPool.set(peer.id.toString(), this.createStreamWithLock(peer));
|
102
|
-
}
|
103
|
-
getOpenStreamForCodec(peerId) {
|
104
|
-
const connections = this.getConnections(peerId);
|
105
|
-
const connection = selectOpenConnection(connections);
|
106
|
-
if (!connection) {
|
107
|
-
return;
|
108
|
-
}
|
109
|
-
const stream = connection.streams.find((s) => s.protocol === this.multicodec);
|
110
|
-
if (!stream) {
|
111
|
-
return;
|
112
|
-
}
|
113
|
-
const isStreamUnusable = ["done", "closed", "closing"].includes(stream.writeStatus || "");
|
114
|
-
if (isStreamUnusable || this.isStreamLocked(stream)) {
|
115
|
-
return;
|
116
|
-
}
|
117
|
-
return stream;
|
118
|
-
}
|
119
|
-
lockStream(peerId, stream) {
|
120
|
-
this.log.info(`Locking stream for peerId:${peerId}\tstreamId:${stream.id}`);
|
121
|
-
stream.metadata[STREAM_LOCK_KEY] = true;
|
122
|
-
}
|
123
|
-
isStreamLocked(stream) {
|
124
|
-
return !!stream.metadata[STREAM_LOCK_KEY];
|
125
|
-
}
|
126
|
-
}
|
127
|
-
|
128
|
-
/**
|
129
|
-
* A class with predefined helpers, to be used as a base to implement Waku
|
130
|
-
* Protocols.
|
131
|
-
*/
|
132
|
-
class BaseProtocol {
|
133
|
-
multicodec;
|
134
|
-
components;
|
135
|
-
pubsubTopics;
|
136
|
-
addLibp2pEventListener;
|
137
|
-
removeLibp2pEventListener;
|
138
|
-
streamManager;
|
139
|
-
constructor(multicodec, components, pubsubTopics) {
|
140
|
-
this.multicodec = multicodec;
|
141
|
-
this.components = components;
|
142
|
-
this.pubsubTopics = pubsubTopics;
|
143
|
-
this.addLibp2pEventListener = components.events.addEventListener.bind(components.events);
|
144
|
-
this.removeLibp2pEventListener = components.events.removeEventListener.bind(components.events);
|
145
|
-
this.streamManager = new StreamManager(multicodec, components.connectionManager.getConnections.bind(components.connectionManager), this.addLibp2pEventListener);
|
146
|
-
}
|
147
|
-
async getStream(peerId) {
|
148
|
-
return this.streamManager.getStream(peerId);
|
149
|
-
}
|
150
|
-
}
|
151
|
-
|
152
|
-
export { BaseProtocol as B, StreamManager as S };
|