From bdf9209824e364bb4e4047f7a32de45479d997e8 Mon Sep 17 00:00:00 2001 From: Thomas Eizinger Date: Thu, 6 Oct 2022 03:50:11 +1100 Subject: [PATCH] swarm: Split off "keep alive" functionality from `DummyConnectionHandler` (#2859) Previously, the `DummyConnectionHandler` offered a "keep alive" functionality, i.e. it allowed users to set the value of what is returned from `ConnectionHandler::keep_alive`. This handler is primarily used in tests or `NetworkBehaviour`s that don't open any connections (like mDNS). In all of these cases, it is statically known whether we want to keep connections alive. As such, this functionality is better represented by a static `KeepAliveConnectionHandler` that always returns `KeepAlive::Yes` and a `DummyConnectionHandler` that always returns `KeepAlive::No`. To follow the naming conventions described in https://github.com/libp2p/rust-libp2p/issues/2217, we introduce a top-level `keep_alive` and `dummy` behaviour in `libp2p-swarm` that contains both the `NetworkBehaviour` and `ConnectionHandler` implementation for either case. --- examples/ping.rs | 22 ++-- misc/metrics/CHANGELOG.md | 4 +- misc/metrics/examples/metrics/main.rs | 22 +++- misc/multistream-select/tests/transport.rs | 6 +- protocols/dcutr/src/handler.rs | 6 +- protocols/mdns/src/behaviour.rs | 9 +- protocols/ping/CHANGELOG.md | 3 + protocols/ping/src/handler.rs | 4 + protocols/ping/tests/ping.rs | 84 +++++++----- protocols/relay/src/v2/client.rs | 4 +- protocols/relay/src/v2/client/handler.rs | 12 +- protocols/relay/src/v2/relay.rs | 9 +- protocols/relay/src/v2/relay/handler.rs | 10 +- protocols/rendezvous/examples/discover.rs | 17 ++- .../examples/register_with_identify.rs | 17 ++- .../rendezvous/examples/rendezvous_point.rs | 13 +- swarm-derive/tests/test.rs | 7 +- swarm/CHANGELOG.md | 5 + swarm/src/behaviour.rs | 4 +- swarm/src/behaviour/toggle.rs | 4 +- swarm/src/connection.rs | 6 +- swarm/src/dummy.rs | 104 +++++++++++++++ swarm/src/handler.rs | 2 - swarm/src/handler/dummy.rs | 117 ----------------- swarm/src/keep_alive.rs | 119 +++++++++++++++++ swarm/src/lib.rs | 121 ++++-------------- 26 files changed, 412 insertions(+), 319 deletions(-) create mode 100644 swarm/src/dummy.rs delete mode 100644 swarm/src/handler/dummy.rs create mode 100644 swarm/src/keep_alive.rs diff --git a/examples/ping.rs b/examples/ping.rs index 26223459bfa..3919bfd41db 100644 --- a/examples/ping.rs +++ b/examples/ping.rs @@ -42,7 +42,8 @@ use futures::prelude::*; use libp2p::swarm::{Swarm, SwarmEvent}; -use libp2p::{identity, ping, Multiaddr, PeerId}; +use libp2p::{identity, ping, Multiaddr, NetworkBehaviour, PeerId}; +use libp2p_swarm::keep_alive; use std::error::Error; #[async_std::main] @@ -53,14 +54,7 @@ async fn main() -> Result<(), Box> { let transport = libp2p::development_transport(local_key).await?; - // Create a ping network behaviour. - // - // For illustrative purposes, the ping protocol is configured to - // keep the connection alive, so a continuous sequence of pings - // can be observed. - let behaviour = ping::Behaviour::new(ping::Config::new().with_keep_alive(true)); - - let mut swarm = Swarm::new(transport, behaviour, local_peer_id); + let mut swarm = Swarm::new(transport, Behaviour::default(), local_peer_id); // Tell the swarm to listen on all interfaces and a random, OS-assigned // port. @@ -82,3 +76,13 @@ async fn main() -> Result<(), Box> { } } } + +/// Our network behaviour. +/// +/// For illustrative purposes, this includes the [`KeepAlive`](behaviour::KeepAlive) behaviour so a continuous sequence of +/// pings can be observed. +#[derive(NetworkBehaviour, Default)] +struct Behaviour { + keep_alive: keep_alive::Behaviour, + ping: ping::Behaviour, +} diff --git a/misc/metrics/CHANGELOG.md b/misc/metrics/CHANGELOG.md index fdf6806f0b1..fe428745d70 100644 --- a/misc/metrics/CHANGELOG.md +++ b/misc/metrics/CHANGELOG.md @@ -1,7 +1,5 @@ # 0.10.0 [unreleased] -- Update to `libp2p-kad` `v0.41.0`. - - Update to `libp2p-swarm` `v0.40.0`. - Update to `libp2p-dcutr` `v0.7.0`. @@ -12,6 +10,8 @@ - Update to `libp2p-relay` `v0.13.0`. +- Update to `libp2p-kad` `v0.41.0`. + - Update to `libp2p-core` `v0.37.0`. - Update to `libp2p-gossipsub` `v0.42.0`. diff --git a/misc/metrics/examples/metrics/main.rs b/misc/metrics/examples/metrics/main.rs index 51b0df8c2a4..0307e32dc1e 100644 --- a/misc/metrics/examples/metrics/main.rs +++ b/misc/metrics/examples/metrics/main.rs @@ -48,19 +48,19 @@ //! You should see a long list of metrics printed to the terminal. Check the //! `libp2p_ping` metrics, they should be `>0`. +use env_logger::Env; use futures::executor::block_on; use futures::stream::StreamExt; use libp2p::core::Multiaddr; use libp2p::metrics::{Metrics, Recorder}; -use libp2p::ping; use libp2p::swarm::SwarmEvent; -use libp2p::{identity, PeerId, Swarm}; +use libp2p::{identity, ping, NetworkBehaviour, PeerId, Swarm}; +use libp2p_swarm::keep_alive; +use log::info; use prometheus_client::registry::Registry; use std::error::Error; use std::thread; -use env_logger::Env; -use log::info; mod http_service; fn main() -> Result<(), Box> { @@ -72,7 +72,7 @@ fn main() -> Result<(), Box> { let mut swarm = Swarm::new( block_on(libp2p::development_transport(local_key))?, - ping::Behaviour::new(ping::Config::new().with_keep_alive(true)), + Behaviour::default(), local_peer_id, ); @@ -91,7 +91,7 @@ fn main() -> Result<(), Box> { block_on(async { loop { match swarm.select_next_some().await { - SwarmEvent::Behaviour(ping_event) => { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping_event)) => { info!("{:?}", ping_event); metrics.record(&ping_event); } @@ -104,3 +104,13 @@ fn main() -> Result<(), Box> { }); Ok(()) } + +/// Our network behaviour. +/// +/// For illustrative purposes, this includes the [`keep_alive::Behaviour`]) behaviour so the ping actually happen +/// and can be observed via the metrics. +#[derive(NetworkBehaviour, Default)] +struct Behaviour { + keep_alive: keep_alive::Behaviour, + ping: ping::Behaviour, +} diff --git a/misc/multistream-select/tests/transport.rs b/misc/multistream-select/tests/transport.rs index 7c9680ab893..bf5dd247b40 100644 --- a/misc/multistream-select/tests/transport.rs +++ b/misc/multistream-select/tests/transport.rs @@ -28,7 +28,7 @@ use libp2p::core::{ }; use libp2p::mplex::MplexConfig; use libp2p::plaintext::PlainText2Config; -use libp2p::swarm::{DummyBehaviour, Swarm, SwarmEvent}; +use libp2p::swarm::{dummy, Swarm, SwarmEvent}; use rand::random; use std::task::Poll; @@ -61,8 +61,8 @@ fn transport_upgrade() { let listen_addr = Multiaddr::from(Protocol::Memory(random::())); - let mut dialer = Swarm::new(dialer_transport, DummyBehaviour::default(), dialer_id); - let mut listener = Swarm::new(listener_transport, DummyBehaviour::default(), listener_id); + let mut dialer = Swarm::new(dialer_transport, dummy::Behaviour, dialer_id); + let mut listener = Swarm::new(listener_transport, dummy::Behaviour, listener_id); listener.listen_on(listen_addr).unwrap(); let (addr_sender, addr_receiver) = oneshot::channel(); diff --git a/protocols/dcutr/src/handler.rs b/protocols/dcutr/src/handler.rs index 12eb8f4097a..e854b395308 100644 --- a/protocols/dcutr/src/handler.rs +++ b/protocols/dcutr/src/handler.rs @@ -23,7 +23,7 @@ use either::Either; use libp2p_core::connection::ConnectionId; use libp2p_core::upgrade::{self, DeniedUpgrade}; use libp2p_core::{ConnectedPoint, PeerId}; -use libp2p_swarm::handler::DummyConnectionHandler; +use libp2p_swarm::dummy; use libp2p_swarm::handler::SendWrapper; use libp2p_swarm::{ConnectionHandler, IntoConnectionHandler}; @@ -44,7 +44,7 @@ pub enum Role { } impl IntoConnectionHandler for Prototype { - type Handler = Either>; + type Handler = Either>; fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { match self { @@ -52,7 +52,7 @@ impl IntoConnectionHandler for Prototype { if endpoint.is_relayed() { Either::Left(relayed::Handler::new(endpoint.clone())) } else { - Either::Right(Either::Right(DummyConnectionHandler::default())) + Either::Right(Either::Right(dummy::ConnectionHandler)) } } Self::DirectConnection { diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index d645468ed5c..e6c7e67981a 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -31,8 +31,7 @@ use if_watch::{IfEvent, IfWatcher}; use libp2p_core::transport::ListenerId; use libp2p_core::{Multiaddr, PeerId}; use libp2p_swarm::{ - handler::DummyConnectionHandler, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, - PollParameters, + dummy, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, }; use smallvec::SmallVec; use std::collections::hash_map::{Entry, HashMap}; @@ -120,11 +119,11 @@ where T: Builder + Stream, S: AsyncSocket, { - type ConnectionHandler = DummyConnectionHandler; + type ConnectionHandler = dummy::ConnectionHandler; type OutEvent = MdnsEvent; fn new_handler(&mut self) -> Self::ConnectionHandler { - DummyConnectionHandler::default() + dummy::ConnectionHandler } fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec { @@ -168,7 +167,7 @@ where &mut self, cx: &mut Context<'_>, params: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { // Poll ifwatch. while let Poll::Ready(event) = Pin::new(&mut self.if_watch).poll(cx) { match event { diff --git a/protocols/ping/CHANGELOG.md b/protocols/ping/CHANGELOG.md index 1ea4f4ab21b..923dfa48c84 100644 --- a/protocols/ping/CHANGELOG.md +++ b/protocols/ping/CHANGELOG.md @@ -8,8 +8,11 @@ - Update to `libp2p-swarm` `v0.40.0`. +- Deprecate `Config::with_keep_alive`. See [PR 2859]. + [PR 2857]: https://github.com/libp2p/rust-libp2p/pull/2857 [PR 2937]: https://github.com/libp2p/rust-libp2p/pull/2937 +[PR 2859]: https://github.com/libp2p/rust-libp2p/pull/2859/ # 0.39.0 diff --git a/protocols/ping/src/handler.rs b/protocols/ping/src/handler.rs index d2176434c58..af1ef898981 100644 --- a/protocols/ping/src/handler.rs +++ b/protocols/ping/src/handler.rs @@ -111,6 +111,10 @@ impl Config { /// If the maximum number of allowed ping failures is reached, the /// connection is always terminated as a result of [`ConnectionHandler::poll`] /// returning an error, regardless of the keep-alive setting. + #[deprecated( + since = "0.40.0", + note = "Use `libp2p::swarm::behaviour::KeepAlive` if you need to keep connections alive unconditionally." + )] pub fn with_keep_alive(mut self, b: bool) -> Self { self.keep_alive = b; self diff --git a/protocols/ping/tests/ping.rs b/protocols/ping/tests/ping.rs index a9df0874b73..e489f90c254 100644 --- a/protocols/ping/tests/ping.rs +++ b/protocols/ping/tests/ping.rs @@ -30,24 +30,24 @@ use libp2p::core::{ use libp2p::mplex; use libp2p::noise; use libp2p::ping; -use libp2p::swarm::{DummyBehaviour, KeepAlive, Swarm, SwarmEvent}; +use libp2p::swarm::{Swarm, SwarmEvent}; use libp2p::tcp::{GenTcpConfig, TcpTransport}; use libp2p::yamux; +use libp2p::NetworkBehaviour; +use libp2p_swarm::keep_alive; use quickcheck::*; use std::{num::NonZeroU8, time::Duration}; #[test] fn ping_pong() { fn prop(count: NonZeroU8, muxer: MuxerChoice) { - let cfg = ping::Config::new() - .with_keep_alive(true) - .with_interval(Duration::from_millis(10)); + let cfg = ping::Config::new().with_interval(Duration::from_millis(10)); let (peer1_id, trans) = mk_transport(muxer); - let mut swarm1 = Swarm::new(trans, ping::Behaviour::new(cfg.clone()), peer1_id); + let mut swarm1 = Swarm::new(trans, Behaviour::new(cfg.clone()), peer1_id); let (peer2_id, trans) = mk_transport(muxer); - let mut swarm2 = Swarm::new(trans, ping::Behaviour::new(cfg), peer2_id); + let mut swarm2 = Swarm::new(trans, Behaviour::new(cfg), peer2_id); let (mut tx, mut rx) = mpsc::channel::(1); @@ -62,16 +62,19 @@ fn ping_pong() { loop { match swarm1.select_next_some().await { SwarmEvent::NewListenAddr { address, .. } => tx.send(address).await.unwrap(), - SwarmEvent::Behaviour(ping::Event { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { peer, result: Ok(ping::Success::Ping { rtt }), - }) => { + })) => { count1 -= 1; if count1 == 0 { return (pid1, peer, rtt); } } - SwarmEvent::Behaviour(ping::Event { result: Err(e), .. }) => { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { + result: Err(e), + .. + })) => { panic!("Ping failure: {:?}", e) } _ => {} @@ -85,16 +88,19 @@ fn ping_pong() { loop { match swarm2.select_next_some().await { - SwarmEvent::Behaviour(ping::Event { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { peer, result: Ok(ping::Success::Ping { rtt }), - }) => { + })) => { count2 -= 1; if count2 == 0 { return (pid2, peer, rtt); } } - SwarmEvent::Behaviour(ping::Event { result: Err(e), .. }) => { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { + result: Err(e), + .. + })) => { panic!("Ping failure: {:?}", e) } _ => {} @@ -117,16 +123,15 @@ fn ping_pong() { fn max_failures() { fn prop(max_failures: NonZeroU8, muxer: MuxerChoice) { let cfg = ping::Config::new() - .with_keep_alive(true) .with_interval(Duration::from_millis(10)) .with_timeout(Duration::from_millis(0)) .with_max_failures(max_failures.into()); let (peer1_id, trans) = mk_transport(muxer); - let mut swarm1 = Swarm::new(trans, ping::Behaviour::new(cfg.clone()), peer1_id); + let mut swarm1 = Swarm::new(trans, Behaviour::new(cfg.clone()), peer1_id); let (peer2_id, trans) = mk_transport(muxer); - let mut swarm2 = Swarm::new(trans, ping::Behaviour::new(cfg), peer2_id); + let mut swarm2 = Swarm::new(trans, Behaviour::new(cfg), peer2_id); let (mut tx, mut rx) = mpsc::channel::(1); @@ -139,13 +144,16 @@ fn max_failures() { loop { match swarm1.select_next_some().await { SwarmEvent::NewListenAddr { address, .. } => tx.send(address).await.unwrap(), - SwarmEvent::Behaviour(ping::Event { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { result: Ok(ping::Success::Ping { .. }), .. - }) => { + })) => { count1 = 0; // there may be an occasional success } - SwarmEvent::Behaviour(ping::Event { result: Err(_), .. }) => { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { + result: Err(_), + .. + })) => { count1 += 1; } SwarmEvent::ConnectionClosed { .. } => return count1, @@ -161,13 +169,16 @@ fn max_failures() { loop { match swarm2.select_next_some().await { - SwarmEvent::Behaviour(ping::Event { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { result: Ok(ping::Success::Ping { .. }), .. - }) => { + })) => { count2 = 0; // there may be an occasional success } - SwarmEvent::Behaviour(ping::Event { result: Err(_), .. }) => { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { + result: Err(_), + .. + })) => { count2 += 1; } SwarmEvent::ConnectionClosed { .. } => return count2, @@ -187,18 +198,10 @@ fn max_failures() { #[test] fn unsupported_doesnt_fail() { let (peer1_id, trans) = mk_transport(MuxerChoice::Mplex); - let mut swarm1 = Swarm::new( - trans, - DummyBehaviour::with_keep_alive(KeepAlive::Yes), - peer1_id, - ); + let mut swarm1 = Swarm::new(trans, keep_alive::Behaviour, peer1_id); let (peer2_id, trans) = mk_transport(MuxerChoice::Mplex); - let mut swarm2 = Swarm::new( - trans, - ping::Behaviour::new(ping::Config::new().with_keep_alive(true)), - peer2_id, - ); + let mut swarm2 = Swarm::new(trans, Behaviour::default(), peer2_id); let (mut tx, mut rx) = mpsc::channel::(1); @@ -218,10 +221,10 @@ fn unsupported_doesnt_fail() { loop { match swarm2.select_next_some().await { - SwarmEvent::Behaviour(ping::Event { + SwarmEvent::Behaviour(BehaviourEvent::Ping(ping::Event { result: Err(ping::Failure::Unsupported), .. - }) => { + })) => { swarm2.disconnect_peer_id(peer1_id).unwrap(); } SwarmEvent::ConnectionClosed { cause: Some(e), .. } => { @@ -265,3 +268,18 @@ impl Arbitrary for MuxerChoice { *g.choose(&[MuxerChoice::Mplex, MuxerChoice::Yamux]).unwrap() } } + +#[derive(NetworkBehaviour, Default)] +struct Behaviour { + keep_alive: keep_alive::Behaviour, + ping: ping::Behaviour, +} + +impl Behaviour { + fn new(config: ping::Config) -> Self { + Self { + keep_alive: keep_alive::Behaviour, + ping: ping::Behaviour::new(config), + } + } +} diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index d039cd08cbd..68e69e20a28 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -35,7 +35,7 @@ use futures::stream::StreamExt; use libp2p_core::connection::{ConnectedPoint, ConnectionId}; use libp2p_core::{Multiaddr, PeerId}; use libp2p_swarm::dial_opts::DialOpts; -use libp2p_swarm::handler::DummyConnectionHandler; +use libp2p_swarm::dummy; use libp2p_swarm::{ ConnectionHandlerUpgrErr, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, @@ -144,7 +144,7 @@ impl NetworkBehaviour for Client { peer_id: &PeerId, connection_id: &ConnectionId, endpoint: &ConnectedPoint, - _handler: Either, + _handler: Either, _remaining_established: usize, ) { if !endpoint.is_relayed() { diff --git a/protocols/relay/src/v2/client/handler.rs b/protocols/relay/src/v2/client/handler.rs index c0e2172329d..a346a4eaeb3 100644 --- a/protocols/relay/src/v2/client/handler.rs +++ b/protocols/relay/src/v2/client/handler.rs @@ -31,12 +31,10 @@ use instant::Instant; use libp2p_core::either::EitherError; use libp2p_core::multiaddr::Protocol; use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId}; -use libp2p_swarm::handler::{ - DummyConnectionHandler, InboundUpgradeSend, OutboundUpgradeSend, SendWrapper, -}; +use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; use libp2p_swarm::{ - ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, - KeepAlive, NegotiatedSubstream, SubstreamProtocol, + dummy, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, + IntoConnectionHandler, KeepAlive, NegotiatedSubstream, SubstreamProtocol, }; use log::debug; use std::collections::{HashMap, VecDeque}; @@ -125,7 +123,7 @@ impl Prototype { } impl IntoConnectionHandler for Prototype { - type Handler = Either; + type Handler = Either; fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { if endpoint.is_relayed() { @@ -138,7 +136,7 @@ impl IntoConnectionHandler for Prototype { } // Deny all substreams on relayed connection. - Either::Right(DummyConnectionHandler::default()) + Either::Right(dummy::ConnectionHandler) } else { let mut handler = Handler { remote_peer_id: *remote_peer_id, diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index ed5fe6ca326..5b1eb810f60 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -30,9 +30,8 @@ use instant::Instant; use libp2p_core::connection::{ConnectedPoint, ConnectionId}; use libp2p_core::multiaddr::Protocol; use libp2p_core::PeerId; -use libp2p_swarm::handler::DummyConnectionHandler; use libp2p_swarm::{ - ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + dummy, ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use std::collections::{hash_map, HashMap, HashSet, VecDeque}; @@ -234,7 +233,7 @@ impl NetworkBehaviour for Relay { peer: &PeerId, connection: &ConnectionId, _: &ConnectedPoint, - _handler: Either, + _handler: Either, _remaining_established: usize, ) { if let hash_map::Entry::Occupied(mut peer) = self.reservations.entry(*peer) { @@ -283,7 +282,7 @@ impl NetworkBehaviour for Relay { assert!( !endpoint.is_relayed(), - "`DummyConnectionHandler` handles relayed connections. It \ + "`dummy::ConnectionHandler` handles relayed connections. It \ denies all inbound substreams." ); @@ -410,7 +409,7 @@ impl NetworkBehaviour for Relay { assert!( !endpoint.is_relayed(), - "`DummyConnectionHandler` handles relayed connections. It \ + "`dummy::ConnectionHandler` handles relayed connections. It \ denies all inbound substreams." ); diff --git a/protocols/relay/src/v2/relay/handler.rs b/protocols/relay/src/v2/relay/handler.rs index 9801ca74b43..1c6987692fa 100644 --- a/protocols/relay/src/v2/relay/handler.rs +++ b/protocols/relay/src/v2/relay/handler.rs @@ -33,11 +33,11 @@ use instant::Instant; use libp2p_core::connection::ConnectionId; use libp2p_core::either::EitherError; use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId}; -use libp2p_swarm::handler::{DummyConnectionHandler, SendWrapper}; +use libp2p_swarm::handler::SendWrapper; use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_swarm::{ - ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, - KeepAlive, NegotiatedSubstream, SubstreamProtocol, + dummy, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, + IntoConnectionHandler, KeepAlive, NegotiatedSubstream, SubstreamProtocol, }; use std::collections::VecDeque; use std::fmt; @@ -342,12 +342,12 @@ pub struct Prototype { } impl IntoConnectionHandler for Prototype { - type Handler = Either; + type Handler = Either; fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { if endpoint.is_relayed() { // Deny all substreams on relayed connection. - Either::Right(DummyConnectionHandler::default()) + Either::Right(dummy::ConnectionHandler) } else { Either::Left(Handler { endpoint: endpoint.clone(), diff --git a/protocols/rendezvous/examples/discover.rs b/protocols/rendezvous/examples/discover.rs index 1c9e90208f4..c14e114ee88 100644 --- a/protocols/rendezvous/examples/discover.rs +++ b/protocols/rendezvous/examples/discover.rs @@ -23,10 +23,11 @@ use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::multiaddr::Protocol; use libp2p::ping; -use libp2p::swarm::SwarmEvent; +use libp2p::swarm::{keep_alive, SwarmEvent}; use libp2p::Swarm; use libp2p::{development_transport, rendezvous, Multiaddr}; use std::time::Duration; +use void::Void; const NAMESPACE: &str = "rendezvous"; @@ -44,11 +45,8 @@ async fn main() { development_transport(identity.clone()).await.unwrap(), MyBehaviour { rendezvous: rendezvous::client::Behaviour::new(identity.clone()), - ping: ping::Behaviour::new( - ping::Config::new() - .with_interval(Duration::from_secs(1)) - .with_keep_alive(true), - ), + ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))), + keep_alive: keep_alive::Behaviour, }, PeerId::from(identity.public()), ); @@ -139,10 +137,17 @@ impl From for MyEvent { } } +impl From for MyEvent { + fn from(event: Void) -> Self { + void::unreachable(event) + } +} + #[derive(libp2p::NetworkBehaviour)] #[behaviour(event_process = false)] #[behaviour(out_event = "MyEvent")] struct MyBehaviour { rendezvous: rendezvous::client::Behaviour, ping: ping::Behaviour, + keep_alive: keep_alive::Behaviour, } diff --git a/protocols/rendezvous/examples/register_with_identify.rs b/protocols/rendezvous/examples/register_with_identify.rs index 5c4acf1cf2f..f12a1a6ed98 100644 --- a/protocols/rendezvous/examples/register_with_identify.rs +++ b/protocols/rendezvous/examples/register_with_identify.rs @@ -23,10 +23,11 @@ use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::identify; use libp2p::ping; -use libp2p::swarm::{Swarm, SwarmEvent}; +use libp2p::swarm::{keep_alive, Swarm, SwarmEvent}; use libp2p::{development_transport, rendezvous}; use libp2p::{Multiaddr, NetworkBehaviour}; use std::time::Duration; +use void::Void; #[tokio::main] async fn main() { @@ -47,11 +48,8 @@ async fn main() { identity.public(), )), rendezvous: rendezvous::client::Behaviour::new(identity.clone()), - ping: ping::Behaviour::new( - ping::Config::new() - .with_interval(Duration::from_secs(1)) - .with_keep_alive(true), - ), + ping: ping::Behaviour::new(ping::Config::new().with_interval(Duration::from_secs(1))), + keep_alive: keep_alive::Behaviour, }, PeerId::from(identity.public()), ); @@ -139,6 +137,12 @@ impl From for MyEvent { } } +impl From for MyEvent { + fn from(event: Void) -> Self { + void::unreachable(event) + } +} + #[derive(NetworkBehaviour)] #[behaviour(event_process = false)] #[behaviour(out_event = "MyEvent")] @@ -146,4 +150,5 @@ struct MyBehaviour { identify: identify::Behaviour, rendezvous: rendezvous::client::Behaviour, ping: ping::Behaviour, + keep_alive: keep_alive::Behaviour, } diff --git a/protocols/rendezvous/examples/rendezvous_point.rs b/protocols/rendezvous/examples/rendezvous_point.rs index 0b822b9d95a..980a3a6fd5d 100644 --- a/protocols/rendezvous/examples/rendezvous_point.rs +++ b/protocols/rendezvous/examples/rendezvous_point.rs @@ -23,9 +23,10 @@ use libp2p::core::identity; use libp2p::core::PeerId; use libp2p::identify; use libp2p::ping; -use libp2p::swarm::{Swarm, SwarmEvent}; +use libp2p::swarm::{keep_alive, Swarm, SwarmEvent}; use libp2p::NetworkBehaviour; use libp2p::{development_transport, rendezvous}; +use void::Void; /// Examples for the rendezvous protocol: /// @@ -51,7 +52,8 @@ async fn main() { identity.public(), )), rendezvous: rendezvous::server::Behaviour::new(rendezvous::server::Config::default()), - ping: ping::Behaviour::new(ping::Config::new().with_keep_alive(true)), + ping: ping::Behaviour::new(ping::Config::new()), + keep_alive: keep_alive::Behaviour, }, PeerId::from(identity.public()), ); @@ -123,6 +125,12 @@ impl From for MyEvent { } } +impl From for MyEvent { + fn from(event: Void) -> Self { + void::unreachable(event) + } +} + #[derive(NetworkBehaviour)] #[behaviour(event_process = false)] #[behaviour(out_event = "MyEvent")] @@ -130,4 +138,5 @@ struct MyBehaviour { identify: identify::Behaviour, rendezvous: rendezvous::server::Behaviour, ping: ping::Behaviour, + keep_alive: keep_alive::Behaviour, } diff --git a/swarm-derive/tests/test.rs b/swarm-derive/tests/test.rs index bc6fc3c72a4..2404ef699ca 100644 --- a/swarm-derive/tests/test.rs +++ b/swarm-derive/tests/test.rs @@ -19,7 +19,7 @@ // DEALINGS IN THE SOFTWARE. use futures::prelude::*; -use libp2p::swarm::{NetworkBehaviour, SwarmEvent}; +use libp2p::swarm::{dummy, NetworkBehaviour, SwarmEvent}; use libp2p::{identify, ping}; use libp2p_swarm_derive::*; use std::fmt::Debug; @@ -354,7 +354,6 @@ fn generated_out_event_derive_debug() { #[test] fn custom_out_event_no_type_parameters() { use libp2p::core::connection::ConnectionId; - use libp2p::swarm::handler::DummyConnectionHandler; use libp2p::swarm::{ ConnectionHandler, IntoConnectionHandler, NetworkBehaviourAction, PollParameters, }; @@ -367,11 +366,11 @@ fn custom_out_event_no_type_parameters() { } impl NetworkBehaviour for TemplatedBehaviour { - type ConnectionHandler = DummyConnectionHandler; + type ConnectionHandler = dummy::ConnectionHandler; type OutEvent = void::Void; fn new_handler(&mut self) -> Self::ConnectionHandler { - DummyConnectionHandler::default() + dummy::ConnectionHandler } fn inject_event( diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 15a12eece13..ec7b8e83d4f 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -4,7 +4,12 @@ - Update to `libp2p-core` `v0.37.0`. +- Introduce `libp2p_swarm::keep_alive::ConnectionHandler` in favor of removing `keep_alive` from + `libp2p_swarm::dummy::ConnectionHandler`. `dummy::ConnectionHandler` now literally does not do anything. In the same + spirit, introduce `libp2p_swarm::keep_alive::Behaviour` and `libp2p_swarm::dummy::Behaviour`. See [PR 2859]. + [PR 2857]: https://github.com/libp2p/rust-libp2p/pull/2857 +[PR 2859]: https://github.com/libp2p/rust-libp2p/pull/2859/ - Pass actual `PeerId` of dial to `NetworkBehaviour::inject_dial_failure` on `DialError::ConnectionLimit`. See [PR 2928]. diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index e95381ae5fa..385b7eaf0a3 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -62,9 +62,9 @@ pub(crate) type THandlerOutEvent = /// [`Toggle`](crate::behaviour::toggle::Toggle) [`NetworkBehaviour`]. /// /// ``` rust -/// # use libp2p_swarm::DummyBehaviour; +/// # use libp2p_swarm::dummy; /// # use libp2p_swarm::behaviour::toggle::Toggle; -/// let my_behaviour = DummyBehaviour::default(); +/// let my_behaviour = dummy::Behaviour; /// let my_toggled_behaviour = Toggle::from(Some(my_behaviour)); /// ``` /// diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index 07a15d56da9..8f91c236148 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -411,7 +411,7 @@ where #[cfg(test)] mod tests { use super::*; - use crate::handler::DummyConnectionHandler; + use crate::dummy; /// A disabled [`ToggleConnectionHandler`] can receive listen upgrade errors in /// the following two cases: @@ -429,7 +429,7 @@ mod tests { /// [`ToggleConnectionHandler`] should ignore the error in both of these cases. #[test] fn ignore_listen_upgrade_error_when_disabled() { - let mut handler = ToggleConnectionHandler:: { inner: None }; + let mut handler = ToggleConnectionHandler:: { inner: None }; handler.inject_listen_upgrade_error(Either::Right(()), ConnectionHandlerUpgrErr::Timeout); } diff --git a/swarm/src/connection.rs b/swarm/src/connection.rs index 22223fb9608..304f2b5c759 100644 --- a/swarm/src/connection.rs +++ b/swarm/src/connection.rs @@ -552,7 +552,7 @@ enum Shutdown { #[cfg(test)] mod tests { use super::*; - use crate::handler::DummyConnectionHandler; + use crate::keep_alive; use futures::AsyncRead; use futures::AsyncWrite; use libp2p_core::upgrade::DeniedUpgrade; @@ -572,9 +572,7 @@ mod tests { StreamMuxerBox::new(DummyStreamMuxer { counter: alive_substream_counter.clone(), }), - DummyConnectionHandler { - keep_alive: KeepAlive::Yes, - }, + keep_alive::ConnectionHandler, None, max_negotiating_inbound_streams, ); diff --git a/swarm/src/dummy.rs b/swarm/src/dummy.rs new file mode 100644 index 00000000000..61f055915b3 --- /dev/null +++ b/swarm/src/dummy.rs @@ -0,0 +1,104 @@ +use crate::behaviour::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use crate::handler::{InboundUpgradeSend, OutboundUpgradeSend}; +use crate::{ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol}; +use libp2p_core::connection::ConnectionId; +use libp2p_core::upgrade::DeniedUpgrade; +use libp2p_core::PeerId; +use libp2p_core::UpgradeError; +use std::task::{Context, Poll}; +use void::Void; + +/// Implementation of [`NetworkBehaviour`] that doesn't do anything. +pub struct Behaviour; + +impl NetworkBehaviour for Behaviour { + type ConnectionHandler = ConnectionHandler; + type OutEvent = Void; + + fn new_handler(&mut self) -> Self::ConnectionHandler { + ConnectionHandler + } + + fn inject_event(&mut self, _: PeerId, _: ConnectionId, event: Void) { + void::unreachable(event) + } + + fn poll( + &mut self, + _: &mut Context<'_>, + _: &mut impl PollParameters, + ) -> Poll> { + Poll::Pending + } +} + +/// An implementation of [`ConnectionHandler`] that neither handles any protocols nor does it keep the connection alive. +#[derive(Clone)] +pub struct ConnectionHandler; + +impl crate::handler::ConnectionHandler for ConnectionHandler { + type InEvent = Void; + type OutEvent = Void; + type Error = Void; + type InboundProtocol = DeniedUpgrade; + type OutboundProtocol = DeniedUpgrade; + type InboundOpenInfo = (); + type OutboundOpenInfo = Void; + + fn listen_protocol(&self) -> SubstreamProtocol { + SubstreamProtocol::new(DeniedUpgrade, ()) + } + + fn inject_fully_negotiated_inbound( + &mut self, + protocol: ::Output, + _: Self::InboundOpenInfo, + ) { + void::unreachable(protocol) + } + + fn inject_fully_negotiated_outbound( + &mut self, + protocol: ::Output, + _: Self::OutboundOpenInfo, + ) { + void::unreachable(protocol) + } + + fn inject_event(&mut self, event: Self::InEvent) { + void::unreachable(event) + } + + fn inject_dial_upgrade_error( + &mut self, + _: Self::OutboundOpenInfo, + error: ConnectionHandlerUpgrErr<::Error>, + ) { + match error { + ConnectionHandlerUpgrErr::Timeout => unreachable!(), + ConnectionHandlerUpgrErr::Timer => unreachable!(), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)) => void::unreachable(e), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(_)) => { + unreachable!("Denied upgrade does not support any protocols") + } + } + } + + fn connection_keep_alive(&self) -> KeepAlive { + KeepAlive::No + } + + fn poll( + &mut self, + _: &mut Context<'_>, + ) -> Poll< + ConnectionHandlerEvent< + Self::OutboundProtocol, + Self::OutboundOpenInfo, + Self::OutEvent, + Self::Error, + >, + > { + Poll::Pending + } +} diff --git a/swarm/src/handler.rs b/swarm/src/handler.rs index c6125f277b1..5c60f2bf24a 100644 --- a/swarm/src/handler.rs +++ b/swarm/src/handler.rs @@ -38,7 +38,6 @@ //! > the network as a whole, see the //! > [`NetworkBehaviour`](crate::behaviour::NetworkBehaviour) trait. -mod dummy; pub mod either; mod map_in; mod map_out; @@ -53,7 +52,6 @@ use instant::Instant; use libp2p_core::{upgrade::UpgradeError, ConnectedPoint, Multiaddr, PeerId}; use std::{cmp::Ordering, error, fmt, task::Context, task::Poll, time::Duration}; -pub use dummy::DummyConnectionHandler; pub use map_in::MapInEvent; pub use map_out::MapOutEvent; pub use one_shot::{OneShotHandler, OneShotHandlerConfig}; diff --git a/swarm/src/handler/dummy.rs b/swarm/src/handler/dummy.rs deleted file mode 100644 index 67594686674..00000000000 --- a/swarm/src/handler/dummy.rs +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2018 Parity Technologies (UK) Ltd. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the "Software"), -// to deal in the Software without restriction, including without limitation -// the rights to use, copy, modify, merge, publish, distribute, sublicense, -// and/or sell copies of the Software, and to permit persons to whom the -// Software is furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -// DEALINGS IN THE SOFTWARE. - -use crate::handler::{ - ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, - SubstreamProtocol, -}; -use crate::NegotiatedSubstream; -use libp2p_core::{ - upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade}, - Multiaddr, -}; -use std::task::{Context, Poll}; -use void::Void; - -/// Implementation of [`ConnectionHandler`] that doesn't handle anything. -#[derive(Clone, Debug)] -pub struct DummyConnectionHandler { - pub keep_alive: KeepAlive, -} - -impl Default for DummyConnectionHandler { - fn default() -> Self { - DummyConnectionHandler { - keep_alive: KeepAlive::No, - } - } -} - -impl ConnectionHandler for DummyConnectionHandler { - type InEvent = Void; - type OutEvent = Void; - type Error = Void; - type InboundProtocol = DeniedUpgrade; - type OutboundProtocol = DeniedUpgrade; - type OutboundOpenInfo = Void; - type InboundOpenInfo = (); - - fn listen_protocol(&self) -> SubstreamProtocol { - SubstreamProtocol::new(DeniedUpgrade, ()) - } - - fn inject_fully_negotiated_inbound( - &mut self, - _: >::Output, - _: Self::InboundOpenInfo, - ) { - unreachable!("`DeniedUpgrade` is never successful."); - } - - fn inject_fully_negotiated_outbound( - &mut self, - _: >::Output, - v: Self::OutboundOpenInfo, - ) { - void::unreachable(v) - } - - fn inject_event(&mut self, v: Self::InEvent) { - void::unreachable(v) - } - - fn inject_address_change(&mut self, _: &Multiaddr) {} - - fn inject_dial_upgrade_error( - &mut self, - _: Self::OutboundOpenInfo, - _: ConnectionHandlerUpgrErr< - >::Error, - >, - ) { - } - - fn inject_listen_upgrade_error( - &mut self, - _: Self::InboundOpenInfo, - _: ConnectionHandlerUpgrErr< - >::Error, - >, - ) { - } - - fn connection_keep_alive(&self) -> KeepAlive { - self.keep_alive - } - - fn poll( - &mut self, - _: &mut Context<'_>, - ) -> Poll< - ConnectionHandlerEvent< - Self::OutboundProtocol, - Self::OutboundOpenInfo, - Self::OutEvent, - Self::Error, - >, - > { - Poll::Pending - } -} diff --git a/swarm/src/keep_alive.rs b/swarm/src/keep_alive.rs new file mode 100644 index 00000000000..ea5d5ee6399 --- /dev/null +++ b/swarm/src/keep_alive.rs @@ -0,0 +1,119 @@ +use crate::behaviour::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use crate::handler::{ + ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol, +}; +use crate::NegotiatedSubstream; +use libp2p_core::connection::ConnectionId; +use libp2p_core::PeerId; +use libp2p_core::{ + upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade}, + Multiaddr, +}; +use std::task::{Context, Poll}; +use void::Void; + +/// Implementation of [`NetworkBehaviour`] that doesn't do anything other than keep all connections alive. +/// +/// This is primarily useful for test code. In can however occasionally be useful for production code too. +/// The caveat is that open connections consume system resources and should thus be shutdown when +/// they are not in use. Connections can also fail at any time so really, your application should be +/// designed to establish them when necessary, making the use of this behaviour likely redundant. +#[derive(Default)] +pub struct Behaviour; + +impl NetworkBehaviour for Behaviour { + type ConnectionHandler = ConnectionHandler; + type OutEvent = Void; + + fn new_handler(&mut self) -> Self::ConnectionHandler { + ConnectionHandler + } + + fn inject_event(&mut self, _: PeerId, _: ConnectionId, event: Void) { + void::unreachable(event) + } + + fn poll( + &mut self, + _: &mut Context<'_>, + _: &mut impl PollParameters, + ) -> Poll> { + Poll::Pending + } +} + +/// Implementation of [`ConnectionHandler`] that doesn't handle anything but keeps the connection alive. +#[derive(Clone, Debug)] +pub struct ConnectionHandler; + +impl crate::handler::ConnectionHandler for ConnectionHandler { + type InEvent = Void; + type OutEvent = Void; + type Error = Void; + type InboundProtocol = DeniedUpgrade; + type OutboundProtocol = DeniedUpgrade; + type InboundOpenInfo = (); + type OutboundOpenInfo = Void; + + fn listen_protocol(&self) -> SubstreamProtocol { + SubstreamProtocol::new(DeniedUpgrade, ()) + } + + fn inject_fully_negotiated_inbound( + &mut self, + protocol: >::Output, + _: Self::InboundOpenInfo, + ) { + void::unreachable(protocol); + } + + fn inject_fully_negotiated_outbound( + &mut self, + protocol: >::Output, + _: Self::OutboundOpenInfo, + ) { + void::unreachable(protocol) + } + + fn inject_event(&mut self, v: Self::InEvent) { + void::unreachable(v) + } + + fn inject_address_change(&mut self, _: &Multiaddr) {} + + fn inject_dial_upgrade_error( + &mut self, + _: Self::OutboundOpenInfo, + _: ConnectionHandlerUpgrErr< + >::Error, + >, + ) { + } + + fn inject_listen_upgrade_error( + &mut self, + _: Self::InboundOpenInfo, + _: ConnectionHandlerUpgrErr< + >::Error, + >, + ) { + } + + fn connection_keep_alive(&self) -> KeepAlive { + KeepAlive::Yes + } + + fn poll( + &mut self, + _: &mut Context<'_>, + ) -> Poll< + ConnectionHandlerEvent< + Self::OutboundProtocol, + Self::OutboundOpenInfo, + Self::OutEvent, + Self::Error, + >, + > { + Poll::Pending + } +} diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 58ffb91c994..3979bcfecba 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -61,7 +61,9 @@ mod upgrade; pub mod behaviour; pub mod dial_opts; +pub mod dummy; pub mod handler; +pub mod keep_alive; pub use behaviour::{ CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, @@ -348,11 +350,11 @@ where /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; /// # use libp2p_core::{Multiaddr, PeerId, Transport}; /// # use libp2p_core::transport::dummy::DummyTransport; - /// # use libp2p_swarm::DummyBehaviour; + /// # use libp2p_swarm::dummy; /// # /// let mut swarm = Swarm::new( /// DummyTransport::new().boxed(), - /// DummyBehaviour::default(), + /// dummy::Behaviour, /// PeerId::random(), /// ); /// @@ -1514,58 +1516,6 @@ impl error::Error for DialError { } } -/// Dummy implementation of [`NetworkBehaviour`] that doesn't do anything. -#[derive(Clone)] -pub struct DummyBehaviour { - keep_alive: KeepAlive, -} - -impl DummyBehaviour { - pub fn with_keep_alive(keep_alive: KeepAlive) -> Self { - Self { keep_alive } - } - - pub fn keep_alive_mut(&mut self) -> &mut KeepAlive { - &mut self.keep_alive - } -} - -impl Default for DummyBehaviour { - fn default() -> Self { - Self { - keep_alive: KeepAlive::No, - } - } -} - -impl NetworkBehaviour for DummyBehaviour { - type ConnectionHandler = handler::DummyConnectionHandler; - type OutEvent = void::Void; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - handler::DummyConnectionHandler { - keep_alive: self.keep_alive, - } - } - - fn inject_event( - &mut self, - _: PeerId, - _: ConnectionId, - event: ::OutEvent, - ) { - void::unreachable(event) - } - - fn poll( - &mut self, - _: &mut Context<'_>, - _: &mut impl PollParameters, - ) -> Poll> { - Poll::Pending - } -} - /// Information about the connections obtained by [`Swarm::network_info()`]. #[derive(Clone, Debug)] pub struct NetworkInfo { @@ -1617,7 +1567,6 @@ fn p2p_addr(peer: Option, addr: Multiaddr) -> Result(handler_proto.clone()).build(); let mut swarm2 = new_test_swarm::<_, ()>(handler_proto).build(); @@ -1834,9 +1781,7 @@ mod tests { fn test_swarm_disconnect() { // Since the test does not try to open any substreams, we can // use the dummy protocols handler. - let handler_proto = DummyConnectionHandler { - keep_alive: KeepAlive::Yes, - }; + let handler_proto = keep_alive::ConnectionHandler; let mut swarm1 = new_test_swarm::<_, ()>(handler_proto.clone()).build(); let mut swarm2 = new_test_swarm::<_, ()>(handler_proto).build(); @@ -1902,9 +1847,7 @@ mod tests { fn test_behaviour_disconnect_all() { // Since the test does not try to open any substreams, we can // use the dummy protocols handler. - let handler_proto = DummyConnectionHandler { - keep_alive: KeepAlive::Yes, - }; + let handler_proto = keep_alive::ConnectionHandler; let mut swarm1 = new_test_swarm::<_, ()>(handler_proto.clone()).build(); let mut swarm2 = new_test_swarm::<_, ()>(handler_proto).build(); @@ -1972,9 +1915,7 @@ mod tests { fn test_behaviour_disconnect_one() { // Since the test does not try to open any substreams, we can // use the dummy protocols handler. - let handler_proto = DummyConnectionHandler { - keep_alive: KeepAlive::Yes, - }; + let handler_proto = keep_alive::ConnectionHandler; let mut swarm1 = new_test_swarm::<_, ()>(handler_proto.clone()).build(); let mut swarm2 = new_test_swarm::<_, ()>(handler_proto).build(); @@ -2059,11 +2000,9 @@ mod tests { fn prop(concurrency_factor: DialConcurrencyFactor) { block_on(async { - let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler { - keep_alive: KeepAlive::Yes, - }) - .dial_concurrency_factor(concurrency_factor.0) - .build(); + let mut swarm = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler) + .dial_concurrency_factor(concurrency_factor.0) + .build(); // Listen on `concurrency_factor + 1` addresses. // @@ -2129,11 +2068,9 @@ mod tests { let outgoing_limit = rand::thread_rng().gen_range(1..10); let limits = ConnectionLimits::default().with_max_pending_outgoing(Some(outgoing_limit)); - let mut network = new_test_swarm::<_, ()>(DummyConnectionHandler { - keep_alive: KeepAlive::Yes, - }) - .connection_limits(limits) - .build(); + let mut network = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler) + .connection_limits(limits) + .build(); let addr: Multiaddr = "/memory/1234".parse().unwrap(); @@ -2185,16 +2122,12 @@ mod tests { fn prop(limit: Limit) { let limit = limit.0; - let mut network1 = new_test_swarm::<_, ()>(DummyConnectionHandler { - keep_alive: KeepAlive::Yes, - }) - .connection_limits(limits(limit)) - .build(); - let mut network2 = new_test_swarm::<_, ()>(DummyConnectionHandler { - keep_alive: KeepAlive::Yes, - }) - .connection_limits(limits(limit)) - .build(); + let mut network1 = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler) + .connection_limits(limits(limit)) + .build(); + let mut network2 = new_test_swarm::<_, ()>(keep_alive::ConnectionHandler) + .connection_limits(limits(limit)) + .build(); let _ = network1.listen_on(multiaddr![Memory(0u64)]).unwrap(); let listen_addr = async_std::task::block_on(poll_fn(|cx| { @@ -2299,8 +2232,8 @@ mod tests { // Checks whether dialing an address containing the wrong peer id raises an error // for the expected peer id instead of the obtained peer id. - let mut swarm1 = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); - let mut swarm2 = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); + let mut swarm1 = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build(); + let mut swarm2 = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build(); swarm1.listen_on("/memory/0".parse().unwrap()).unwrap(); @@ -2359,7 +2292,7 @@ mod tests { // // The last two can happen in any order. - let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); + let mut swarm = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build(); swarm.listen_on("/memory/0".parse().unwrap()).unwrap(); let local_address = @@ -2417,7 +2350,7 @@ mod tests { fn dial_self_by_id() { // Trying to dial self by passing the same `PeerId` shouldn't even be possible in the first // place. - let swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); + let swarm = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build(); let peer_id = *swarm.local_peer_id(); assert!(!swarm.is_connected(&peer_id)); } @@ -2428,7 +2361,7 @@ mod tests { let target = PeerId::random(); - let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); + let mut swarm = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build(); let addresses = HashSet::from([ multiaddr![Ip4([0, 0, 0, 0]), Tcp(rand::random::())], @@ -2473,8 +2406,8 @@ mod tests { fn aborting_pending_connection_surfaces_error() { let _ = env_logger::try_init(); - let mut dialer = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); - let mut listener = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); + let mut dialer = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build(); + let mut listener = new_test_swarm::<_, ()>(dummy::ConnectionHandler).build(); let listener_peer_id = *listener.local_peer_id(); listener.listen_on(multiaddr![Memory(0u64)]).unwrap();