From e6d3c2f595a2abf676305187e50f37ede672465a Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Mon, 28 Feb 2022 17:23:30 +1100 Subject: [PATCH] Improve count of relay peers Active relay peers are peer which are part of the gossip mesh. Which means that it's not just a peer we are connect to but a peer on subscribed to the same pubsub topic, with a good score, part of the mesh, etc. Mesh maintenance is done during the gossipsub hearbeat so it's the best time to review the count. A store peer is any peer we are connected to that support the store protocol, so it can be counted when a new peer is added to the store. This does not cater for store peers that disconnect, but we are not handling those just yet. --- examples/web-chat/src/Room.tsx | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/examples/web-chat/src/Room.tsx b/examples/web-chat/src/Room.tsx index fba77f5f71..f1255f48e9 100644 --- a/examples/web-chat/src/Room.tsx +++ b/examples/web-chat/src/Room.tsx @@ -7,7 +7,6 @@ import { TitleBar } from "@livechat/ui-kit"; import { Message } from "./Message"; import { ChatMessage } from "./chat_message"; import { useEffect, useState } from "react"; -import PeerId from "peer-id"; interface Props { messages: Message[]; @@ -18,41 +17,31 @@ interface Props { export default function Room(props: Props) { const { waku } = useWaku(); - const [peers, setPeers] = useState([]); const [storePeers, setStorePeers] = useState(0); const [relayPeers, setRelayPeers] = useState(0); useEffect(() => { - // Add a peer to the list every time a connection happen to ensure the stats update correctly if (!waku) return; - const addPeer = (event: { peerId: PeerId }) => { - setPeers((peers) => { - return [...peers, event.peerId]; - }); - }; - - waku.libp2p.peerStore.on("change:protocols", addPeer); - - return () => { - waku.libp2p.connectionManager.removeListener("change:protocols", addPeer); - }; + // Update relay peer count on heartbeat + waku.relay.on("gossipsub:heartbeat", () => { + setRelayPeers(waku.relay.getPeers().size); + }); }, [waku]); useEffect(() => { if (!waku) return; - setRelayPeers(waku.relay.getPeers().size); - - (async () => { + // Update store peer when new peer connected & identified + waku.libp2p.peerStore.on("change:protocols", async () => { let counter = 0; // eslint-disable-next-line @typescript-eslint/no-unused-vars for await (const _peer of waku.store.peers) { counter++; } setStorePeers(counter); - })(); - }, [waku, peers]); + }); + }, [waku]); return (