Skip to content

Commit 7e89ac4

Browse files
add protocol implementation
1 parent 9b7a027 commit 7e89ac4

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed
+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import type { PeerId } from "@libp2p/interface/peer-id";
2+
import type {
3+
IMetadata,
4+
Libp2p,
5+
MetadataQueryParams,
6+
ShardInfo
7+
} from "@waku/interfaces";
8+
import { Logger } from "@waku/utils";
9+
import all from "it-all";
10+
import * as lp from "it-length-prefixed";
11+
import { pipe } from "it-pipe";
12+
import { Uint8ArrayList } from "uint8arraylist";
13+
14+
import { BaseProtocol } from "../base_protocol.js";
15+
16+
import { MetadataRpc } from "./rpc.js";
17+
18+
const log = new Logger("metadata");
19+
20+
export const MetadataCodec = "/vac/waku/metadata/1.0.0";
21+
22+
class Metadata extends BaseProtocol {
23+
constructor(libp2p: Libp2p) {
24+
super(MetadataCodec, libp2p.components);
25+
}
26+
27+
/**
28+
* Make a metadata query to a peer
29+
*/
30+
async query(params: MetadataQueryParams, peerId: PeerId): Promise<ShardInfo> {
31+
const rpcQuery = MetadataRpc.createRequest(params.clusterId, params.shards);
32+
33+
const peer = await this.getPeer(peerId);
34+
35+
const stream = await this.getStream(peer);
36+
37+
const res = await pipe(
38+
[rpcQuery.encode()],
39+
lp.encode,
40+
stream,
41+
lp.decode,
42+
async (source) => await all(source)
43+
);
44+
45+
try {
46+
const bytes = new Uint8ArrayList();
47+
res.forEach((chunk) => {
48+
bytes.append(chunk);
49+
});
50+
51+
const { response } = MetadataRpc.decode(bytes);
52+
if (!response) {
53+
throw new Error("No response in query");
54+
}
55+
56+
const { shards, clusterId } = response;
57+
return {
58+
cluster: clusterId,
59+
indexList: shards
60+
} as ShardInfo;
61+
} catch (e) {
62+
log.error(`Error decoding response: ${e}`);
63+
throw e;
64+
}
65+
}
66+
}
67+
68+
export function wakuMetadata(): (libp2p: Libp2p) => IMetadata {
69+
return (libp2p: Libp2p) => new Metadata(libp2p);
70+
}

0 commit comments

Comments
 (0)