Skip to content

Commit

Permalink
swarm: Split off "keep alive" functionality from `DummyConnectionHand…
Browse files Browse the repository at this point in the history
…ler` (#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
#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.
  • Loading branch information
thomaseizinger authored Oct 5, 2022
1 parent da0403d commit bdf9209
Show file tree
Hide file tree
Showing 26 changed files with 412 additions and 319 deletions.
22 changes: 13 additions & 9 deletions examples/ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -53,14 +54,7 @@ async fn main() -> Result<(), Box<dyn Error>> {

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.
Expand All @@ -82,3 +76,13 @@ async fn main() -> Result<(), Box<dyn Error>> {
}
}
}

/// 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,
}
4 changes: 2 additions & 2 deletions misc/metrics/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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`.
Expand All @@ -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`.
Expand Down
22 changes: 16 additions & 6 deletions misc/metrics/examples/metrics/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn Error>> {
Expand All @@ -72,7 +72,7 @@ fn main() -> Result<(), Box<dyn Error>> {

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,
);

Expand All @@ -91,7 +91,7 @@ fn main() -> Result<(), Box<dyn Error>> {
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);
}
Expand All @@ -104,3 +104,13 @@ fn main() -> Result<(), Box<dyn Error>> {
});
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,
}
6 changes: 3 additions & 3 deletions misc/multistream-select/tests/transport.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -61,8 +61,8 @@ fn transport_upgrade() {

let listen_addr = Multiaddr::from(Protocol::Memory(random::<u64>()));

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();
Expand Down
6 changes: 3 additions & 3 deletions protocols/dcutr/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand All @@ -44,15 +44,15 @@ pub enum Role {
}

impl IntoConnectionHandler for Prototype {
type Handler = Either<relayed::Handler, Either<direct::Handler, DummyConnectionHandler>>;
type Handler = Either<relayed::Handler, Either<direct::Handler, dummy::ConnectionHandler>>;

fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
match self {
Self::UnknownConnection => {
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 {
Expand Down
9 changes: 4 additions & 5 deletions protocols/mdns/src/behaviour.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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<Multiaddr> {
Expand Down Expand Up @@ -168,7 +167,7 @@ where
&mut self,
cx: &mut Context<'_>,
params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, DummyConnectionHandler>> {
) -> Poll<NetworkBehaviourAction<Self::OutEvent, dummy::ConnectionHandler>> {
// Poll ifwatch.
while let Poll::Ready(event) = Pin::new(&mut self.if_watch).poll(cx) {
match event {
Expand Down
3 changes: 3 additions & 0 deletions protocols/ping/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 4 additions & 0 deletions protocols/ping/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading

0 comments on commit bdf9209

Please sign in to comment.