Skip to content

Commit

Permalink
feat: do not dial mdns discovered relayed addrs, cleanup code
Browse files Browse the repository at this point in the history
  • Loading branch information
fbozic committed Jun 6, 2024
1 parent 19491c9 commit f48a0f6
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 43 deletions.
13 changes: 5 additions & 8 deletions examples/chat/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,21 +162,18 @@ impl EventLoop {
swarm,
command_receiver,
event_sender,
// discovery_state: discovery::DiscoveryState::new(rendezvous_namespace, 0.5),
discovery: discovery::Discovery::new(discovery::DiscoveryConfig::new(
discovery::RendezvousConfig::new(
rendezvous_namespace,
Duration::from_secs(90),
0.5,
),
discovery: discovery::Discovery::new(discovery::RendezvousConfig::new(
rendezvous_namespace,
Duration::from_secs(90),
0.5,
)),
pending_dial: Default::default(),
}
}

pub(crate) async fn run(mut self) {
let mut rendezvous_discover_tick =
tokio::time::interval(self.discovery.config.rendezvous.discovery_interval);
tokio::time::interval(self.discovery.rendezvous_config.discovery_interval);

loop {
tokio::select! {
Expand Down
36 changes: 8 additions & 28 deletions examples/chat/src/network/discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,30 +9,19 @@ use super::EventLoop;

#[derive(Debug)]
pub struct Discovery {
pub config: DiscoveryConfig,
pub(crate) rendezvous_config: RendezvousConfig,
pub(crate) state: state::DiscoveryState,
}

impl Discovery {
pub(crate) fn new(config: DiscoveryConfig) -> Self {
pub(crate) fn new(rendezvous_config: RendezvousConfig) -> Self {
Discovery {
state: Default::default(),
config,
rendezvous_config,
}
}
}

#[derive(Debug)]
pub(crate) struct DiscoveryConfig {
pub rendezvous: RendezvousConfig,
}

impl DiscoveryConfig {
pub(crate) fn new(rendezvous: RendezvousConfig) -> Self {
DiscoveryConfig { rendezvous }
}
}

#[derive(Debug)]
pub struct RendezvousConfig {
pub namespace: rendezvous::Namespace,
Expand Down Expand Up @@ -102,7 +91,7 @@ impl EventLoop {
info.last_discovery_at().map_or(false, |instant| {
instant.elapsed()
> time::Duration::from_secs_f32(
60.0 / self.discovery.config.rendezvous.discovery_rpm,
60.0 / self.discovery.rendezvous_config.discovery_rpm,
)
})
});
Expand All @@ -115,7 +104,7 @@ impl EventLoop {

if !is_throttled {
self.swarm.behaviour_mut().rendezvous.discover(
Some(self.discovery.config.rendezvous.namespace.clone()),
Some(self.discovery.rendezvous_config.namespace.clone()),
peer_info
.rendezvous()
.and_then(|info| info.cookie())
Expand Down Expand Up @@ -172,7 +161,7 @@ impl EventLoop {
// This function expectes that the relay peer is already connected.
pub(crate) fn update_rendezvous_registration(&mut self, peer_id: &PeerId) -> eyre::Result<()> {
if let Err(err) = self.swarm.behaviour_mut().rendezvous.register(
self.discovery.config.rendezvous.namespace.clone(),
self.discovery.rendezvous_config.namespace.clone(),
*peer_id,
None,
) {
Expand All @@ -183,7 +172,7 @@ impl EventLoop {
}

debug!(
%peer_id, rendezvous_namespace=%(self.discovery.config.rendezvous.namespace),
%peer_id, rendezvous_namespace=%(self.discovery.rendezvous_config.namespace),
"Sent register request to rendezvous node"
);
Ok(())
Expand Down Expand Up @@ -220,16 +209,7 @@ impl EventLoop {
.get_preferred_addr()
.wrap_err("Failed to get preferred addr for relay peer")?;

let relayed_addr = match preferred_addr
.clone()
.with(multiaddr::Protocol::P2pCircuit)
.with_p2p(self.swarm.local_peer_id().clone())
{
Ok(addr) => addr,
Err(err) => {
eyre::bail!("Failed to construct relayed addr for relay peer: {:?}", err)
}
};
let relayed_addr = preferred_addr.clone().with(multiaddr::Protocol::P2pCircuit);
self.swarm.listen_on(relayed_addr)?;
self.discovery
.state
Expand Down
15 changes: 11 additions & 4 deletions examples/chat/src/network/events.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use tracing::{error, info};
use tracing::error;

use super::*;

Expand Down Expand Up @@ -83,19 +83,26 @@ impl EventLoop {
}
}
SwarmEvent::OutgoingConnectionError { peer_id, error, .. } => {
debug!("Outgoing connection error: {:?} {:?}", peer_id, error);
if let Some(peer_id) = peer_id {
if let Some(sender) = self.pending_dial.remove(&peer_id) {
let _ = sender.send(Err(eyre::eyre!(error)));
}
}
}
SwarmEvent::IncomingConnectionError { .. } => {}
SwarmEvent::IncomingConnectionError {
send_back_addr,
error,
..
} => {
debug!(?send_back_addr, %error, "Incoming connection error");
}
SwarmEvent::Dialing {
peer_id: Some(peer_id),
..
} => debug!("Dialing peer: {}", peer_id),
SwarmEvent::ExpiredListenAddr { address, .. } => {
trace!("Expired listen address: {}", address)
debug!("Expired listen address: {}", address)
}
SwarmEvent::ListenerClosed {
addresses, reason, ..
Expand All @@ -105,7 +112,7 @@ impl EventLoop {
trace!("New external address candidate: {}", address)
}
SwarmEvent::ExternalAddrConfirmed { address } => {
info!("External address confirmed: {}", address);
debug!("External address confirmed: {}", address);
if let Ok(relayed_addr) = RelayedMultiaddr::try_from(&address) {
self.discovery.state.update_relay_reservation_status(
&relayed_addr.relay_peer,
Expand Down
12 changes: 9 additions & 3 deletions examples/chat/src/network/events/mdns.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use libp2p::mdns;
use owo_colors::OwoColorize;
use tracing::{debug, error};
use tracing::{debug, error, info};

use super::{EventHandler, EventLoop};
use super::{EventHandler, EventLoop, RelayedMultiaddr};

impl EventHandler<mdns::Event> for EventLoop {
async fn handle(&mut self, event: mdns::Event) {
Expand All @@ -11,7 +11,13 @@ impl EventHandler<mdns::Event> for EventLoop {
match event {
mdns::Event::Discovered(peers) => {
for (peer_id, addr) in peers {
debug!(%peer_id, %addr, "Discovered peer via mdns");
if RelayedMultiaddr::try_from(&addr).is_ok() {
// Skip "fake" relayed addresses to avoid OutgoingConnectionError e.g.:
// /ip4/192.168.1.4/udp/4001/quic-v1/p2p/12D3KooWRnt7EmBwrNALhAXAgM151MdH7Ka9tvYS91ZUqnqwpjVg/p2p-circuit/p2p/12D3KooWSUpChB4mHmZNwVV26at6ZsRo25hNBHJRmPa8zfCeT41Y
continue;
}

info!(%peer_id, %addr, "Attempting to dial discovered peer via mdns");

if let Err(err) = self.swarm.dial(addr) {
error!("Failed to dial peer: {:?}", err);
Expand Down

0 comments on commit f48a0f6

Please sign in to comment.