diff --git a/packages/core/src/lib/connection_manager.ts b/packages/core/src/lib/connection_manager.ts index 30e8f37dc9..293c5bb11f 100644 --- a/packages/core/src/lib/connection_manager.ts +++ b/packages/core/src/lib/connection_manager.ts @@ -116,11 +116,7 @@ export class ConnectionManager ...options }; - this.keepAliveManager = new KeepAliveManager( - libp2p.peerStore, - keepAliveOptions, - relay - ); + this.keepAliveManager = new KeepAliveManager(keepAliveOptions, relay); this.run() .then(() => log(`Connection Manager is now running`)) @@ -344,7 +340,11 @@ export class ConnectionManager void (async () => { const peerId = evt.detail; - this.keepAliveManager.start(peerId, this.libp2p.services.ping); + this.keepAliveManager.start( + peerId, + this.libp2p.services.ping, + this.libp2p.peerStore + ); const isBootstrap = (await this.getTagNamesForPeer(peerId)).includes( Tags.BOOTSTRAP diff --git a/packages/core/src/lib/keep_alive_manager.ts b/packages/core/src/lib/keep_alive_manager.ts index 5810371c90..1103e46487 100644 --- a/packages/core/src/lib/keep_alive_manager.ts +++ b/packages/core/src/lib/keep_alive_manager.ts @@ -16,17 +16,19 @@ export class KeepAliveManager { private relayKeepAliveTimers: Map>; private options: KeepAliveOptions; private relay?: IRelay; - private peerStore: PeerStore; - constructor(peerStore: PeerStore, options: KeepAliveOptions, relay?: IRelay) { + constructor(options: KeepAliveOptions, relay?: IRelay) { this.pingKeepAliveTimers = new Map(); this.relayKeepAliveTimers = new Map(); this.options = options; this.relay = relay; - this.peerStore = peerStore; } - public start(peerId: PeerId, libp2pPing: PingService): void { + public start( + peerId: PeerId, + libp2pPing: PingService, + peerStore: PeerStore + ): void { // Just in case a timer already exists for this peer this.stop(peerId); @@ -37,11 +39,13 @@ export class KeepAliveManager { if (pingPeriodSecs !== 0) { const interval = setInterval(() => { + // ping the peer for keep alive + // also update the peer store with the latency libp2pPing .ping(peerId) .then((ping) => { log(`Ping succeeded (${peerIdStr})`, ping); - this.peerStore + peerStore .patch(peerId, { metadata: { ping: utf8ToBytes(ping.toString()) diff --git a/packages/utils/src/libp2p/index.ts b/packages/utils/src/libp2p/index.ts index 3b3d6d14da..6c1019b8b7 100644 --- a/packages/utils/src/libp2p/index.ts +++ b/packages/utils/src/libp2p/index.ts @@ -20,7 +20,7 @@ export function selectRandomPeer(peers: Peer[]): Peer | undefined { /** * Returns the peer with the lowest latency. - * @param getPing - A function that returns the latency for a given peer + * @param peerStore - The Libp2p PeerStore * @param peers - The list of peers to choose from * @returns The peer with the lowest latency, or undefined if no peer could be reached */