From 24a151214dafcec4285936f3574dc785203b6281 Mon Sep 17 00:00:00 2001 From: Brian Ginsburg Date: Wed, 25 Oct 2023 11:17:15 -0700 Subject: [PATCH] refactor: Improve dialing after rendezvous discovery Only dial when we are not at connected peer limit. Only dial peers we are not already connected to. --- .../src/event_handler/swarm_event.rs | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/homestar-runtime/src/event_handler/swarm_event.rs b/homestar-runtime/src/event_handler/swarm_event.rs index 9ddac384..4e760fc1 100644 --- a/homestar-runtime/src/event_handler/swarm_event.rs +++ b/homestar-runtime/src/event_handler/swarm_event.rs @@ -28,7 +28,7 @@ use libp2p::{ }, mdns, multiaddr::Protocol, - rendezvous::{self, Namespace}, + rendezvous::{self, Namespace, Registration}, request_response, swarm::{dial_opts::DialOpts, SwarmEvent}, PeerId, StreamProtocol, @@ -190,17 +190,34 @@ async fn handle_swarm_event( registrations, cookie, } => { - // save cookie for later (when we are hungry for snacks again. yummy.) if cookie.namespace() == Some(&Namespace::from_static(RENDEZVOUS_NAMESPACE)) { + // Store cookie event_handler .rendezvous_cookies .insert(rendezvous_node, cookie); - // Dial discovered peers - for (index, registration) in registrations.iter().enumerate() { + let connected_peers_count = event_handler.connected_peers.len(); + + // Skip dialing peers if at connected peers limit + if connected_peers_count >= event_handler.connected_peers_limit as usize { + return; + } + + // Filter out already connected peers + let new_registrations: Vec<&Registration> = registrations + .iter() + .filter(|registration| { + !event_handler + .connected_peers + .contains_key(®istration.record.peer_id()) + }) + .collect(); + + // Dial newly discovered peers + for (index, registration) in new_registrations.iter().enumerate() { // Dial discovered peer if not us and not at connected peers limit if ®istration.record.peer_id() != event_handler.swarm.local_peer_id() - && event_handler.connected_peers.len() + index + && connected_peers_count + index < event_handler.connected_peers_limit as usize { // TODO: do anything with ttl here? @@ -221,7 +238,7 @@ async fn handle_swarm_event( } } } else { - // don't add peers that aren't from our namespace + // Do not dial peers that are not using our namespace warn!(peer_id=rendezvous_node.to_string(), namespace=?cookie.namespace(), "rendezvous peer gave records from an unexpected namespace"); } }