From 90a1349c9be41c42f7b69f806a895bbcd1d23306 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Sat, 3 Sep 2022 18:00:21 +0900 Subject: [PATCH 01/60] swarm/behaviour: Replace inject_* with on_event Replace the various `NetworkBehaviour::inject_*` methods with a single `NetworkBehaviour::on_event` method and a `InEvent` `enum`. --- swarm/src/behaviour.rs | 361 +++++++++++++++++++++++++++++----- swarm/src/behaviour/either.rs | 188 ++---------------- swarm/src/behaviour/toggle.rs | 135 +------------ swarm/src/handler/either.rs | 23 +++ swarm/src/lib.rs | 188 +++++++++++++++--- 5 files changed, 521 insertions(+), 374 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index a5bf0e06f06..1465e2ee401 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -152,7 +152,15 @@ pub trait NetworkBehaviour: 'static { vec![] } + /// Informs the behaviour about an event from the [Transport](libp2p_core::Transport) or the + /// [`ConnectionHandler`]. + fn on_event(&mut self, _event: InEvent); + /// Informs the behaviour about a newly established connection to a peer. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::ConnectionEstablished` in `NetworkBehaviour::on_event` instead." + )] fn inject_connection_established( &mut self, _peer_id: &PeerId, @@ -163,21 +171,31 @@ pub trait NetworkBehaviour: 'static { ) { } - /// Informs the behaviour about a closed connection to a peer. - /// - /// A call to this method is always paired with an earlier call to - /// [`NetworkBehaviour::inject_connection_established`] with the same peer ID, connection ID and endpoint. - fn inject_connection_closed( - &mut self, - _: &PeerId, - _: &ConnectionId, - _: &ConnectedPoint, - _: ::Handler, - _remaining_established: usize, - ) { - } + // TODO: Have to remove this as it takes ownership of `Handler`. + // + // /// Informs the behaviour about a closed connection to a peer. + // /// + // /// A call to this method is always paired with an earlier call to + // /// [`NetworkBehaviour::inject_connection_established`] with the same peer ID, connection ID and endpoint. + // #[deprecated( + // since = "0.39.0", + // note = "Handle `InEvent::ConnectionClosed` in `NetworkBehaviour::on_event` instead." + // )] + // fn inject_connection_closed( + // &mut self, + // _: &PeerId, + // _: &ConnectionId, + // _: &ConnectedPoint, + // _: ::Handler, + // _remaining_established: usize, + // ) { + // } /// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::AddressChange` in `NetworkBehaviour::on_event` instead." + )] fn inject_address_change( &mut self, _: &PeerId, @@ -187,61 +205,99 @@ pub trait NetworkBehaviour: 'static { ) { } - /// Informs the behaviour about an event generated by the handler dedicated to the peer identified by `peer_id`. - /// for the behaviour. - /// - /// The `peer_id` is guaranteed to be in a connected state. In other words, - /// [`NetworkBehaviour::inject_connection_established`] has previously been called with this `PeerId`. - fn inject_event( - &mut self, - peer_id: PeerId, - connection: ConnectionId, - event: <::Handler as ConnectionHandler>::OutEvent, - ); - - /// Indicates to the behaviour that the dial to a known or unknown node failed. - fn inject_dial_failure( - &mut self, - _peer_id: Option, - _handler: Self::ConnectionHandler, - _error: &DialError, - ) { - } - - /// Indicates to the behaviour that an error happened on an incoming connection during its - /// initial handshake. - /// - /// This can include, for example, an error during the handshake of the encryption layer, or the - /// connection unexpectedly closed. - fn inject_listen_failure( - &mut self, - _local_addr: &Multiaddr, - _send_back_addr: &Multiaddr, - _handler: Self::ConnectionHandler, - ) { - } + // TODO: Can not deprecate as it takes ownership of handler event. + // + // /// Informs the behaviour about an event generated by the handler dedicated to the peer identified by `peer_id`. + // /// for the behaviour. + // /// + // /// The `peer_id` is guaranteed to be in a connected state. In other words, + // /// [`NetworkBehaviour::inject_connection_established`] has previously been called with this `PeerId`. + // #[deprecated( + // since = "0.39.0", + // note = "Handle `InEvent::ConnectionHandler` in `NetworkBehaviour::on_event` instead." + // )] + // fn inject_event( + // &mut self, + // peer_id: PeerId, + // connection: ConnectionId, + // event: <::Handler as ConnectionHandler>::OutEvent, + // ); + + // TODO: Can not deprecate as it takes ownership of handler. + // + // /// Indicates to the behaviour that the dial to a known or unknown node failed. + // fn inject_dial_failure( + // &mut self, + // _peer_id: Option, + // _handler: Self::ConnectionHandler, + // _error: &DialError, + // ) { + // } + + // TODO: Can not deprecate as it takes ownership of handler. + // + // /// Indicates to the behaviour that an error happened on an incoming connection during its + // /// initial handshake. + // /// + // /// This can include, for example, an error during the handshake of the encryption layer, or the + // /// connection unexpectedly closed. + // fn inject_listen_failure( + // &mut self, + // _local_addr: &Multiaddr, + // _send_back_addr: &Multiaddr, + // _handler: Self::ConnectionHandler, + // ) { + // } /// Indicates to the behaviour that a new listener was created. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::NewListener` in `NetworkBehaviour::on_event` instead." + )] fn inject_new_listener(&mut self, _id: ListenerId) {} /// Indicates to the behaviour that we have started listening on a new multiaddr. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::NewListenAddr` in `NetworkBehaviour::on_event` instead." + )] fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) {} /// Indicates to the behaviour that a multiaddr we were listening on has expired, - /// which means that we are no longer listening in it. + /// which means that we are no longer listening on it. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::ExpiredListenAddr` in `NetworkBehaviour::on_event` instead." + )] fn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) {} /// A listener experienced an error. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::ListenerError` in `NetworkBehaviour::on_event` instead." + )] fn inject_listener_error(&mut self, _id: ListenerId, _err: &(dyn std::error::Error + 'static)) { } /// A listener closed. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::ListenerClosed` in `NetworkBehaviour::on_event` instead." + )] fn inject_listener_closed(&mut self, _id: ListenerId, _reason: Result<(), &std::io::Error>) {} /// Indicates to the behaviour that we have discovered a new external address for us. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::NewExternalAddr` in `NetworkBehaviour::on_event` instead." + )] fn inject_new_external_addr(&mut self, _addr: &Multiaddr) {} /// Indicates to the behaviour that an external address was removed. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::ExpiredExternalAddr` in `NetworkBehaviour::on_event` instead." + )] fn inject_expired_external_addr(&mut self, _addr: &Multiaddr) {} /// Polls for things that swarm should do. @@ -721,3 +777,214 @@ impl Default for CloseConnection { CloseConnection::All } } + +pub enum InEvent<'a, Handler: IntoConnectionHandler> { + /// Informs the behaviour about a newly established connection to a peer. + ConnectionEstablished { + peer_id: PeerId, + connection_id: ConnectionId, + endpoint: &'a ConnectedPoint, + // TODO: Would a slice not be better? + failed_addresses: Option<&'a Vec>, + other_established: usize, + }, + /// Informs the behaviour about a closed connection to a peer. + /// + /// This event is always paired with an earlier call to + /// [`InEvent::ConnectionEstablished`] with the same peer ID, connection ID + /// and endpoint. + ConnectionClosed { + peer_id: PeerId, + connection_id: ConnectionId, + endpoint: &'a ConnectedPoint, + handler: ::Handler, + remaining_established: usize, + }, + /// Informs the behaviour that the [`ConnectedPoint`] of an existing + /// connection has changed. + AddressChange { + peer_id: PeerId, + connection_id: ConnectionId, + old: &'a ConnectedPoint, + new: &'a ConnectedPoint, + }, + /// Informs the behaviour about an event generated by the handler dedicated to the peer + /// identified by `peer_id`. for the behaviour. + /// + /// The `peer_id` is guaranteed to be in a connected state. In other words, + /// [`InEvent::ConnectionEstablished`] has previously been received with this `PeerId`. + ConnectionHandler { + peer_id: PeerId, + connection: ConnectionId, + event: <::Handler as ConnectionHandler>::OutEvent, + }, + /// Indicates to the behaviour that the dial to a known or unknown node failed. + DialFailure { + peer_id: Option, + handler: Handler, + error: &'a DialError, + }, + /// Indicates to the behaviour that an error happened on an incoming connection during its + /// initial handshake. + /// + /// This can include, for example, an error during the handshake of the encryption layer, or the + /// connection unexpectedly closed. + ListenFailure { + local_addr: &'a Multiaddr, + send_back_addr: &'a Multiaddr, + handler: Handler, + }, + /// Indicates to the behaviour that a new listener was created. + NewListener { listener_id: ListenerId }, + /// Indicates to the behaviour that we have started listening on a new multiaddr. + NewListenAddr { + listener_id: ListenerId, + addr: &'a Multiaddr, + }, + /// Indicates to the behaviour that a multiaddr we were listening on has expired, + /// which means that we are no longer listening on it. + ExpiredListenAddr { + listener_id: ListenerId, + addr: &'a Multiaddr, + }, + /// A listener experienced an error. + ListenerError { + listener_id: ListenerId, + err: &'a (dyn std::error::Error + 'static), + }, + /// A listener closed. + ListenerClosed { + listener_id: ListenerId, + reason: Result<(), &'a std::io::Error>, + }, + /// Indicates to the behaviour that we have discovered a new external address for us. + NewExternalAddr { addr: &'a Multiaddr }, + /// Indicates to the behaviour that an external address was removed. + ExpiredExternalAddr { addr: &'a Multiaddr }, +} + +impl<'a, Handler: IntoConnectionHandler> InEvent<'a, Handler> { + fn map_handler( + self, + map_into_handler: impl FnOnce(Handler) -> NewHandler, + map_handler: impl FnOnce( + ::Handler, + ) -> ::Handler, + map_event: impl FnOnce( + <::Handler as ConnectionHandler>::OutEvent, + ) -> + <::Handler as ConnectionHandler>::OutEvent, + ) -> InEvent<'a, NewHandler> + where + NewHandler: IntoConnectionHandler, + { + self.try_map_handler( + |h| Some(map_into_handler(h)), + |h| Some(map_handler(h)), + |e| Some(map_event(e)), + ) + .expect("To return Some as all closures return Some.") + } + + fn try_map_handler( + self, + map_into_handler: impl FnOnce(Handler) -> Option, + map_handler: impl FnOnce( + ::Handler, + ) -> Option<::Handler>, + map_event: impl FnOnce( + <::Handler as ConnectionHandler>::OutEvent, + ) -> Option< + <::Handler as ConnectionHandler>::OutEvent, + >, + ) -> Option> + where + NewHandler: IntoConnectionHandler, + { + match self { + InEvent::ConnectionClosed { + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + } => Some(InEvent::ConnectionClosed { + peer_id, + connection_id, + endpoint, + handler: map_handler(handler)?, + remaining_established, + }), + InEvent::ConnectionEstablished { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + } => Some(InEvent::ConnectionEstablished { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + }), + InEvent::AddressChange { + peer_id, + connection_id, + old, + new, + } => Some(InEvent::AddressChange { + peer_id, + connection_id, + old, + new, + }), + InEvent::ConnectionHandler { + peer_id, + connection, + event, + } => Some(InEvent::ConnectionHandler { + peer_id, + connection, + event: map_event(event)?, + }), + InEvent::DialFailure { + peer_id, + handler, + error, + } => Some(InEvent::DialFailure { + peer_id, + handler: map_into_handler(handler)?, + error, + }), + InEvent::ListenFailure { + local_addr, + send_back_addr, + handler, + } => Some(InEvent::ListenFailure { + local_addr, + send_back_addr, + handler: map_into_handler(handler)?, + }), + InEvent::NewListener { listener_id } => Some(InEvent::NewListener { listener_id }), + InEvent::NewListenAddr { listener_id, addr } => { + Some(InEvent::NewListenAddr { listener_id, addr }) + } + InEvent::ExpiredListenAddr { listener_id, addr } => { + Some(InEvent::ExpiredListenAddr { listener_id, addr }) + } + InEvent::ListenerError { listener_id, err } => { + Some(InEvent::ListenerError { listener_id, err }) + } + InEvent::ListenerClosed { + listener_id, + reason, + } => Some(InEvent::ListenerClosed { + listener_id, + reason, + }), + InEvent::NewExternalAddr { addr } => Some(InEvent::NewExternalAddr { addr }), + InEvent::ExpiredExternalAddr { addr } => Some(InEvent::ExpiredExternalAddr { addr }), + } + } +} diff --git a/swarm/src/behaviour/either.rs b/swarm/src/behaviour/either.rs index 6bb1d95a519..e9677ff419a 100644 --- a/swarm/src/behaviour/either.rs +++ b/swarm/src/behaviour/either.rs @@ -18,12 +18,10 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::handler::{either::IntoEitherHandler, ConnectionHandler, IntoConnectionHandler}; -use crate::{DialError, NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use crate::handler::either::IntoEitherHandler; +use crate::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; use either::Either; -use libp2p_core::{ - connection::ConnectionId, transport::ListenerId, ConnectedPoint, Multiaddr, PeerId, -}; +use libp2p_core::{Multiaddr, PeerId}; use std::{task::Context, task::Poll}; /// Implementation of [`NetworkBehaviour`] that can be either of two implementations. @@ -49,170 +47,24 @@ where } } - fn inject_connection_established( - &mut self, - peer_id: &PeerId, - connection: &ConnectionId, - endpoint: &ConnectedPoint, - errors: Option<&Vec>, - other_established: usize, - ) { - match self { - Either::Left(a) => a.inject_connection_established( - peer_id, - connection, - endpoint, - errors, - other_established, - ), - Either::Right(b) => b.inject_connection_established( - peer_id, - connection, - endpoint, - errors, - other_established, - ), - } - } - - fn inject_connection_closed( - &mut self, - peer_id: &PeerId, - connection: &ConnectionId, - endpoint: &ConnectedPoint, - handler: ::Handler, - remaining_established: usize, - ) { - match (self, handler) { - (Either::Left(behaviour), Either::Left(handler)) => behaviour.inject_connection_closed( - peer_id, - connection, - endpoint, - handler, - remaining_established, - ), - (Either::Right(behaviour), Either::Right(handler)) => behaviour - .inject_connection_closed( - peer_id, - connection, - endpoint, - handler, - remaining_established, - ), - _ => unreachable!(), - } - } - - fn inject_address_change( - &mut self, - peer_id: &PeerId, - connection: &ConnectionId, - old: &ConnectedPoint, - new: &ConnectedPoint, - ) { - match self { - Either::Left(a) => a.inject_address_change(peer_id, connection, old, new), - Either::Right(b) => b.inject_address_change(peer_id, connection, old, new), - } - } - - fn inject_event( - &mut self, - peer_id: PeerId, - connection: ConnectionId, - event: <::Handler as ConnectionHandler>::OutEvent, - ) { - match (self, event) { - (Either::Left(behaviour), Either::Left(event)) => { - behaviour.inject_event(peer_id, connection, event) - } - (Either::Right(behaviour), Either::Right(event)) => { - behaviour.inject_event(peer_id, connection, event) - } - _ => unreachable!(), - } - } - - fn inject_dial_failure( - &mut self, - peer_id: Option, - handler: Self::ConnectionHandler, - error: &DialError, - ) { - match (self, handler) { - (Either::Left(behaviour), IntoEitherHandler::Left(handler)) => { - behaviour.inject_dial_failure(peer_id, handler, error) - } - (Either::Right(behaviour), IntoEitherHandler::Right(handler)) => { - behaviour.inject_dial_failure(peer_id, handler, error) - } - _ => unreachable!(), - } - } - - fn inject_listen_failure( - &mut self, - local_addr: &Multiaddr, - send_back_addr: &Multiaddr, - handler: Self::ConnectionHandler, - ) { - match (self, handler) { - (Either::Left(behaviour), IntoEitherHandler::Left(handler)) => { - behaviour.inject_listen_failure(local_addr, send_back_addr, handler) - } - (Either::Right(behaviour), IntoEitherHandler::Right(handler)) => { - behaviour.inject_listen_failure(local_addr, send_back_addr, handler) - } - _ => unreachable!(), - } - } - - fn inject_new_listener(&mut self, id: ListenerId) { - match self { - Either::Left(a) => a.inject_new_listener(id), - Either::Right(b) => b.inject_new_listener(id), - } - } - - fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - match self { - Either::Left(a) => a.inject_new_listen_addr(id, addr), - Either::Right(b) => b.inject_new_listen_addr(id, addr), - } - } - - fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - match self { - Either::Left(a) => a.inject_expired_listen_addr(id, addr), - Either::Right(b) => b.inject_expired_listen_addr(id, addr), - } - } - - fn inject_new_external_addr(&mut self, addr: &Multiaddr) { - match self { - Either::Left(a) => a.inject_new_external_addr(addr), - Either::Right(b) => b.inject_new_external_addr(addr), - } - } - - fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { - match self { - Either::Left(a) => a.inject_expired_external_addr(addr), - Either::Right(b) => b.inject_expired_external_addr(addr), - } - } - - fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { - match self { - Either::Left(a) => a.inject_listener_error(id, err), - Either::Right(b) => b.inject_listener_error(id, err), - } - } - - fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { + fn on_event(&mut self, event: super::InEvent) { match self { - Either::Left(a) => a.inject_listener_closed(id, reason), - Either::Right(b) => b.inject_listener_closed(id, reason), + Either::Left(b) => b.on_event(event.map_handler( + |h| h.unwrap_left(), + |h| match h { + Either::Left(h) => h, + Either::Right(_) => unreachable!(), + }, + |e| e.unwrap_left(), + )), + Either::Right(b) => b.on_event(event.map_handler( + |h| h.unwrap_right(), + |h| match h { + Either::Right(h) => h, + Either::Left(_) => unreachable!(), + }, + |e| e.unwrap_right(), + )), } } diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index 07a15d56da9..6561876e555 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -23,12 +23,10 @@ use crate::handler::{ KeepAlive, SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; -use crate::{DialError, NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use crate::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; use either::Either; use libp2p_core::{ - connection::ConnectionId, either::{EitherError, EitherOutput}, - transport::ListenerId, upgrade::{DeniedUpgrade, EitherUpgrade}, ConnectedPoint, Multiaddr, PeerId, }; @@ -84,137 +82,14 @@ where .unwrap_or_else(Vec::new) } - fn inject_connection_established( - &mut self, - peer_id: &PeerId, - connection: &ConnectionId, - endpoint: &ConnectedPoint, - errors: Option<&Vec>, - other_established: usize, - ) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_connection_established( - peer_id, - connection, - endpoint, - errors, - other_established, - ) - } - } - - fn inject_connection_closed( - &mut self, - peer_id: &PeerId, - connection: &ConnectionId, - endpoint: &ConnectedPoint, - handler: ::Handler, - remaining_established: usize, - ) { - if let Some(inner) = self.inner.as_mut() { - if let Some(handler) = handler.inner { - inner.inject_connection_closed( - peer_id, - connection, - endpoint, - handler, - remaining_established, - ) - } - } - } - - fn inject_address_change( - &mut self, - peer_id: &PeerId, - connection: &ConnectionId, - old: &ConnectedPoint, - new: &ConnectedPoint, - ) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_address_change(peer_id, connection, old, new) - } - } - - fn inject_event( - &mut self, - peer_id: PeerId, - connection: ConnectionId, - event: <::Handler as ConnectionHandler>::OutEvent, - ) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_event(peer_id, connection, event); - } - } - - fn inject_dial_failure( - &mut self, - peer_id: Option, - handler: Self::ConnectionHandler, - error: &DialError, - ) { - if let Some(inner) = self.inner.as_mut() { - if let Some(handler) = handler.inner { - inner.inject_dial_failure(peer_id, handler, error) - } - } - } - - fn inject_listen_failure( - &mut self, - local_addr: &Multiaddr, - send_back_addr: &Multiaddr, - handler: Self::ConnectionHandler, - ) { - if let Some(inner) = self.inner.as_mut() { - if let Some(handler) = handler.inner { - inner.inject_listen_failure(local_addr, send_back_addr, handler) + fn on_event(&mut self, event: super::InEvent) { + if let Some(behaviour) = &mut self.inner { + if let Some(event) = event.try_map_handler(|h| h.inner, |h| h.inner, |e| Some(e)) { + behaviour.on_event(event); } } } - fn inject_new_listener(&mut self, id: ListenerId) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_new_listener(id) - } - } - - fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_new_listen_addr(id, addr) - } - } - - fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_expired_listen_addr(id, addr) - } - } - - fn inject_new_external_addr(&mut self, addr: &Multiaddr) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_new_external_addr(addr) - } - } - - fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_expired_external_addr(addr) - } - } - - fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_listener_error(id, err) - } - } - - fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { - if let Some(inner) = self.inner.as_mut() { - inner.inject_listener_closed(id, reason) - } - } - fn poll( &mut self, cx: &mut Context<'_>, diff --git a/swarm/src/handler/either.rs b/swarm/src/handler/either.rs index 21d386ec56a..2823b6ed824 100644 --- a/swarm/src/handler/either.rs +++ b/swarm/src/handler/either.rs @@ -64,6 +64,29 @@ where } } +// Taken from https://github.com/bluss/either. +impl IntoEitherHandler { + /// Returns the left value. + pub fn unwrap_left(self) -> L { + match self { + IntoEitherHandler::Left(l) => l, + IntoEitherHandler::Right(_) => { + panic!("called `IntoEitherHandler::unwrap_left()` on a `Right` value.",) + } + } + } + + /// Returns the right value. + pub fn unwrap_right(self) -> R { + match self { + IntoEitherHandler::Right(r) => r, + IntoEitherHandler::Left(_) => { + panic!("called `IntoEitherHandler::unwrap_right()` on a `Left` value.",) + } + } + } +} + /// Implementation of a [`ConnectionHandler`] that represents either of two [`ConnectionHandler`] /// implementations. impl ConnectionHandler for Either diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 230de4631db..ed2ecd5c6ce 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -63,6 +63,7 @@ pub mod behaviour; pub mod dial_opts; pub mod handler; +use behaviour::InEvent; pub use behaviour::{ CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; @@ -327,6 +328,9 @@ where /// Depending on the underlying transport, one listener may have multiple listening addresses. pub fn listen_on(&mut self, addr: Multiaddr) -> Result> { let id = self.transport.listen_on(addr)?; + self.behaviour + .on_event(InEvent::NewListener { listener_id: id }); + #[allow(deprecated)] self.behaviour.inject_new_listener(id); Ok(id) } @@ -403,11 +407,11 @@ where PeerCondition::Always => true, }; if !condition_matched { - self.behaviour.inject_dial_failure( - Some(peer_id), + self.behaviour.on_event(InEvent::DialFailure { + peer_id: Some(peer_id), handler, - &DialError::DialPeerConditionFalse(condition), - ); + error: &DialError::DialPeerConditionFalse(condition), + }); return Err(DialError::DialPeerConditionFalse(condition)); } @@ -415,8 +419,11 @@ where // Check if peer is banned. if self.banned_peers.contains(&peer_id) { let error = DialError::Banned; - self.behaviour - .inject_dial_failure(Some(peer_id), handler, &error); + self.behaviour.on_event(InEvent::DialFailure { + peer_id: Some(peer_id), + handler, + error: &error, + }); return Err(error); } @@ -452,8 +459,11 @@ where if addresses.is_empty() { let error = DialError::NoAddresses; - self.behaviour - .inject_dial_failure(Some(peer_id), handler, &error); + self.behaviour.on_event(InEvent::DialFailure { + peer_id: Some(peer_id), + handler, + error: &error, + }); return Err(error); }; @@ -535,7 +545,11 @@ where Ok(_connection_id) => Ok(()), Err((connection_limit, handler)) => { let error = DialError::ConnectionLimit(connection_limit); - self.behaviour.inject_dial_failure(None, handler, &error); + self.behaviour.on_event(InEvent::DialFailure { + peer_id: None, + handler, + error: &error, + }); Err(error) } } @@ -576,12 +590,18 @@ where let result = self.external_addrs.add(a.clone(), s); let expired = match &result { AddAddressResult::Inserted { expired } => { + self.behaviour + .on_event(InEvent::NewExternalAddr { addr: &a }); + #[allow(deprecated)] self.behaviour.inject_new_external_addr(&a); expired } AddAddressResult::Updated { expired } => expired, }; for a in expired { + self.behaviour + .on_event(InEvent::ExpiredExternalAddr { addr: &a.addr }); + #[allow(deprecated)] self.behaviour.inject_expired_external_addr(&a.addr); } result @@ -595,6 +615,9 @@ where /// otherwise. pub fn remove_external_address(&mut self, addr: &Multiaddr) -> bool { if self.external_addrs.remove(addr) { + self.behaviour + .on_event(InEvent::ExpiredExternalAddr { addr }); + #[allow(deprecated)] self.behaviour.inject_expired_external_addr(addr); true } else { @@ -701,6 +724,15 @@ where let failed_addresses = concurrent_dial_errors .as_ref() .map(|es| es.iter().map(|(a, _)| a).cloned().collect()); + self.behaviour + .on_event(behaviour::InEvent::ConnectionEstablished { + peer_id, + connection_id: id, + endpoint: &endpoint, + failed_addresses: failed_addresses.as_ref(), + other_established: non_banned_established, + }); + #[allow(deprecated)] self.behaviour.inject_connection_established( &peer_id, &id, @@ -724,7 +756,11 @@ where } => { let error = error.into(); - self.behaviour.inject_dial_failure(peer, handler, &error); + self.behaviour.on_event(InEvent::DialFailure { + peer_id: peer, + handler, + error: &error, + }); if let Some(peer) = peer { log::debug!("Connection attempt to {:?} failed with {:?}.", peer, error,); @@ -745,8 +781,11 @@ where handler, } => { log::debug!("Incoming connection failed: {:?}", error); - self.behaviour - .inject_listen_failure(&local_addr, &send_back_addr, handler); + self.behaviour.on_event(InEvent::ListenFailure { + local_addr: &local_addr, + send_back_addr: &send_back_addr, + handler, + }); return Some(SwarmEvent::IncomingConnectionError { local_addr, send_back_addr, @@ -785,13 +824,14 @@ where .into_iter() .filter(|conn_id| !self.banned_peer_connections.contains(conn_id)) .count(); - self.behaviour.inject_connection_closed( - &peer_id, - &id, - &endpoint, - handler, - remaining_non_banned, - ); + self.behaviour + .on_event(behaviour::InEvent::ConnectionClosed { + peer_id, + connection_id: id, + endpoint: &endpoint, + handler, + remaining_established: remaining_non_banned, + }); } return Some(SwarmEvent::ConnectionClosed { peer_id, @@ -804,7 +844,11 @@ where if self.banned_peer_connections.contains(&id) { log::debug!("Ignoring event from banned peer: {} {:?}.", peer_id, id); } else { - self.behaviour.inject_event(peer_id, id, event); + self.behaviour.on_event(InEvent::ConnectionHandler { + peer_id, + connection: id, + event, + }); } } PoolEvent::AddressChange { @@ -814,6 +858,13 @@ where old_endpoint, } => { if !self.banned_peer_connections.contains(&id) { + self.behaviour.on_event(behaviour::InEvent::AddressChange { + peer_id, + connection_id: id, + old: &old_endpoint, + new: &new_endpoint, + }); + #[allow(deprecated)] self.behaviour.inject_address_change( &peer_id, &id, @@ -857,8 +908,11 @@ where }); } Err((connection_limit, handler)) => { - self.behaviour - .inject_listen_failure(&local_addr, &send_back_addr, handler); + self.behaviour.on_event(InEvent::ListenFailure { + local_addr: &local_addr, + send_back_addr: &send_back_addr, + handler, + }); log::warn!("Incoming connection rejected: {:?}", connection_limit); } }; @@ -872,6 +926,11 @@ where if !addrs.contains(&listen_addr) { addrs.push(listen_addr.clone()) } + self.behaviour.on_event(InEvent::NewListenAddr { + listener_id, + addr: &listen_addr, + }); + #[allow(deprecated)] self.behaviour .inject_new_listen_addr(listener_id, &listen_addr); return Some(SwarmEvent::NewListenAddr { @@ -891,6 +950,11 @@ where if let Some(addrs) = self.listened_addrs.get_mut(&listener_id) { addrs.retain(|a| a != &listen_addr); } + self.behaviour.on_event(InEvent::ExpiredListenAddr { + listener_id, + addr: &listen_addr, + }); + #[allow(deprecated)] self.behaviour .inject_expired_listen_addr(listener_id, &listen_addr); return Some(SwarmEvent::ExpiredListenAddr { @@ -905,8 +969,19 @@ where log::debug!("Listener {:?}; Closed by {:?}.", listener_id, reason); let addrs = self.listened_addrs.remove(&listener_id).unwrap_or_default(); for addr in addrs.iter() { + self.behaviour + .on_event(InEvent::ExpiredListenAddr { listener_id, addr }); + #[allow(deprecated)] self.behaviour.inject_expired_listen_addr(listener_id, addr); } + self.behaviour.on_event(InEvent::ListenerClosed { + listener_id, + reason: match &reason { + Ok(()) => Ok(()), + Err(err) => Err(err), + }, + }); + #[allow(deprecated)] self.behaviour.inject_listener_closed( listener_id, match &reason { @@ -921,6 +996,11 @@ where }); } TransportEvent::ListenerError { listener_id, error } => { + self.behaviour.on_event(InEvent::ListenerError { + listener_id, + err: &error, + }); + #[allow(deprecated)] self.behaviour.inject_listener_error(listener_id, &error); return Some(SwarmEvent::ListenerError { listener_id, error }); } @@ -1542,13 +1622,63 @@ impl NetworkBehaviour for DummyBehaviour { } } - fn inject_event( - &mut self, - _: PeerId, - _: ConnectionId, - event: ::OutEvent, - ) { - void::unreachable(event) + fn on_event(&mut self, event: InEvent) { + match event { + InEvent::ConnectionHandler { + peer_id: _, + connection: _, + event, + } => void::unreachable(event), + InEvent::ConnectionEstablished { + peer_id: _, + connection_id: _, + endpoint: _, + failed_addresses: _, + other_established: _, + } => {} + InEvent::ConnectionClosed { + peer_id: _, + connection_id: _, + endpoint: _, + handler: _, + remaining_established: _, + } => {} + InEvent::AddressChange { + peer_id: _, + connection_id: _, + old: _, + new: _, + } => {} + InEvent::DialFailure { + peer_id: _, + handler: _, + error: _, + } => {} + InEvent::ListenFailure { + local_addr: _, + send_back_addr: _, + handler: _, + } => {} + InEvent::NewListener { listener_id: _ } => {} + InEvent::NewListenAddr { + listener_id: _, + addr: _, + } => {} + InEvent::ExpiredListenAddr { + listener_id: _, + addr: _, + } => {} + InEvent::ListenerError { + listener_id: _, + err: _, + } => {} + InEvent::ListenerClosed { + listener_id: _, + reason: _, + } => {} + InEvent::NewExternalAddr { addr: _ } => {} + InEvent::ExpiredExternalAddr { addr: _ } => {} + } } fn poll( From de5c46dbe198c756c27de467196324084dee86b8 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Wed, 7 Sep 2022 15:11:36 +0900 Subject: [PATCH 02/60] swarm/behaviour: Delegate to on_event from inject_* --- swarm/src/behaviour.rs | 235 ++++++++++++++++++++++++++--------------- swarm/src/lib.rs | 121 ++++++--------------- 2 files changed, 179 insertions(+), 177 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 1465e2ee401..a8716eeaef9 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -159,146 +159,207 @@ pub trait NetworkBehaviour: 'static { /// Informs the behaviour about a newly established connection to a peer. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ConnectionEstablished` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::ConnectionEstablished` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_connection_established( &mut self, - _peer_id: &PeerId, - _connection_id: &ConnectionId, - _endpoint: &ConnectedPoint, - _failed_addresses: Option<&Vec>, - _other_established: usize, + peer_id: &PeerId, + connection_id: &ConnectionId, + endpoint: &ConnectedPoint, + failed_addresses: Option<&Vec>, + other_established: usize, ) { + self.on_event(InEvent::ConnectionEstablished { + peer_id: *peer_id, + connection_id: *connection_id, + endpoint, + failed_addresses, + other_established, + }); } - // TODO: Have to remove this as it takes ownership of `Handler`. - // - // /// Informs the behaviour about a closed connection to a peer. - // /// - // /// A call to this method is always paired with an earlier call to - // /// [`NetworkBehaviour::inject_connection_established`] with the same peer ID, connection ID and endpoint. - // #[deprecated( - // since = "0.39.0", - // note = "Handle `InEvent::ConnectionClosed` in `NetworkBehaviour::on_event` instead." - // )] - // fn inject_connection_closed( - // &mut self, - // _: &PeerId, - // _: &ConnectionId, - // _: &ConnectedPoint, - // _: ::Handler, - // _remaining_established: usize, - // ) { - // } + /// Informs the behaviour about a closed connection to a peer. + /// + /// A call to this method is always paired with an earlier call to + /// [`NetworkBehaviour::inject_connection_established`] with the same peer ID, connection ID and endpoint. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::ConnectionClosed` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + )] + fn inject_connection_closed( + &mut self, + peer_id: &PeerId, + connection_id: &ConnectionId, + endpoint: &ConnectedPoint, + handler: ::Handler, + remaining_established: usize, + ) { + self.on_event(InEvent::ConnectionClosed { + peer_id: *peer_id, + connection_id: *connection_id, + endpoint, + handler, + remaining_established, + }); + } /// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::AddressChange` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::AddressChange` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_address_change( &mut self, - _: &PeerId, - _: &ConnectionId, - _old: &ConnectedPoint, - _new: &ConnectedPoint, + peer_id: &PeerId, + connection_id: &ConnectionId, + old: &ConnectedPoint, + new: &ConnectedPoint, ) { + self.on_event(InEvent::AddressChange { + peer_id: *peer_id, + connection_id: *connection_id, + old, + new, + }); } - // TODO: Can not deprecate as it takes ownership of handler event. - // - // /// Informs the behaviour about an event generated by the handler dedicated to the peer identified by `peer_id`. - // /// for the behaviour. - // /// - // /// The `peer_id` is guaranteed to be in a connected state. In other words, - // /// [`NetworkBehaviour::inject_connection_established`] has previously been called with this `PeerId`. - // #[deprecated( - // since = "0.39.0", - // note = "Handle `InEvent::ConnectionHandler` in `NetworkBehaviour::on_event` instead." - // )] - // fn inject_event( - // &mut self, - // peer_id: PeerId, - // connection: ConnectionId, - // event: <::Handler as ConnectionHandler>::OutEvent, - // ); - - // TODO: Can not deprecate as it takes ownership of handler. - // - // /// Indicates to the behaviour that the dial to a known or unknown node failed. - // fn inject_dial_failure( - // &mut self, - // _peer_id: Option, - // _handler: Self::ConnectionHandler, - // _error: &DialError, - // ) { - // } - - // TODO: Can not deprecate as it takes ownership of handler. - // - // /// Indicates to the behaviour that an error happened on an incoming connection during its - // /// initial handshake. - // /// - // /// This can include, for example, an error during the handshake of the encryption layer, or the - // /// connection unexpectedly closed. - // fn inject_listen_failure( - // &mut self, - // _local_addr: &Multiaddr, - // _send_back_addr: &Multiaddr, - // _handler: Self::ConnectionHandler, - // ) { - // } + /// Informs the behaviour about an event generated by the handler dedicated to the peer identified by `peer_id`. + /// for the behaviour. + /// + /// The `peer_id` is guaranteed to be in a connected state. In other words, + /// [`NetworkBehaviour::inject_connection_established`] has previously been called with this `PeerId`. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::ConnectionHandler` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + )] + fn inject_event( + &mut self, + peer_id: PeerId, + connection: ConnectionId, + event: <::Handler as ConnectionHandler>::OutEvent, + ) { + self.on_event(InEvent::ConnectionHandler { + peer_id, + connection, + event, + }); + } + + /// Indicates to the behaviour that the dial to a known or unknown node failed. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::DialFailure` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + )] + fn inject_dial_failure( + &mut self, + peer_id: Option, + handler: Self::ConnectionHandler, + error: &DialError, + ) { + self.on_event(InEvent::DialFailure { + peer_id, + handler, + error, + }); + } + + /// Indicates to the behaviour that an error happened on an incoming connection during its + /// initial handshake. + /// + /// This can include, for example, an error during the handshake of the encryption layer, or the + /// connection unexpectedly closed. + #[deprecated( + since = "0.39.0", + note = "Handle `InEvent::ListenFailure` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + )] + fn inject_listen_failure( + &mut self, + local_addr: &Multiaddr, + send_back_addr: &Multiaddr, + handler: Self::ConnectionHandler, + ) { + self.on_event(InEvent::ListenFailure { + local_addr, + send_back_addr, + handler, + }); + } /// Indicates to the behaviour that a new listener was created. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewListener` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::NewListener` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] - fn inject_new_listener(&mut self, _id: ListenerId) {} + fn inject_new_listener(&mut self, id: ListenerId) { + self.on_event(InEvent::NewListener { listener_id: id }); + } /// Indicates to the behaviour that we have started listening on a new multiaddr. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewListenAddr` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::NewListenAddr` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] - fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) {} + fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { + self.on_event(InEvent::NewListenAddr { + listener_id: id, + addr, + }); + } /// Indicates to the behaviour that a multiaddr we were listening on has expired, /// which means that we are no longer listening on it. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ExpiredListenAddr` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::ExpiredListenAddr` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] - fn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) {} + fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { + self.on_event(InEvent::ExpiredListenAddr { + listener_id: id, + addr, + }); + } /// A listener experienced an error. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ListenerError` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::ListenerError` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] - fn inject_listener_error(&mut self, _id: ListenerId, _err: &(dyn std::error::Error + 'static)) { + fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { + self.on_event(InEvent::ListenerError { + listener_id: id, + err, + }); } /// A listener closed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ListenerClosed` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::ListenerClosed` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] - fn inject_listener_closed(&mut self, _id: ListenerId, _reason: Result<(), &std::io::Error>) {} + fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { + self.on_event(InEvent::ListenerClosed { + listener_id: id, + reason, + }); + } /// Indicates to the behaviour that we have discovered a new external address for us. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewExternalAddr` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::NewExternalAddr` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] - fn inject_new_external_addr(&mut self, _addr: &Multiaddr) {} + fn inject_new_external_addr(&mut self, addr: &Multiaddr) { + self.on_event(InEvent::NewExternalAddr { addr }); + } /// Indicates to the behaviour that an external address was removed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ExpiredExternalAddr` in `NetworkBehaviour::on_event` instead." + note = "Handle `InEvent::ExpiredExternalAddr` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." )] - fn inject_expired_external_addr(&mut self, _addr: &Multiaddr) {} + fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { + self.on_event(InEvent::ExpiredExternalAddr { addr }); + } /// Polls for things that swarm should do. /// diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index ed2ecd5c6ce..00a26bf3c78 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -328,8 +328,6 @@ where /// Depending on the underlying transport, one listener may have multiple listening addresses. pub fn listen_on(&mut self, addr: Multiaddr) -> Result> { let id = self.transport.listen_on(addr)?; - self.behaviour - .on_event(InEvent::NewListener { listener_id: id }); #[allow(deprecated)] self.behaviour.inject_new_listener(id); Ok(id) @@ -407,11 +405,12 @@ where PeerCondition::Always => true, }; if !condition_matched { - self.behaviour.on_event(InEvent::DialFailure { - peer_id: Some(peer_id), + #[allow(deprecated)] + self.behaviour.inject_dial_failure( + Some(peer_id), handler, - error: &DialError::DialPeerConditionFalse(condition), - }); + &DialError::DialPeerConditionFalse(condition), + ); return Err(DialError::DialPeerConditionFalse(condition)); } @@ -419,11 +418,9 @@ where // Check if peer is banned. if self.banned_peers.contains(&peer_id) { let error = DialError::Banned; - self.behaviour.on_event(InEvent::DialFailure { - peer_id: Some(peer_id), - handler, - error: &error, - }); + #[allow(deprecated)] + self.behaviour + .inject_dial_failure(Some(peer_id), handler, &error); return Err(error); } @@ -459,11 +456,9 @@ where if addresses.is_empty() { let error = DialError::NoAddresses; - self.behaviour.on_event(InEvent::DialFailure { - peer_id: Some(peer_id), - handler, - error: &error, - }); + #[allow(deprecated)] + self.behaviour + .inject_dial_failure(Some(peer_id), handler, &error); return Err(error); }; @@ -545,11 +540,8 @@ where Ok(_connection_id) => Ok(()), Err((connection_limit, handler)) => { let error = DialError::ConnectionLimit(connection_limit); - self.behaviour.on_event(InEvent::DialFailure { - peer_id: None, - handler, - error: &error, - }); + #[allow(deprecated)] + self.behaviour.inject_dial_failure(None, handler, &error); Err(error) } } @@ -590,8 +582,6 @@ where let result = self.external_addrs.add(a.clone(), s); let expired = match &result { AddAddressResult::Inserted { expired } => { - self.behaviour - .on_event(InEvent::NewExternalAddr { addr: &a }); #[allow(deprecated)] self.behaviour.inject_new_external_addr(&a); expired @@ -599,8 +589,6 @@ where AddAddressResult::Updated { expired } => expired, }; for a in expired { - self.behaviour - .on_event(InEvent::ExpiredExternalAddr { addr: &a.addr }); #[allow(deprecated)] self.behaviour.inject_expired_external_addr(&a.addr); } @@ -615,8 +603,6 @@ where /// otherwise. pub fn remove_external_address(&mut self, addr: &Multiaddr) -> bool { if self.external_addrs.remove(addr) { - self.behaviour - .on_event(InEvent::ExpiredExternalAddr { addr }); #[allow(deprecated)] self.behaviour.inject_expired_external_addr(addr); true @@ -724,14 +710,6 @@ where let failed_addresses = concurrent_dial_errors .as_ref() .map(|es| es.iter().map(|(a, _)| a).cloned().collect()); - self.behaviour - .on_event(behaviour::InEvent::ConnectionEstablished { - peer_id, - connection_id: id, - endpoint: &endpoint, - failed_addresses: failed_addresses.as_ref(), - other_established: non_banned_established, - }); #[allow(deprecated)] self.behaviour.inject_connection_established( &peer_id, @@ -756,11 +734,8 @@ where } => { let error = error.into(); - self.behaviour.on_event(InEvent::DialFailure { - peer_id: peer, - handler, - error: &error, - }); + #[allow(deprecated)] + self.behaviour.inject_dial_failure(peer, handler, &error); if let Some(peer) = peer { log::debug!("Connection attempt to {:?} failed with {:?}.", peer, error,); @@ -781,11 +756,9 @@ where handler, } => { log::debug!("Incoming connection failed: {:?}", error); - self.behaviour.on_event(InEvent::ListenFailure { - local_addr: &local_addr, - send_back_addr: &send_back_addr, - handler, - }); + #[allow(deprecated)] + self.behaviour + .inject_listen_failure(&local_addr, &send_back_addr, handler); return Some(SwarmEvent::IncomingConnectionError { local_addr, send_back_addr, @@ -824,14 +797,14 @@ where .into_iter() .filter(|conn_id| !self.banned_peer_connections.contains(conn_id)) .count(); - self.behaviour - .on_event(behaviour::InEvent::ConnectionClosed { - peer_id, - connection_id: id, - endpoint: &endpoint, - handler, - remaining_established: remaining_non_banned, - }); + #[allow(deprecated)] + self.behaviour.inject_connection_closed( + &peer_id, + &id, + &endpoint, + handler, + remaining_non_banned, + ); } return Some(SwarmEvent::ConnectionClosed { peer_id, @@ -844,11 +817,8 @@ where if self.banned_peer_connections.contains(&id) { log::debug!("Ignoring event from banned peer: {} {:?}.", peer_id, id); } else { - self.behaviour.on_event(InEvent::ConnectionHandler { - peer_id, - connection: id, - event, - }); + #[allow(deprecated)] + self.behaviour.inject_event(peer_id, id, event); } } PoolEvent::AddressChange { @@ -858,12 +828,6 @@ where old_endpoint, } => { if !self.banned_peer_connections.contains(&id) { - self.behaviour.on_event(behaviour::InEvent::AddressChange { - peer_id, - connection_id: id, - old: &old_endpoint, - new: &new_endpoint, - }); #[allow(deprecated)] self.behaviour.inject_address_change( &peer_id, @@ -908,11 +872,9 @@ where }); } Err((connection_limit, handler)) => { - self.behaviour.on_event(InEvent::ListenFailure { - local_addr: &local_addr, - send_back_addr: &send_back_addr, - handler, - }); + #[allow(deprecated)] + self.behaviour + .inject_listen_failure(&local_addr, &send_back_addr, handler); log::warn!("Incoming connection rejected: {:?}", connection_limit); } }; @@ -926,10 +888,6 @@ where if !addrs.contains(&listen_addr) { addrs.push(listen_addr.clone()) } - self.behaviour.on_event(InEvent::NewListenAddr { - listener_id, - addr: &listen_addr, - }); #[allow(deprecated)] self.behaviour .inject_new_listen_addr(listener_id, &listen_addr); @@ -950,10 +908,6 @@ where if let Some(addrs) = self.listened_addrs.get_mut(&listener_id) { addrs.retain(|a| a != &listen_addr); } - self.behaviour.on_event(InEvent::ExpiredListenAddr { - listener_id, - addr: &listen_addr, - }); #[allow(deprecated)] self.behaviour .inject_expired_listen_addr(listener_id, &listen_addr); @@ -969,18 +923,9 @@ where log::debug!("Listener {:?}; Closed by {:?}.", listener_id, reason); let addrs = self.listened_addrs.remove(&listener_id).unwrap_or_default(); for addr in addrs.iter() { - self.behaviour - .on_event(InEvent::ExpiredListenAddr { listener_id, addr }); #[allow(deprecated)] self.behaviour.inject_expired_listen_addr(listener_id, addr); } - self.behaviour.on_event(InEvent::ListenerClosed { - listener_id, - reason: match &reason { - Ok(()) => Ok(()), - Err(err) => Err(err), - }, - }); #[allow(deprecated)] self.behaviour.inject_listener_closed( listener_id, @@ -996,10 +941,6 @@ where }); } TransportEvent::ListenerError { listener_id, error } => { - self.behaviour.on_event(InEvent::ListenerError { - listener_id, - err: &error, - }); #[allow(deprecated)] self.behaviour.inject_listener_error(listener_id, &error); return Some(SwarmEvent::ListenerError { listener_id, error }); From 021a7f1338fed87338fb27430502cd6eb1604fe4 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Wed, 7 Sep 2022 15:25:31 +0900 Subject: [PATCH 03/60] swarm/behaviour: Address code review --- swarm/src/behaviour.rs | 4 ++-- swarm/src/behaviour/either.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index a8716eeaef9..2582d72ecf8 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -152,7 +152,7 @@ pub trait NetworkBehaviour: 'static { vec![] } - /// Informs the behaviour about an event from the [Transport](libp2p_core::Transport) or the + /// Informs the behaviour about an event from the [`Transport`](libp2p_core::Transport) or the /// [`ConnectionHandler`]. fn on_event(&mut self, _event: InEvent); @@ -851,7 +851,7 @@ pub enum InEvent<'a, Handler: IntoConnectionHandler> { }, /// Informs the behaviour about a closed connection to a peer. /// - /// This event is always paired with an earlier call to + /// This event is always paired with an earlier /// [`InEvent::ConnectionEstablished`] with the same peer ID, connection ID /// and endpoint. ConnectionClosed { diff --git a/swarm/src/behaviour/either.rs b/swarm/src/behaviour/either.rs index e9677ff419a..3daf5c13c18 100644 --- a/swarm/src/behaviour/either.rs +++ b/swarm/src/behaviour/either.rs @@ -18,8 +18,8 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::behaviour::{self, NetworkBehaviour, NetworkBehaviourAction, PollParameters}; use crate::handler::either::IntoEitherHandler; -use crate::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; use either::Either; use libp2p_core::{Multiaddr, PeerId}; use std::{task::Context, task::Poll}; @@ -47,7 +47,7 @@ where } } - fn on_event(&mut self, event: super::InEvent) { + fn on_event(&mut self, event: behaviour::InEvent) { match self { Either::Left(b) => b.on_event(event.map_handler( |h| h.unwrap_left(), From 07a4f201b78978cb56a6f24fd1426de5664447cc Mon Sep 17 00:00:00 2001 From: Max Inden Date: Sat, 17 Sep 2022 17:35:27 +0200 Subject: [PATCH 04/60] swarm/behaviour: Add on_connection_handler_event --- swarm/src/behaviour.rs | 114 ++++++++++++++-------------------- swarm/src/behaviour/either.rs | 25 ++++++-- swarm/src/behaviour/toggle.rs | 17 ++++- swarm/src/lib.rs | 16 +++-- 4 files changed, 91 insertions(+), 81 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 2582d72ecf8..b99e0603f9e 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -152,14 +152,29 @@ pub trait NetworkBehaviour: 'static { vec![] } - /// Informs the behaviour about an event from the [`Transport`](libp2p_core::Transport) or the - /// [`ConnectionHandler`]. - fn on_event(&mut self, _event: InEvent); + // TODO: Should we add an empty default implementation? That way this is not a breaking change. + /// Informs the behaviour about an event from the [`Swarm`](crate::Swarm). + fn on_swarm_event(&mut self, _event: InEvent); + + // TODO: Should we add an empty default implementation? That way this is not a breaking change. + /// Informs the behaviour about an event generated by the [`ConnectionHandler`] dedicated to the + /// peer identified by `peer_id`. for the behaviour. + /// + /// The [`PeerId`] is guaranteed to be in a connected state. In other words, + /// [`InEvent::ConnectionEstablished`] has previously been received with this [`PeerId`]. + fn on_connection_handler_event( + &mut self, + peer_id: PeerId, + connection_id: ConnectionId, + // TODO: Instead of the type alias THandlerOutEvent the full definition might be more + // intuitive for users outside of libp2p-swarm. + event: crate::THandlerOutEvent, + ); /// Informs the behaviour about a newly established connection to a peer. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ConnectionEstablished` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::ConnectionEstablished` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_connection_established( &mut self, @@ -169,7 +184,7 @@ pub trait NetworkBehaviour: 'static { failed_addresses: Option<&Vec>, other_established: usize, ) { - self.on_event(InEvent::ConnectionEstablished { + self.on_swarm_event(InEvent::ConnectionEstablished { peer_id: *peer_id, connection_id: *connection_id, endpoint, @@ -184,7 +199,7 @@ pub trait NetworkBehaviour: 'static { /// [`NetworkBehaviour::inject_connection_established`] with the same peer ID, connection ID and endpoint. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ConnectionClosed` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::ConnectionClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_connection_closed( &mut self, @@ -194,7 +209,7 @@ pub trait NetworkBehaviour: 'static { handler: ::Handler, remaining_established: usize, ) { - self.on_event(InEvent::ConnectionClosed { + self.on_swarm_event(InEvent::ConnectionClosed { peer_id: *peer_id, connection_id: *connection_id, endpoint, @@ -206,7 +221,7 @@ pub trait NetworkBehaviour: 'static { /// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::AddressChange` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::AddressChange` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_address_change( &mut self, @@ -215,7 +230,7 @@ pub trait NetworkBehaviour: 'static { old: &ConnectedPoint, new: &ConnectedPoint, ) { - self.on_event(InEvent::AddressChange { + self.on_swarm_event(InEvent::AddressChange { peer_id: *peer_id, connection_id: *connection_id, old, @@ -230,7 +245,7 @@ pub trait NetworkBehaviour: 'static { /// [`NetworkBehaviour::inject_connection_established`] has previously been called with this `PeerId`. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ConnectionHandler` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Implement `NetworkBehaviour::on_connection_handler_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_event( &mut self, @@ -238,17 +253,13 @@ pub trait NetworkBehaviour: 'static { connection: ConnectionId, event: <::Handler as ConnectionHandler>::OutEvent, ) { - self.on_event(InEvent::ConnectionHandler { - peer_id, - connection, - event, - }); + self.on_connection_handler_event(peer_id, connection, event); } /// Indicates to the behaviour that the dial to a known or unknown node failed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::DialFailure` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::DialFailure` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_dial_failure( &mut self, @@ -256,7 +267,7 @@ pub trait NetworkBehaviour: 'static { handler: Self::ConnectionHandler, error: &DialError, ) { - self.on_event(InEvent::DialFailure { + self.on_swarm_event(InEvent::DialFailure { peer_id, handler, error, @@ -270,7 +281,7 @@ pub trait NetworkBehaviour: 'static { /// connection unexpectedly closed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ListenFailure` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::ListenFailure` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listen_failure( &mut self, @@ -278,7 +289,7 @@ pub trait NetworkBehaviour: 'static { send_back_addr: &Multiaddr, handler: Self::ConnectionHandler, ) { - self.on_event(InEvent::ListenFailure { + self.on_swarm_event(InEvent::ListenFailure { local_addr, send_back_addr, handler, @@ -288,19 +299,19 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that a new listener was created. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewListener` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::NewListener` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_listener(&mut self, id: ListenerId) { - self.on_event(InEvent::NewListener { listener_id: id }); + self.on_swarm_event(InEvent::NewListener { listener_id: id }); } /// Indicates to the behaviour that we have started listening on a new multiaddr. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewListenAddr` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::NewListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.on_event(InEvent::NewListenAddr { + self.on_swarm_event(InEvent::NewListenAddr { listener_id: id, addr, }); @@ -310,10 +321,10 @@ pub trait NetworkBehaviour: 'static { /// which means that we are no longer listening on it. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ExpiredListenAddr` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::ExpiredListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.on_event(InEvent::ExpiredListenAddr { + self.on_swarm_event(InEvent::ExpiredListenAddr { listener_id: id, addr, }); @@ -322,10 +333,10 @@ pub trait NetworkBehaviour: 'static { /// A listener experienced an error. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ListenerError` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::ListenerError` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { - self.on_event(InEvent::ListenerError { + self.on_swarm_event(InEvent::ListenerError { listener_id: id, err, }); @@ -334,10 +345,10 @@ pub trait NetworkBehaviour: 'static { /// A listener closed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ListenerClosed` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::ListenerClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { - self.on_event(InEvent::ListenerClosed { + self.on_swarm_event(InEvent::ListenerClosed { listener_id: id, reason, }); @@ -346,19 +357,19 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that we have discovered a new external address for us. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewExternalAddr` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::NewExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_external_addr(&mut self, addr: &Multiaddr) { - self.on_event(InEvent::NewExternalAddr { addr }); + self.on_swarm_event(InEvent::NewExternalAddr { addr }); } /// Indicates to the behaviour that an external address was removed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ExpiredExternalAddr` in `NetworkBehaviour::on_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `InEvent::ExpiredExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { - self.on_event(InEvent::ExpiredExternalAddr { addr }); + self.on_swarm_event(InEvent::ExpiredExternalAddr { addr }); } /// Polls for things that swarm should do. @@ -839,6 +850,7 @@ impl Default for CloseConnection { } } +// TODO: Rename to FromSwarm pub enum InEvent<'a, Handler: IntoConnectionHandler> { /// Informs the behaviour about a newly established connection to a peer. ConnectionEstablished { @@ -869,16 +881,6 @@ pub enum InEvent<'a, Handler: IntoConnectionHandler> { old: &'a ConnectedPoint, new: &'a ConnectedPoint, }, - /// Informs the behaviour about an event generated by the handler dedicated to the peer - /// identified by `peer_id`. for the behaviour. - /// - /// The `peer_id` is guaranteed to be in a connected state. In other words, - /// [`InEvent::ConnectionEstablished`] has previously been received with this `PeerId`. - ConnectionHandler { - peer_id: PeerId, - connection: ConnectionId, - event: <::Handler as ConnectionHandler>::OutEvent, - }, /// Indicates to the behaviour that the dial to a known or unknown node failed. DialFailure { peer_id: Option, @@ -931,20 +933,12 @@ impl<'a, Handler: IntoConnectionHandler> InEvent<'a, Handler> { map_handler: impl FnOnce( ::Handler, ) -> ::Handler, - map_event: impl FnOnce( - <::Handler as ConnectionHandler>::OutEvent, - ) -> - <::Handler as ConnectionHandler>::OutEvent, ) -> InEvent<'a, NewHandler> where NewHandler: IntoConnectionHandler, { - self.try_map_handler( - |h| Some(map_into_handler(h)), - |h| Some(map_handler(h)), - |e| Some(map_event(e)), - ) - .expect("To return Some as all closures return Some.") + self.try_map_handler(|h| Some(map_into_handler(h)), |h| Some(map_handler(h))) + .expect("To return Some as all closures return Some.") } fn try_map_handler( @@ -953,11 +947,6 @@ impl<'a, Handler: IntoConnectionHandler> InEvent<'a, Handler> { map_handler: impl FnOnce( ::Handler, ) -> Option<::Handler>, - map_event: impl FnOnce( - <::Handler as ConnectionHandler>::OutEvent, - ) -> Option< - <::Handler as ConnectionHandler>::OutEvent, - >, ) -> Option> where NewHandler: IntoConnectionHandler, @@ -1000,15 +989,6 @@ impl<'a, Handler: IntoConnectionHandler> InEvent<'a, Handler> { old, new, }), - InEvent::ConnectionHandler { - peer_id, - connection, - event, - } => Some(InEvent::ConnectionHandler { - peer_id, - connection, - event: map_event(event)?, - }), InEvent::DialFailure { peer_id, handler, diff --git a/swarm/src/behaviour/either.rs b/swarm/src/behaviour/either.rs index 3daf5c13c18..59bc0f389e1 100644 --- a/swarm/src/behaviour/either.rs +++ b/swarm/src/behaviour/either.rs @@ -47,27 +47,42 @@ where } } - fn on_event(&mut self, event: behaviour::InEvent) { + fn on_swarm_event(&mut self, event: behaviour::InEvent) { match self { - Either::Left(b) => b.on_event(event.map_handler( + Either::Left(b) => b.on_swarm_event(event.map_handler( |h| h.unwrap_left(), |h| match h { Either::Left(h) => h, Either::Right(_) => unreachable!(), }, - |e| e.unwrap_left(), )), - Either::Right(b) => b.on_event(event.map_handler( + Either::Right(b) => b.on_swarm_event(event.map_handler( |h| h.unwrap_right(), |h| match h { Either::Right(h) => h, Either::Left(_) => unreachable!(), }, - |e| e.unwrap_right(), )), } } + fn on_connection_handler_event( + &mut self, + peer_id: PeerId, + connection_id: libp2p_core::connection::ConnectionId, + event: crate::THandlerOutEvent, + ) { + match (self, event) { + (Either::Left(left), Either::Left(event)) => { + left.on_connection_handler_event(peer_id, connection_id, event) + } + (Either::Right(right), Either::Right(event)) => { + right.on_connection_handler_event(peer_id, connection_id, event) + } + _ => unreachable!(), + } + } + fn poll( &mut self, cx: &mut Context<'_>, diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index 6561876e555..bdc245eeadc 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -82,14 +82,25 @@ where .unwrap_or_else(Vec::new) } - fn on_event(&mut self, event: super::InEvent) { + fn on_swarm_event(&mut self, event: super::InEvent) { if let Some(behaviour) = &mut self.inner { - if let Some(event) = event.try_map_handler(|h| h.inner, |h| h.inner, |e| Some(e)) { - behaviour.on_event(event); + if let Some(event) = event.try_map_handler(|h| h.inner, |h| h.inner) { + behaviour.on_swarm_event(event); } } } + fn on_connection_handler_event( + &mut self, + peer_id: PeerId, + connection_id: libp2p_core::connection::ConnectionId, + event: crate::THandlerOutEvent, + ) { + if let Some(behaviour) = &mut self.inner { + behaviour.on_connection_handler_event(peer_id, connection_id, event) + } + } + fn poll( &mut self, cx: &mut Context<'_>, diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 14799100ba4..b37715442ba 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -1563,13 +1563,8 @@ impl NetworkBehaviour for DummyBehaviour { } } - fn on_event(&mut self, event: InEvent) { + fn on_swarm_event(&mut self, event: InEvent) { match event { - InEvent::ConnectionHandler { - peer_id: _, - connection: _, - event, - } => void::unreachable(event), InEvent::ConnectionEstablished { peer_id: _, connection_id: _, @@ -1622,6 +1617,15 @@ impl NetworkBehaviour for DummyBehaviour { } } + fn on_connection_handler_event( + &mut self, + _peer_id: PeerId, + _connection_id: ConnectionId, + event: crate::THandlerOutEvent, + ) { + void::unreachable(event) + } + fn poll( &mut self, _: &mut Context<'_>, From 99a4b64f2a4c1715aa5da641c314955bd277e077 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Sat, 17 Sep 2022 16:53:38 +0100 Subject: [PATCH 05/60] swarm/behaviour: Use slice --- swarm/src/behaviour.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index b99e0603f9e..e9735d204fe 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -188,7 +188,9 @@ pub trait NetworkBehaviour: 'static { peer_id: *peer_id, connection_id: *connection_id, endpoint, - failed_addresses, + failed_addresses: failed_addresses + .map(|v| v.as_slice()) + .unwrap_or_else(|| &[]), other_established, }); } @@ -857,8 +859,7 @@ pub enum InEvent<'a, Handler: IntoConnectionHandler> { peer_id: PeerId, connection_id: ConnectionId, endpoint: &'a ConnectedPoint, - // TODO: Would a slice not be better? - failed_addresses: Option<&'a Vec>, + failed_addresses: &'a [Multiaddr], other_established: usize, }, /// Informs the behaviour about a closed connection to a peer. From 46f20fab508c916eb02a50a84260ad427cd817e1 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Sat, 17 Sep 2022 17:55:52 +0200 Subject: [PATCH 06/60] swarm/behaviour: Rename to maybe_map_handler --- swarm/src/behaviour.rs | 4 ++-- swarm/src/behaviour/toggle.rs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index e9735d204fe..d682ed1ead4 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -938,11 +938,11 @@ impl<'a, Handler: IntoConnectionHandler> InEvent<'a, Handler> { where NewHandler: IntoConnectionHandler, { - self.try_map_handler(|h| Some(map_into_handler(h)), |h| Some(map_handler(h))) + self.maybe_map_handler(|h| Some(map_into_handler(h)), |h| Some(map_handler(h))) .expect("To return Some as all closures return Some.") } - fn try_map_handler( + fn maybe_map_handler( self, map_into_handler: impl FnOnce(Handler) -> Option, map_handler: impl FnOnce( diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index bdc245eeadc..ea5a2d736ed 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -84,7 +84,7 @@ where fn on_swarm_event(&mut self, event: super::InEvent) { if let Some(behaviour) = &mut self.inner { - if let Some(event) = event.try_map_handler(|h| h.inner, |h| h.inner) { + if let Some(event) = event.maybe_map_handler(|h| h.inner, |h| h.inner) { behaviour.on_swarm_event(event); } } From 63b70fe60d723ce75510dc0cfea81302b92a7f58 Mon Sep 17 00:00:00 2001 From: Max Inden Date: Sat, 17 Sep 2022 17:58:02 +0200 Subject: [PATCH 07/60] swarm/behaviour: Provide default for on_swarm and on_connection This allows rolling out the whole patch set in a non-breaking way. --- swarm/src/behaviour.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index d682ed1ead4..887d1a11231 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -152,11 +152,9 @@ pub trait NetworkBehaviour: 'static { vec![] } - // TODO: Should we add an empty default implementation? That way this is not a breaking change. /// Informs the behaviour about an event from the [`Swarm`](crate::Swarm). - fn on_swarm_event(&mut self, _event: InEvent); + fn on_swarm_event(&mut self, _event: InEvent) {} - // TODO: Should we add an empty default implementation? That way this is not a breaking change. /// Informs the behaviour about an event generated by the [`ConnectionHandler`] dedicated to the /// peer identified by `peer_id`. for the behaviour. /// @@ -164,12 +162,13 @@ pub trait NetworkBehaviour: 'static { /// [`InEvent::ConnectionEstablished`] has previously been received with this [`PeerId`]. fn on_connection_handler_event( &mut self, - peer_id: PeerId, - connection_id: ConnectionId, + _peer_id: PeerId, + _connection_id: ConnectionId, // TODO: Instead of the type alias THandlerOutEvent the full definition might be more // intuitive for users outside of libp2p-swarm. - event: crate::THandlerOutEvent, - ); + _event: crate::THandlerOutEvent, + ) { + } /// Informs the behaviour about a newly established connection to a peer. #[deprecated( From 1a33678c00d9d4ccd0c1fca057a1f0b52a6e9eb1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 11 Oct 2022 15:20:46 +0100 Subject: [PATCH 08/60] review: address suggestions --- swarm/src/behaviour.rs | 107 +++++++++++++++++----------------- swarm/src/behaviour/either.rs | 2 +- swarm/src/behaviour/toggle.rs | 2 +- swarm/src/handler/either.rs | 2 + swarm/src/lib.rs | 56 +----------------- swarm/tests/public_api.rs | 64 ++++++++++++++++++++ 6 files changed, 123 insertions(+), 110 deletions(-) create mode 100644 swarm/tests/public_api.rs diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 887d1a11231..2227e73c9de 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -153,19 +153,17 @@ pub trait NetworkBehaviour: 'static { } /// Informs the behaviour about an event from the [`Swarm`](crate::Swarm). - fn on_swarm_event(&mut self, _event: InEvent) {} + fn on_swarm_event(&mut self, _event: FromSwarm) {} /// Informs the behaviour about an event generated by the [`ConnectionHandler`] dedicated to the /// peer identified by `peer_id`. for the behaviour. /// /// The [`PeerId`] is guaranteed to be in a connected state. In other words, - /// [`InEvent::ConnectionEstablished`] has previously been received with this [`PeerId`]. + /// [`FromSwarm::ConnectionEstablished`] has previously been received with this [`PeerId`]. fn on_connection_handler_event( &mut self, _peer_id: PeerId, _connection_id: ConnectionId, - // TODO: Instead of the type alias THandlerOutEvent the full definition might be more - // intuitive for users outside of libp2p-swarm. _event: crate::THandlerOutEvent, ) { } @@ -173,7 +171,7 @@ pub trait NetworkBehaviour: 'static { /// Informs the behaviour about a newly established connection to a peer. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ConnectionEstablished` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::ConnectionEstablished` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_connection_established( &mut self, @@ -183,7 +181,7 @@ pub trait NetworkBehaviour: 'static { failed_addresses: Option<&Vec>, other_established: usize, ) { - self.on_swarm_event(InEvent::ConnectionEstablished { + self.on_swarm_event(FromSwarm::ConnectionEstablished { peer_id: *peer_id, connection_id: *connection_id, endpoint, @@ -200,7 +198,7 @@ pub trait NetworkBehaviour: 'static { /// [`NetworkBehaviour::inject_connection_established`] with the same peer ID, connection ID and endpoint. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ConnectionClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::ConnectionClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_connection_closed( &mut self, @@ -210,7 +208,7 @@ pub trait NetworkBehaviour: 'static { handler: ::Handler, remaining_established: usize, ) { - self.on_swarm_event(InEvent::ConnectionClosed { + self.on_swarm_event(FromSwarm::ConnectionClosed { peer_id: *peer_id, connection_id: *connection_id, endpoint, @@ -222,7 +220,7 @@ pub trait NetworkBehaviour: 'static { /// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::AddressChange` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::AddressChange` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_address_change( &mut self, @@ -231,7 +229,7 @@ pub trait NetworkBehaviour: 'static { old: &ConnectedPoint, new: &ConnectedPoint, ) { - self.on_swarm_event(InEvent::AddressChange { + self.on_swarm_event(FromSwarm::AddressChange { peer_id: *peer_id, connection_id: *connection_id, old, @@ -268,7 +266,7 @@ pub trait NetworkBehaviour: 'static { handler: Self::ConnectionHandler, error: &DialError, ) { - self.on_swarm_event(InEvent::DialFailure { + self.on_swarm_event(FromSwarm::DialFailure { peer_id, handler, error, @@ -282,7 +280,7 @@ pub trait NetworkBehaviour: 'static { /// connection unexpectedly closed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ListenFailure` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::ListenFailure` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listen_failure( &mut self, @@ -290,7 +288,7 @@ pub trait NetworkBehaviour: 'static { send_back_addr: &Multiaddr, handler: Self::ConnectionHandler, ) { - self.on_swarm_event(InEvent::ListenFailure { + self.on_swarm_event(FromSwarm::ListenFailure { local_addr, send_back_addr, handler, @@ -300,19 +298,19 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that a new listener was created. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewListener` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::NewListener` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_listener(&mut self, id: ListenerId) { - self.on_swarm_event(InEvent::NewListener { listener_id: id }); + self.on_swarm_event(FromSwarm::NewListener { listener_id: id }); } /// Indicates to the behaviour that we have started listening on a new multiaddr. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::NewListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.on_swarm_event(InEvent::NewListenAddr { + self.on_swarm_event(FromSwarm::NewListenAddr { listener_id: id, addr, }); @@ -322,10 +320,10 @@ pub trait NetworkBehaviour: 'static { /// which means that we are no longer listening on it. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ExpiredListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::ExpiredListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.on_swarm_event(InEvent::ExpiredListenAddr { + self.on_swarm_event(FromSwarm::ExpiredListenAddr { listener_id: id, addr, }); @@ -334,10 +332,10 @@ pub trait NetworkBehaviour: 'static { /// A listener experienced an error. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ListenerError` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::ListenerError` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { - self.on_swarm_event(InEvent::ListenerError { + self.on_swarm_event(FromSwarm::ListenerError { listener_id: id, err, }); @@ -346,10 +344,10 @@ pub trait NetworkBehaviour: 'static { /// A listener closed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ListenerClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::ListenerClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { - self.on_swarm_event(InEvent::ListenerClosed { + self.on_swarm_event(FromSwarm::ListenerClosed { listener_id: id, reason, }); @@ -358,19 +356,19 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that we have discovered a new external address for us. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::NewExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::NewExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_external_addr(&mut self, addr: &Multiaddr) { - self.on_swarm_event(InEvent::NewExternalAddr { addr }); + self.on_swarm_event(FromSwarm::NewExternalAddr { addr }); } /// Indicates to the behaviour that an external address was removed. #[deprecated( since = "0.39.0", - note = "Handle `InEvent::ExpiredExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." + note = "Handle `FromSwarm::ExpiredExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { - self.on_swarm_event(InEvent::ExpiredExternalAddr { addr }); + self.on_swarm_event(FromSwarm::ExpiredExternalAddr { addr }); } /// Polls for things that swarm should do. @@ -851,8 +849,7 @@ impl Default for CloseConnection { } } -// TODO: Rename to FromSwarm -pub enum InEvent<'a, Handler: IntoConnectionHandler> { +pub enum FromSwarm<'a, Handler: IntoConnectionHandler> { /// Informs the behaviour about a newly established connection to a peer. ConnectionEstablished { peer_id: PeerId, @@ -864,7 +861,7 @@ pub enum InEvent<'a, Handler: IntoConnectionHandler> { /// Informs the behaviour about a closed connection to a peer. /// /// This event is always paired with an earlier - /// [`InEvent::ConnectionEstablished`] with the same peer ID, connection ID + /// [`FromSwarm::ConnectionEstablished`] with the same peer ID, connection ID /// and endpoint. ConnectionClosed { peer_id: PeerId, @@ -926,14 +923,14 @@ pub enum InEvent<'a, Handler: IntoConnectionHandler> { ExpiredExternalAddr { addr: &'a Multiaddr }, } -impl<'a, Handler: IntoConnectionHandler> InEvent<'a, Handler> { +impl<'a, Handler: IntoConnectionHandler> FromSwarm<'a, Handler> { fn map_handler( self, map_into_handler: impl FnOnce(Handler) -> NewHandler, map_handler: impl FnOnce( ::Handler, ) -> ::Handler, - ) -> InEvent<'a, NewHandler> + ) -> FromSwarm<'a, NewHandler> where NewHandler: IntoConnectionHandler, { @@ -947,85 +944,87 @@ impl<'a, Handler: IntoConnectionHandler> InEvent<'a, Handler> { map_handler: impl FnOnce( ::Handler, ) -> Option<::Handler>, - ) -> Option> + ) -> Option> where NewHandler: IntoConnectionHandler, { match self { - InEvent::ConnectionClosed { + FromSwarm::ConnectionClosed { peer_id, connection_id, endpoint, handler, remaining_established, - } => Some(InEvent::ConnectionClosed { + } => Some(FromSwarm::ConnectionClosed { peer_id, connection_id, endpoint, handler: map_handler(handler)?, remaining_established, }), - InEvent::ConnectionEstablished { + FromSwarm::ConnectionEstablished { peer_id, connection_id, endpoint, failed_addresses, other_established, - } => Some(InEvent::ConnectionEstablished { + } => Some(FromSwarm::ConnectionEstablished { peer_id, connection_id, endpoint, failed_addresses, other_established, }), - InEvent::AddressChange { + FromSwarm::AddressChange { peer_id, connection_id, old, new, - } => Some(InEvent::AddressChange { + } => Some(FromSwarm::AddressChange { peer_id, connection_id, old, new, }), - InEvent::DialFailure { + FromSwarm::DialFailure { peer_id, handler, error, - } => Some(InEvent::DialFailure { + } => Some(FromSwarm::DialFailure { peer_id, handler: map_into_handler(handler)?, error, }), - InEvent::ListenFailure { + FromSwarm::ListenFailure { local_addr, send_back_addr, handler, - } => Some(InEvent::ListenFailure { + } => Some(FromSwarm::ListenFailure { local_addr, send_back_addr, handler: map_into_handler(handler)?, }), - InEvent::NewListener { listener_id } => Some(InEvent::NewListener { listener_id }), - InEvent::NewListenAddr { listener_id, addr } => { - Some(InEvent::NewListenAddr { listener_id, addr }) + FromSwarm::NewListener { listener_id } => Some(FromSwarm::NewListener { listener_id }), + FromSwarm::NewListenAddr { listener_id, addr } => { + Some(FromSwarm::NewListenAddr { listener_id, addr }) } - InEvent::ExpiredListenAddr { listener_id, addr } => { - Some(InEvent::ExpiredListenAddr { listener_id, addr }) + FromSwarm::ExpiredListenAddr { listener_id, addr } => { + Some(FromSwarm::ExpiredListenAddr { listener_id, addr }) } - InEvent::ListenerError { listener_id, err } => { - Some(InEvent::ListenerError { listener_id, err }) + FromSwarm::ListenerError { listener_id, err } => { + Some(FromSwarm::ListenerError { listener_id, err }) } - InEvent::ListenerClosed { + FromSwarm::ListenerClosed { listener_id, reason, - } => Some(InEvent::ListenerClosed { + } => Some(FromSwarm::ListenerClosed { listener_id, reason, }), - InEvent::NewExternalAddr { addr } => Some(InEvent::NewExternalAddr { addr }), - InEvent::ExpiredExternalAddr { addr } => Some(InEvent::ExpiredExternalAddr { addr }), + FromSwarm::NewExternalAddr { addr } => Some(FromSwarm::NewExternalAddr { addr }), + FromSwarm::ExpiredExternalAddr { addr } => { + Some(FromSwarm::ExpiredExternalAddr { addr }) + } } } } diff --git a/swarm/src/behaviour/either.rs b/swarm/src/behaviour/either.rs index 59bc0f389e1..7c8171e5a9c 100644 --- a/swarm/src/behaviour/either.rs +++ b/swarm/src/behaviour/either.rs @@ -47,7 +47,7 @@ where } } - fn on_swarm_event(&mut self, event: behaviour::InEvent) { + fn on_swarm_event(&mut self, event: behaviour::FromSwarm) { match self { Either::Left(b) => b.on_swarm_event(event.map_handler( |h| h.unwrap_left(), diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index ea5a2d736ed..6d886425a6f 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -82,7 +82,7 @@ where .unwrap_or_else(Vec::new) } - fn on_swarm_event(&mut self, event: super::InEvent) { + fn on_swarm_event(&mut self, event: super::FromSwarm) { if let Some(behaviour) = &mut self.inner { if let Some(event) = event.maybe_map_handler(|h| h.inner, |h| h.inner) { behaviour.on_swarm_event(event); diff --git a/swarm/src/handler/either.rs b/swarm/src/handler/either.rs index 2823b6ed824..53007b5a181 100644 --- a/swarm/src/handler/either.rs +++ b/swarm/src/handler/either.rs @@ -29,6 +29,8 @@ use libp2p_core::upgrade::{EitherUpgrade, UpgradeError}; use libp2p_core::{ConnectedPoint, Multiaddr, PeerId}; use std::task::{Context, Poll}; +/// Auxiliary type to allow implementing [`IntoConnectionHandler`]. As [`IntoConnectionHandler`] is +/// already implemented for T, we cannot implement it for Either. pub enum IntoEitherHandler { Left(L), Right(R), diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index b37715442ba..b8cfcf9368d 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -63,7 +63,7 @@ pub mod behaviour; pub mod dial_opts; pub mod handler; -use behaviour::InEvent; +use behaviour::FromSwarm; pub use behaviour::{ CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; @@ -1563,59 +1563,7 @@ impl NetworkBehaviour for DummyBehaviour { } } - fn on_swarm_event(&mut self, event: InEvent) { - match event { - InEvent::ConnectionEstablished { - peer_id: _, - connection_id: _, - endpoint: _, - failed_addresses: _, - other_established: _, - } => {} - InEvent::ConnectionClosed { - peer_id: _, - connection_id: _, - endpoint: _, - handler: _, - remaining_established: _, - } => {} - InEvent::AddressChange { - peer_id: _, - connection_id: _, - old: _, - new: _, - } => {} - InEvent::DialFailure { - peer_id: _, - handler: _, - error: _, - } => {} - InEvent::ListenFailure { - local_addr: _, - send_back_addr: _, - handler: _, - } => {} - InEvent::NewListener { listener_id: _ } => {} - InEvent::NewListenAddr { - listener_id: _, - addr: _, - } => {} - InEvent::ExpiredListenAddr { - listener_id: _, - addr: _, - } => {} - InEvent::ListenerError { - listener_id: _, - err: _, - } => {} - InEvent::ListenerClosed { - listener_id: _, - reason: _, - } => {} - InEvent::NewExternalAddr { addr: _ } => {} - InEvent::ExpiredExternalAddr { addr: _ } => {} - } - } + fn on_swarm_event(&mut self, _event: FromSwarm) {} fn on_connection_handler_event( &mut self, diff --git a/swarm/tests/public_api.rs b/swarm/tests/public_api.rs new file mode 100644 index 00000000000..e61c2165f7b --- /dev/null +++ b/swarm/tests/public_api.rs @@ -0,0 +1,64 @@ +use libp2p::core::transport::ListenerId; +use libp2p::swarm::behaviour::FromSwarm; +use libp2p::swarm::handler::DummyConnectionHandler; + +#[test] +// test to break compilation everytime a variant changes, +// forcing us to revisit each implementation +fn swarm_event_variants() { + let event: FromSwarm<'_, DummyConnectionHandler> = FromSwarm::ListenerClosed { + listener_id: ListenerId::new(), + reason: Ok(()), + }; + match event { + FromSwarm::ConnectionEstablished { + peer_id: _, + connection_id: _, + endpoint: _, + failed_addresses: _, + other_established: _, + } => {} + FromSwarm::ConnectionClosed { + peer_id: _, + connection_id: _, + endpoint: _, + handler: _, + remaining_established: _, + } => {} + FromSwarm::AddressChange { + peer_id: _, + connection_id: _, + old: _, + new: _, + } => {} + FromSwarm::DialFailure { + peer_id: _, + handler: _, + error: _, + } => {} + FromSwarm::ListenFailure { + local_addr: _, + send_back_addr: _, + handler: _, + } => {} + FromSwarm::NewListener { listener_id: _ } => {} + FromSwarm::NewListenAddr { + listener_id: _, + addr: _, + } => {} + FromSwarm::ExpiredListenAddr { + listener_id: _, + addr: _, + } => {} + FromSwarm::ListenerError { + listener_id: _, + err: _, + } => {} + FromSwarm::ListenerClosed { + listener_id: _, + reason: _, + } => {} + FromSwarm::NewExternalAddr { addr: _ } => {} + FromSwarm::ExpiredExternalAddr { addr: _ } => {} + } +} From 09ca72360331097ec258351c7139fa55c6ba1e54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 11 Oct 2022 17:31:03 +0100 Subject: [PATCH 09/60] autonat/behaviour: Replace inject_* with on_event --- protocols/autonat/src/behaviour.rs | 249 +++++++++++++++++++++++------ 1 file changed, 202 insertions(+), 47 deletions(-) diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index b39a7b141b4..5c2024dd40f 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -37,7 +37,8 @@ use libp2p_request_response::{ RequestResponseConfig, RequestResponseEvent, RequestResponseMessage, ResponseChannel, }; use libp2p_swarm::{ - DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, + behaviour::FromSwarm, DialError, IntoConnectionHandler, NetworkBehaviour, + NetworkBehaviourAction, PollParameters, }; use std::{ collections::{HashMap, VecDeque}, @@ -298,28 +299,24 @@ impl Behaviour { ongoing_inbound: &mut self.ongoing_inbound, } } -} - -impl NetworkBehaviour for Behaviour { - type ConnectionHandler = as NetworkBehaviour>::ConnectionHandler; - type OutEvent = Event; - fn inject_connection_established( + fn on_connection_established( &mut self, - peer: &PeerId, - conn: &ConnectionId, + peer_id: PeerId, + connection_id: ConnectionId, endpoint: &ConnectedPoint, - failed_addresses: Option<&Vec>, + failed_addresses: &[Multiaddr], other_established: usize, ) { - self.inner.inject_connection_established( - peer, - conn, + self.inner.on_swarm_event(FromSwarm::ConnectionEstablished { + peer_id, + connection_id, endpoint, failed_addresses, other_established, - ); - let connections = self.connected.entry(*peer).or_default(); + }); + + let connections = self.connected.entry(peer_id).or_default(); let addr = endpoint.get_remote_address(); let observed_addr = if !endpoint.is_relayed() && (!self.config.only_global_ips || addr.is_global_ip()) { @@ -327,14 +324,14 @@ impl NetworkBehaviour for Behaviour { } else { None }; - connections.insert(*conn, observed_addr); + connections.insert(connection_id, observed_addr); match endpoint { ConnectedPoint::Dialer { address, role_override: Endpoint::Dialer, } => { - if let Some(event) = self.as_server().on_outbound_connection(peer, address) { + if let Some(event) = self.as_server().on_outbound_connection(&peer_id, address) { self.pending_out_events .push_back(Event::InboundProbe(event)); } @@ -351,50 +348,71 @@ impl NetworkBehaviour for Behaviour { } } - fn inject_connection_closed( + fn on_connection_closed( &mut self, - peer: &PeerId, - conn: &ConnectionId, + peer_id: PeerId, + connection_id: ConnectionId, endpoint: &ConnectedPoint, - handler: ::Handler, + handler: as NetworkBehaviour>::ConnectionHandler, remaining_established: usize, ) { - self.inner - .inject_connection_closed(peer, conn, endpoint, handler, remaining_established); + self.inner.on_swarm_event(FromSwarm::ConnectionClosed { + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + }); + if remaining_established == 0 { - self.connected.remove(peer); + self.connected.remove(&peer_id); } else { - let connections = self.connected.get_mut(peer).expect("Peer is connected."); - connections.remove(conn); + let connections = self + .connected + .get_mut(&peer_id) + .expect("Peer is connected."); + connections.remove(&connection_id); } } - fn inject_dial_failure( + fn on_dial_failure( &mut self, - peer: Option, - handler: Self::ConnectionHandler, + peer_id: Option, + handler: as NetworkBehaviour>::ConnectionHandler, error: &DialError, ) { - self.inner.inject_dial_failure(peer, handler, error); - if let Some(event) = self.as_server().on_outbound_dial_error(peer, error) { + self.inner.on_swarm_event(FromSwarm::DialFailure { + peer_id, + handler, + error, + }); + if let Some(event) = self.as_server().on_outbound_dial_error(peer_id, error) { self.pending_out_events .push_back(Event::InboundProbe(event)); } } - fn inject_address_change( + fn on_address_change( &mut self, - peer: &PeerId, - conn: &ConnectionId, + peer_id: PeerId, + connection_id: ConnectionId, old: &ConnectedPoint, new: &ConnectedPoint, ) { - self.inner.inject_address_change(peer, conn, old, new); + self.inner.on_swarm_event(FromSwarm::AddressChange { + peer_id, + connection_id, + old, + new, + }); if old.is_relayed() && new.is_relayed() { return; } - let connections = self.connected.get_mut(peer).expect("Peer is connected."); + let connections = self + .connected + .get_mut(&peer_id) + .expect("Peer is connected."); let addr = new.get_remote_address(); let observed_addr = if !new.is_relayed() && (!self.config.only_global_ips || addr.is_global_ip()) { @@ -402,26 +420,83 @@ impl NetworkBehaviour for Behaviour { } else { None }; - connections.insert(*conn, observed_addr); + connections.insert(connection_id, observed_addr); + } +} + +impl NetworkBehaviour for Behaviour { + type ConnectionHandler = as NetworkBehaviour>::ConnectionHandler; + type OutEvent = Event; + + fn inject_connection_established( + &mut self, + peer: &PeerId, + conn: &ConnectionId, + endpoint: &ConnectedPoint, + failed_addresses: Option<&Vec>, + other_established: usize, + ) { + let failed_addresses = failed_addresses + .map(|v| v.as_slice()) + .unwrap_or_else(|| &[]); + self.on_connection_established(*peer, *conn, endpoint, failed_addresses, other_established) + } + + fn inject_connection_closed( + &mut self, + peer: &PeerId, + conn: &ConnectionId, + endpoint: &ConnectedPoint, + handler: ::Handler, + remaining_established: usize, + ) { + self.on_connection_closed(*peer, *conn, endpoint, handler, remaining_established) + } + + fn inject_dial_failure( + &mut self, + peer: Option, + handler: Self::ConnectionHandler, + error: &DialError, + ) { + self.on_dial_failure(peer, handler, error) + } + + fn inject_address_change( + &mut self, + peer: &PeerId, + conn: &ConnectionId, + old: &ConnectedPoint, + new: &ConnectedPoint, + ) { + self.on_address_change(*peer, *conn, old, new) } fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.inner.inject_new_listen_addr(id, addr); + self.inner.on_swarm_event(FromSwarm::NewListenAddr { + listener_id: id, + addr, + }); self.as_client().on_new_address(); } fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.inner.inject_expired_listen_addr(id, addr); + self.inner.on_swarm_event(FromSwarm::ExpiredListenAddr { + listener_id: id, + addr, + }); self.as_client().on_expired_address(addr); } fn inject_new_external_addr(&mut self, addr: &Multiaddr) { - self.inner.inject_new_external_addr(addr); + self.inner + .on_swarm_event(FromSwarm::NewExternalAddr { addr }); self.as_client().on_new_address(); } fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { - self.inner.inject_expired_external_addr(addr); + self.inner + .on_swarm_event(FromSwarm::ExpiredExternalAddr { addr }); self.as_client().on_expired_address(addr); } @@ -484,7 +559,7 @@ impl NetworkBehaviour for Behaviour { conn: ConnectionId, event: RequestResponseHandlerEvent, ) { - self.inner.inject_event(peer_id, conn, event) + self.inner.on_connection_handler_event(peer_id, conn, event) } fn inject_listen_failure( @@ -493,20 +568,100 @@ impl NetworkBehaviour for Behaviour { send_back_addr: &Multiaddr, handler: Self::ConnectionHandler, ) { - self.inner - .inject_listen_failure(local_addr, send_back_addr, handler) + self.inner.on_swarm_event(FromSwarm::ListenFailure { + local_addr, + send_back_addr, + handler, + }); } fn inject_new_listener(&mut self, id: ListenerId) { - self.inner.inject_new_listener(id) + self.inner + .on_swarm_event(FromSwarm::NewListener { listener_id: id }) } fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { - self.inner.inject_listener_error(id, err) + self.inner.on_swarm_event(FromSwarm::ListenerError { + listener_id: id, + err, + }); } fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { - self.inner.inject_listener_closed(id, reason) + self.inner.on_swarm_event(FromSwarm::ListenerClosed { + listener_id: id, + reason, + }); + } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + } => self.on_connection_established( + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + ), + FromSwarm::ConnectionClosed { + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + } => self.on_connection_closed( + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + ), + FromSwarm::DialFailure { + peer_id, + handler, + error, + } => self.on_dial_failure(peer_id, handler, error), + FromSwarm::AddressChange { + peer_id, + connection_id, + old, + new, + } => self.on_address_change(peer_id, connection_id, old, new), + listen_addr @ FromSwarm::NewListenAddr { .. } => { + self.inner.on_swarm_event(listen_addr); + self.as_client().on_new_address(); + } + FromSwarm::ExpiredListenAddr { listener_id, addr } => { + self.inner + .on_swarm_event(FromSwarm::ExpiredListenAddr { listener_id, addr }); + self.as_client().on_expired_address(addr); + } + FromSwarm::ExpiredExternalAddr { addr } => { + self.inner + .on_swarm_event(FromSwarm::ExpiredExternalAddr { addr }); + self.as_client().on_expired_address(addr); + } + new_external_addr @ FromSwarm::NewExternalAddr { .. } => { + self.inner.on_swarm_event(new_external_addr); + self.as_client().on_new_address(); + } + listen_failure @ FromSwarm::ListenFailure { .. } => { + self.inner.on_swarm_event(listen_failure) + } + new_listener @ FromSwarm::NewListener { .. } => self.inner.on_swarm_event(new_listener), + listener_error @ FromSwarm::ListenerError { .. } => { + self.inner.on_swarm_event(listener_error) + } + listener_closed @ FromSwarm::ListenerClosed { .. } => { + self.inner.on_swarm_event(listener_closed) + } + } } } From 4f5cc26623b31dd69445552b31a40e0cbfdbb305 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 11 Oct 2022 21:49:03 +0100 Subject: [PATCH 10/60] swarm: remove no longer required DummyBehaviour --- protocols/autonat/src/behaviour.rs | 10 +++--- swarm/src/lib.rs | 55 ------------------------------ swarm/tests/public_api.rs | 4 +-- 3 files changed, 6 insertions(+), 63 deletions(-) diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index 5c2024dd40f..47bdf1dd589 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -29,16 +29,14 @@ pub use as_server::{InboundProbeError, InboundProbeEvent}; use futures_timer::Delay; use instant::Instant; use libp2p_core::{ - connection::ConnectionId, multiaddr::Protocol, transport::ListenerId, ConnectedPoint, Endpoint, - Multiaddr, PeerId, + connection::ConnectionId, multiaddr::Protocol, ConnectedPoint, Endpoint, Multiaddr, PeerId, }; use libp2p_request_response::{ - handler::RequestResponseHandlerEvent, ProtocolSupport, RequestId, RequestResponse, - RequestResponseConfig, RequestResponseEvent, RequestResponseMessage, ResponseChannel, + ProtocolSupport, RequestId, RequestResponse, RequestResponseConfig, RequestResponseEvent, + RequestResponseMessage, ResponseChannel, }; use libp2p_swarm::{ - behaviour::FromSwarm, DialError, IntoConnectionHandler, NetworkBehaviour, - NetworkBehaviourAction, PollParameters, + behaviour::FromSwarm, DialError, NetworkBehaviour, NetworkBehaviourAction, PollParameters, }; use std::{ collections::{HashMap, VecDeque}, diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index e708c27784d..adb2205d3fc 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -65,7 +65,6 @@ pub mod dummy; pub mod handler; pub mod keep_alive; -use behaviour::FromSwarm; pub use behaviour::{ CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; @@ -1537,60 +1536,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 on_swarm_event(&mut self, _event: FromSwarm) {} - - fn on_connection_handler_event( - &mut self, - _peer_id: PeerId, - _connection_id: ConnectionId, - event: crate::THandlerOutEvent, - ) { - 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 { diff --git a/swarm/tests/public_api.rs b/swarm/tests/public_api.rs index e61c2165f7b..ca9d05a8d84 100644 --- a/swarm/tests/public_api.rs +++ b/swarm/tests/public_api.rs @@ -1,12 +1,12 @@ use libp2p::core::transport::ListenerId; use libp2p::swarm::behaviour::FromSwarm; -use libp2p::swarm::handler::DummyConnectionHandler; +use libp2p::swarm::dummy; #[test] // test to break compilation everytime a variant changes, // forcing us to revisit each implementation fn swarm_event_variants() { - let event: FromSwarm<'_, DummyConnectionHandler> = FromSwarm::ListenerClosed { + let event: FromSwarm<'_, dummy::ConnectionHandler> = FromSwarm::ListenerClosed { listener_id: ListenerId::new(), reason: Ok(()), }; From 510fd5e2b68e4e1949ad23da6475275a9c0cf0a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 11 Oct 2022 22:27:26 +0100 Subject: [PATCH 11/60] autonat/behaviour: remove no longer needed inject methods --- protocols/autonat/src/behaviour.rs | 113 ----------------------------- 1 file changed, 113 deletions(-) diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index 47bdf1dd589..605274f9220 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -426,78 +426,6 @@ impl NetworkBehaviour for Behaviour { type ConnectionHandler = as NetworkBehaviour>::ConnectionHandler; type OutEvent = Event; - fn inject_connection_established( - &mut self, - peer: &PeerId, - conn: &ConnectionId, - endpoint: &ConnectedPoint, - failed_addresses: Option<&Vec>, - other_established: usize, - ) { - let failed_addresses = failed_addresses - .map(|v| v.as_slice()) - .unwrap_or_else(|| &[]); - self.on_connection_established(*peer, *conn, endpoint, failed_addresses, other_established) - } - - fn inject_connection_closed( - &mut self, - peer: &PeerId, - conn: &ConnectionId, - endpoint: &ConnectedPoint, - handler: ::Handler, - remaining_established: usize, - ) { - self.on_connection_closed(*peer, *conn, endpoint, handler, remaining_established) - } - - fn inject_dial_failure( - &mut self, - peer: Option, - handler: Self::ConnectionHandler, - error: &DialError, - ) { - self.on_dial_failure(peer, handler, error) - } - - fn inject_address_change( - &mut self, - peer: &PeerId, - conn: &ConnectionId, - old: &ConnectedPoint, - new: &ConnectedPoint, - ) { - self.on_address_change(*peer, *conn, old, new) - } - - fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.inner.on_swarm_event(FromSwarm::NewListenAddr { - listener_id: id, - addr, - }); - self.as_client().on_new_address(); - } - - fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.inner.on_swarm_event(FromSwarm::ExpiredListenAddr { - listener_id: id, - addr, - }); - self.as_client().on_expired_address(addr); - } - - fn inject_new_external_addr(&mut self, addr: &Multiaddr) { - self.inner - .on_swarm_event(FromSwarm::NewExternalAddr { addr }); - self.as_client().on_new_address(); - } - - fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { - self.inner - .on_swarm_event(FromSwarm::ExpiredExternalAddr { addr }); - self.as_client().on_expired_address(addr); - } - fn poll(&mut self, cx: &mut Context<'_>, params: &mut impl PollParameters) -> Poll { loop { if let Some(event) = self.pending_out_events.pop_front() { @@ -551,47 +479,6 @@ impl NetworkBehaviour for Behaviour { self.inner.addresses_of_peer(peer) } - fn inject_event( - &mut self, - peer_id: PeerId, - conn: ConnectionId, - event: RequestResponseHandlerEvent, - ) { - self.inner.on_connection_handler_event(peer_id, conn, event) - } - - fn inject_listen_failure( - &mut self, - local_addr: &Multiaddr, - send_back_addr: &Multiaddr, - handler: Self::ConnectionHandler, - ) { - self.inner.on_swarm_event(FromSwarm::ListenFailure { - local_addr, - send_back_addr, - handler, - }); - } - - fn inject_new_listener(&mut self, id: ListenerId) { - self.inner - .on_swarm_event(FromSwarm::NewListener { listener_id: id }) - } - - fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { - self.inner.on_swarm_event(FromSwarm::ListenerError { - listener_id: id, - err, - }); - } - - fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { - self.inner.on_swarm_event(FromSwarm::ListenerClosed { - listener_id: id, - reason, - }); - } - fn on_swarm_event(&mut self, event: FromSwarm) { match event { FromSwarm::ConnectionEstablished { From 9b60343042b1857cfb086a078723dfad1c7c08a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 12 Oct 2022 11:33:59 +0100 Subject: [PATCH 12/60] swarm/behaviour: use full definition instead of type alias, on on_connection_handler_event --- swarm/src/behaviour.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index f5972569438..2e27282cbc7 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -164,7 +164,8 @@ pub trait NetworkBehaviour: 'static { &mut self, _peer_id: PeerId, _connection_id: ConnectionId, - _event: crate::THandlerOutEvent, + _event: <::Handler as + ConnectionHandler>::OutEvent, ) { } From feccba08b583decfa52d46519e7523cac2980e20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 14 Oct 2022 10:33:33 +0100 Subject: [PATCH 13/60] swarm/behaviour: update FromSwarm enum variants to structs --- swarm/src/behaviour.rs | 286 +++++++++++++++++++++++++---------------- 1 file changed, 178 insertions(+), 108 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 2e27282cbc7..1fc3b109268 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -182,7 +182,7 @@ pub trait NetworkBehaviour: 'static { failed_addresses: Option<&Vec>, other_established: usize, ) { - self.on_swarm_event(FromSwarm::ConnectionEstablished { + self.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { peer_id: *peer_id, connection_id: *connection_id, endpoint, @@ -190,7 +190,7 @@ pub trait NetworkBehaviour: 'static { .map(|v| v.as_slice()) .unwrap_or_else(|| &[]), other_established, - }); + })); } /// Informs the behaviour about a closed connection to a peer. @@ -209,13 +209,13 @@ pub trait NetworkBehaviour: 'static { handler: ::Handler, remaining_established: usize, ) { - self.on_swarm_event(FromSwarm::ConnectionClosed { + self.on_swarm_event(FromSwarm::ConnectionClosed(ConnectionClosed { peer_id: *peer_id, connection_id: *connection_id, endpoint, handler, remaining_established, - }); + })); } /// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed. @@ -230,12 +230,12 @@ pub trait NetworkBehaviour: 'static { old: &ConnectedPoint, new: &ConnectedPoint, ) { - self.on_swarm_event(FromSwarm::AddressChange { + self.on_swarm_event(FromSwarm::AddressChange(AddressChange { peer_id: *peer_id, connection_id: *connection_id, old, new, - }); + })); } /// Informs the behaviour about an event generated by the handler dedicated to the peer identified by `peer_id`. @@ -267,11 +267,11 @@ pub trait NetworkBehaviour: 'static { handler: Self::ConnectionHandler, error: &DialError, ) { - self.on_swarm_event(FromSwarm::DialFailure { + self.on_swarm_event(FromSwarm::DialFailure(DialFailure { peer_id, handler, error, - }); + })); } /// Indicates to the behaviour that an error happened on an incoming connection during its @@ -289,11 +289,11 @@ pub trait NetworkBehaviour: 'static { send_back_addr: &Multiaddr, handler: Self::ConnectionHandler, ) { - self.on_swarm_event(FromSwarm::ListenFailure { + self.on_swarm_event(FromSwarm::ListenFailure(ListenFailure { local_addr, send_back_addr, handler, - }); + })); } /// Indicates to the behaviour that a new listener was created. @@ -302,7 +302,7 @@ pub trait NetworkBehaviour: 'static { note = "Handle `FromSwarm::NewListener` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_listener(&mut self, id: ListenerId) { - self.on_swarm_event(FromSwarm::NewListener { listener_id: id }); + self.on_swarm_event(FromSwarm::NewListener(NewListener { listener_id: id })); } /// Indicates to the behaviour that we have started listening on a new multiaddr. @@ -311,10 +311,10 @@ pub trait NetworkBehaviour: 'static { note = "Handle `FromSwarm::NewListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.on_swarm_event(FromSwarm::NewListenAddr { + self.on_swarm_event(FromSwarm::NewListenAddr(NewListenAddr { listener_id: id, addr, - }); + })); } /// Indicates to the behaviour that a multiaddr we were listening on has expired, @@ -324,10 +324,10 @@ pub trait NetworkBehaviour: 'static { note = "Handle `FromSwarm::ExpiredListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { - self.on_swarm_event(FromSwarm::ExpiredListenAddr { + self.on_swarm_event(FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id: id, addr, - }); + })); } /// A listener experienced an error. @@ -336,10 +336,10 @@ pub trait NetworkBehaviour: 'static { note = "Handle `FromSwarm::ListenerError` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { - self.on_swarm_event(FromSwarm::ListenerError { + self.on_swarm_event(FromSwarm::ListenerError(ListenerError { listener_id: id, err, - }); + })); } /// A listener closed. @@ -348,10 +348,10 @@ pub trait NetworkBehaviour: 'static { note = "Handle `FromSwarm::ListenerClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { - self.on_swarm_event(FromSwarm::ListenerClosed { + self.on_swarm_event(FromSwarm::ListenerClosed(ListenerClosed { listener_id: id, reason, - }); + })); } /// Indicates to the behaviour that we have discovered a new external address for us. @@ -360,7 +360,7 @@ pub trait NetworkBehaviour: 'static { note = "Handle `FromSwarm::NewExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_external_addr(&mut self, addr: &Multiaddr) { - self.on_swarm_event(FromSwarm::NewExternalAddr { addr }); + self.on_swarm_event(FromSwarm::NewExternalAddr(NewExternalAddr { addr })); } /// Indicates to the behaviour that an external address was removed. @@ -369,7 +369,7 @@ pub trait NetworkBehaviour: 'static { note = "Handle `FromSwarm::ExpiredExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { - self.on_swarm_event(FromSwarm::ExpiredExternalAddr { addr }); + self.on_swarm_event(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr })); } /// Polls for things that swarm should do. @@ -850,78 +850,138 @@ impl Default for CloseConnection { } } +/// Enumeration with the list of the possible events +/// to pass to [`on_swarm_event`](NetworkBehaviour::on_swarm_event). pub enum FromSwarm<'a, Handler: IntoConnectionHandler> { /// Informs the behaviour about a newly established connection to a peer. - ConnectionEstablished { - peer_id: PeerId, - connection_id: ConnectionId, - endpoint: &'a ConnectedPoint, - failed_addresses: &'a [Multiaddr], - other_established: usize, - }, + ConnectionEstablished(ConnectionEstablished<'a>), /// Informs the behaviour about a closed connection to a peer. /// /// This event is always paired with an earlier /// [`FromSwarm::ConnectionEstablished`] with the same peer ID, connection ID /// and endpoint. - ConnectionClosed { - peer_id: PeerId, - connection_id: ConnectionId, - endpoint: &'a ConnectedPoint, - handler: ::Handler, - remaining_established: usize, - }, + ConnectionClosed(ConnectionClosed<'a, Handler>), /// Informs the behaviour that the [`ConnectedPoint`] of an existing /// connection has changed. - AddressChange { - peer_id: PeerId, - connection_id: ConnectionId, - old: &'a ConnectedPoint, - new: &'a ConnectedPoint, - }, - /// Indicates to the behaviour that the dial to a known or unknown node failed. - DialFailure { - peer_id: Option, - handler: Handler, - error: &'a DialError, - }, - /// Indicates to the behaviour that an error happened on an incoming connection during its - /// initial handshake. + AddressChange(AddressChange<'a>), + /// Informs the behaviour that the dial to a known + /// or unknown node failed. + DialFailure(DialFailure<'a, Handler>), + /// Informs the behaviour that an error + /// happened on an incoming connection during its initial handshake. /// /// This can include, for example, an error during the handshake of the encryption layer, or the /// connection unexpectedly closed. - ListenFailure { - local_addr: &'a Multiaddr, - send_back_addr: &'a Multiaddr, - handler: Handler, - }, - /// Indicates to the behaviour that a new listener was created. - NewListener { listener_id: ListenerId }, - /// Indicates to the behaviour that we have started listening on a new multiaddr. - NewListenAddr { - listener_id: ListenerId, - addr: &'a Multiaddr, - }, - /// Indicates to the behaviour that a multiaddr we were listening on has expired, + ListenFailure(ListenFailure<'a, Handler>), + /// Informs the behaviour that a new listener was created. + NewListener(NewListener), + /// Informs the behaviour that we have started listening on a new multiaddr. + NewListenAddr(NewListenAddr<'a>), + /// Informs the behaviour that a multiaddr + /// we were listening on has expired, /// which means that we are no longer listening on it. - ExpiredListenAddr { - listener_id: ListenerId, - addr: &'a Multiaddr, - }, - /// A listener experienced an error. - ListenerError { - listener_id: ListenerId, - err: &'a (dyn std::error::Error + 'static), - }, - /// A listener closed. - ListenerClosed { - listener_id: ListenerId, - reason: Result<(), &'a std::io::Error>, - }, - /// Indicates to the behaviour that we have discovered a new external address for us. - NewExternalAddr { addr: &'a Multiaddr }, - /// Indicates to the behaviour that an external address was removed. - ExpiredExternalAddr { addr: &'a Multiaddr }, + ExpiredListenAddr(ExpiredListenAddr<'a>), + /// Informs the behaviour that a listener experienced an error. + ListenerError(ListenerError<'a>), + /// Informs the behaviour that a listener closed. + ListenerClosed(ListenerClosed<'a>), + /// Informs the behaviour that we have discovered a new external address for us. + NewExternalAddr(NewExternalAddr<'a>), + /// Informs the behaviour that an external address was removed. + ExpiredExternalAddr(ExpiredExternalAddr<'a>), +} + +/// [`FromSwarm`] variant that informs the behaviour about a newly established connection to a peer. +pub struct ConnectionEstablished<'a> { + pub peer_id: PeerId, + pub connection_id: ConnectionId, + pub endpoint: &'a ConnectedPoint, + pub failed_addresses: &'a [Multiaddr], + pub other_established: usize, +} + +/// [`FromSwarm`] variant that informs the behaviour about a closed connection to a peer. +/// +/// This event is always paired with an earlier +/// [`FromSwarm::ConnectionEstablished`] with the same peer ID, connection ID +/// and endpoint. +pub struct ConnectionClosed<'a, Handler: IntoConnectionHandler> { + pub peer_id: PeerId, + pub connection_id: ConnectionId, + pub endpoint: &'a ConnectedPoint, + pub handler: ::Handler, + pub remaining_established: usize, +} + +/// [`FromSwarm`] variant that informs the behaviour that the [`ConnectedPoint`] of an existing +/// connection has changed. +pub struct AddressChange<'a> { + pub peer_id: PeerId, + pub connection_id: ConnectionId, + pub old: &'a ConnectedPoint, + pub new: &'a ConnectedPoint, +} + +/// [`FromSwarm`] variant that informs the behaviour that the dial to a known +/// or unknown node failed. +pub struct DialFailure<'a, Handler> { + pub peer_id: Option, + pub handler: Handler, + pub error: &'a DialError, +} + +/// [`FromSwarm`] variant that informs the behaviour that an error +/// happened on an incoming connection during its initial handshake. +/// +/// This can include, for example, an error during the handshake of the encryption layer, or the +/// connection unexpectedly closed. +pub struct ListenFailure<'a, Handler> { + pub local_addr: &'a Multiaddr, + pub send_back_addr: &'a Multiaddr, + pub handler: Handler, +} + +/// [`FromSwarm`] variant that informs the behaviour that a new listener was created. +pub struct NewListener { + pub listener_id: ListenerId, +} + +/// [`FromSwarm`] variant that informs the behaviour +/// that we have started listening on a new multiaddr. +pub struct NewListenAddr<'a> { + pub listener_id: ListenerId, + pub addr: &'a Multiaddr, +} + +/// [`FromSwarm`] variant that informs the behaviour that a multiaddr +/// we were listening on has expired, +/// which means that we are no longer listening on it. +pub struct ExpiredListenAddr<'a> { + pub listener_id: ListenerId, + pub addr: &'a Multiaddr, +} + +/// [`FromSwarm`] variant that informs the behaviour that a listener experienced an error. +pub struct ListenerError<'a> { + pub listener_id: ListenerId, + pub err: &'a (dyn std::error::Error + 'static), +} + +/// [`FromSwarm`] variant that informs the behaviour that a listener closed. +pub struct ListenerClosed<'a> { + pub listener_id: ListenerId, + pub reason: Result<(), &'a std::io::Error>, +} + +/// [`FromSwarm`] variant that informs the behaviour +/// that we have discovered a new external address for us. +pub struct NewExternalAddr<'a> { + pub addr: &'a Multiaddr, +} + +/// [`FromSwarm`] variant that informs the behaviour that an external address was removed. +pub struct ExpiredExternalAddr<'a> { + pub addr: &'a Multiaddr, } impl<'a, Handler: IntoConnectionHandler> FromSwarm<'a, Handler> { @@ -950,81 +1010,91 @@ impl<'a, Handler: IntoConnectionHandler> FromSwarm<'a, Handler> { NewHandler: IntoConnectionHandler, { match self { - FromSwarm::ConnectionClosed { + FromSwarm::ConnectionClosed(ConnectionClosed { peer_id, connection_id, endpoint, handler, remaining_established, - } => Some(FromSwarm::ConnectionClosed { + }) => Some(FromSwarm::ConnectionClosed(ConnectionClosed { peer_id, connection_id, endpoint, handler: map_handler(handler)?, remaining_established, - }), - FromSwarm::ConnectionEstablished { + })), + FromSwarm::ConnectionEstablished(ConnectionEstablished { peer_id, connection_id, endpoint, failed_addresses, other_established, - } => Some(FromSwarm::ConnectionEstablished { + }) => Some(FromSwarm::ConnectionEstablished(ConnectionEstablished { peer_id, connection_id, endpoint, failed_addresses, other_established, - }), - FromSwarm::AddressChange { + })), + FromSwarm::AddressChange(AddressChange { peer_id, connection_id, old, new, - } => Some(FromSwarm::AddressChange { + }) => Some(FromSwarm::AddressChange(AddressChange { peer_id, connection_id, old, new, - }), - FromSwarm::DialFailure { + })), + FromSwarm::DialFailure(DialFailure { peer_id, handler, error, - } => Some(FromSwarm::DialFailure { + }) => Some(FromSwarm::DialFailure(DialFailure { peer_id, handler: map_into_handler(handler)?, error, - }), - FromSwarm::ListenFailure { + })), + FromSwarm::ListenFailure(ListenFailure { local_addr, send_back_addr, handler, - } => Some(FromSwarm::ListenFailure { + }) => Some(FromSwarm::ListenFailure(ListenFailure { local_addr, send_back_addr, handler: map_into_handler(handler)?, - }), - FromSwarm::NewListener { listener_id } => Some(FromSwarm::NewListener { listener_id }), - FromSwarm::NewListenAddr { listener_id, addr } => { - Some(FromSwarm::NewListenAddr { listener_id, addr }) + })), + FromSwarm::NewListener(NewListener { listener_id }) => { + Some(FromSwarm::NewListener(NewListener { listener_id })) + } + FromSwarm::NewListenAddr(NewListenAddr { listener_id, addr }) => { + Some(FromSwarm::NewListenAddr(NewListenAddr { + listener_id, + addr, + })) } - FromSwarm::ExpiredListenAddr { listener_id, addr } => { - Some(FromSwarm::ExpiredListenAddr { listener_id, addr }) + FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id, addr }) => { + Some(FromSwarm::ExpiredListenAddr(ExpiredListenAddr { + listener_id, + addr, + })) } - FromSwarm::ListenerError { listener_id, err } => { - Some(FromSwarm::ListenerError { listener_id, err }) + FromSwarm::ListenerError(ListenerError { listener_id, err }) => { + Some(FromSwarm::ListenerError(ListenerError { listener_id, err })) } - FromSwarm::ListenerClosed { + FromSwarm::ListenerClosed(ListenerClosed { listener_id, reason, - } => Some(FromSwarm::ListenerClosed { + }) => Some(FromSwarm::ListenerClosed(ListenerClosed { listener_id, reason, - }), - FromSwarm::NewExternalAddr { addr } => Some(FromSwarm::NewExternalAddr { addr }), - FromSwarm::ExpiredExternalAddr { addr } => { - Some(FromSwarm::ExpiredExternalAddr { addr }) + })), + FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => { + Some(FromSwarm::NewExternalAddr(NewExternalAddr { addr })) + } + FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }) => { + Some(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr })) } } } From 6dc84f84efea8096bd346321ec31cb37452eb6c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 14 Oct 2022 13:47:10 +0100 Subject: [PATCH 14/60] autonat/behaviour: update on_swarm_event, to use new FromSwarm variant structs --- protocols/autonat/src/behaviour.rs | 154 ++++++++++++++--------------- swarm/src/behaviour.rs | 1 + 2 files changed, 77 insertions(+), 78 deletions(-) diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index 605274f9220..1c8398ef21b 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -36,7 +36,11 @@ use libp2p_request_response::{ RequestResponseMessage, ResponseChannel, }; use libp2p_swarm::{ - behaviour::FromSwarm, DialError, NetworkBehaviour, NetworkBehaviourAction, PollParameters, + behaviour::{ + AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr, + ExpiredListenAddr, FromSwarm, + }, + NetworkBehaviour, NetworkBehaviourAction, PollParameters, }; use std::{ collections::{HashMap, VecDeque}, @@ -298,21 +302,26 @@ impl Behaviour { } } + /// Called on the [`FromSwarm::ConnectionEstablished`] + /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, - peer_id: PeerId, - connection_id: ConnectionId, - endpoint: &ConnectedPoint, - failed_addresses: &[Multiaddr], - other_established: usize, - ) { - self.inner.on_swarm_event(FromSwarm::ConnectionEstablished { + ConnectionEstablished { peer_id, connection_id, endpoint, failed_addresses, other_established, - }); + }: ConnectionEstablished, + ) { + self.inner + .on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + })); let connections = self.connected.entry(peer_id).or_default(); let addr = endpoint.get_remote_address(); @@ -346,21 +355,26 @@ impl Behaviour { } } + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, - peer_id: PeerId, - connection_id: ConnectionId, - endpoint: &ConnectedPoint, - handler: as NetworkBehaviour>::ConnectionHandler, - remaining_established: usize, - ) { - self.inner.on_swarm_event(FromSwarm::ConnectionClosed { + ConnectionClosed { peer_id, connection_id, endpoint, handler, remaining_established, - }); + }: ConnectionClosed<::ConnectionHandler>, + ) { + self.inner + .on_swarm_event(FromSwarm::ConnectionClosed(ConnectionClosed { + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + })); if remaining_established == 0 { self.connected.remove(&peer_id); @@ -373,36 +387,46 @@ impl Behaviour { } } + /// Called on the [`FromSwarm::DialFailure`] + /// [event](`NetworkBehaviour::on_swarm_event`). fn on_dial_failure( &mut self, - peer_id: Option, - handler: as NetworkBehaviour>::ConnectionHandler, - error: &DialError, - ) { - self.inner.on_swarm_event(FromSwarm::DialFailure { + DialFailure { peer_id, handler, error, - }); + }: DialFailure<::ConnectionHandler>, + ) { + self.inner + .on_swarm_event(FromSwarm::DialFailure(DialFailure { + peer_id, + handler, + error, + })); if let Some(event) = self.as_server().on_outbound_dial_error(peer_id, error) { self.pending_out_events .push_back(Event::InboundProbe(event)); } } + /// Called on the [`FromSwarm::AddressChange`] + /// [event](`NetworkBehaviour::on_swarm_event`). fn on_address_change( &mut self, - peer_id: PeerId, - connection_id: ConnectionId, - old: &ConnectedPoint, - new: &ConnectedPoint, - ) { - self.inner.on_swarm_event(FromSwarm::AddressChange { + AddressChange { peer_id, connection_id, old, new, - }); + }: AddressChange, + ) { + self.inner + .on_swarm_event(FromSwarm::AddressChange(AddressChange { + peer_id, + connection_id, + old, + new, + })); if old.is_relayed() && new.is_relayed() { return; @@ -481,69 +505,43 @@ impl NetworkBehaviour for Behaviour { fn on_swarm_event(&mut self, event: FromSwarm) { match event { - FromSwarm::ConnectionEstablished { - peer_id, - connection_id, - endpoint, - failed_addresses, - other_established, - } => self.on_connection_established( - peer_id, - connection_id, - endpoint, - failed_addresses, - other_established, - ), - FromSwarm::ConnectionClosed { - peer_id, - connection_id, - endpoint, - handler, - remaining_established, - } => self.on_connection_closed( - peer_id, - connection_id, - endpoint, - handler, - remaining_established, - ), - FromSwarm::DialFailure { - peer_id, - handler, - error, - } => self.on_dial_failure(peer_id, handler, error), - FromSwarm::AddressChange { - peer_id, - connection_id, - old, - new, - } => self.on_address_change(peer_id, connection_id, old, new), - listen_addr @ FromSwarm::NewListenAddr { .. } => { + FromSwarm::ConnectionEstablished(connection_established) => { + self.on_connection_established(connection_established) + } + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), + FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), + listen_addr @ FromSwarm::NewListenAddr(_) => { self.inner.on_swarm_event(listen_addr); self.as_client().on_new_address(); } - FromSwarm::ExpiredListenAddr { listener_id, addr } => { + FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id, addr }) => { self.inner - .on_swarm_event(FromSwarm::ExpiredListenAddr { listener_id, addr }); + .on_swarm_event(FromSwarm::ExpiredListenAddr(ExpiredListenAddr { + listener_id, + addr, + })); self.as_client().on_expired_address(addr); } - FromSwarm::ExpiredExternalAddr { addr } => { + FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }) => { self.inner - .on_swarm_event(FromSwarm::ExpiredExternalAddr { addr }); + .on_swarm_event(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr })); self.as_client().on_expired_address(addr); } - new_external_addr @ FromSwarm::NewExternalAddr { .. } => { - self.inner.on_swarm_event(new_external_addr); + external_addr @ FromSwarm::NewExternalAddr(_) => { + self.inner.on_swarm_event(external_addr); self.as_client().on_new_address(); } - listen_failure @ FromSwarm::ListenFailure { .. } => { + listen_failure @ FromSwarm::ListenFailure(_) => { self.inner.on_swarm_event(listen_failure) } - new_listener @ FromSwarm::NewListener { .. } => self.inner.on_swarm_event(new_listener), - listener_error @ FromSwarm::ListenerError { .. } => { + new_listener @ FromSwarm::NewListener(_) => self.inner.on_swarm_event(new_listener), + listener_error @ FromSwarm::ListenerError(_) => { self.inner.on_swarm_event(listener_error) } - listener_closed @ FromSwarm::ListenerClosed { .. } => { + listener_closed @ FromSwarm::ListenerClosed(_) => { self.inner.on_swarm_event(listener_closed) } } diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 1fc3b109268..cc0b7f6abac 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -892,6 +892,7 @@ pub enum FromSwarm<'a, Handler: IntoConnectionHandler> { } /// [`FromSwarm`] variant that informs the behaviour about a newly established connection to a peer. +#[derive(Clone, Copy)] pub struct ConnectionEstablished<'a> { pub peer_id: PeerId, pub connection_id: ConnectionId, From e28fac5724f2071ae7bd7def89963366a06172b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 14 Oct 2022 15:20:36 +0100 Subject: [PATCH 15/60] request-response/lib: replace inject_* methods with on_*, on NetworkBehaviour implementation --- protocols/request-response/src/lib.rs | 248 +++++++++++++++----------- 1 file changed, 148 insertions(+), 100 deletions(-) diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index c4e18d894fb..85c25c163c6 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -66,8 +66,10 @@ use futures::channel::oneshot; use handler::{RequestProtocol, RequestResponseHandler, RequestResponseHandlerEvent}; use libp2p_core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId}; use libp2p_swarm::{ - dial_opts::DialOpts, DialError, IntoConnectionHandler, NetworkBehaviour, - NetworkBehaviourAction, NotifyHandler, PollParameters, + behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}, + dial_opts::DialOpts, + IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + PollParameters, }; use smallvec::SmallVec; use std::{ @@ -558,115 +560,70 @@ where .get_mut(peer) .and_then(|connections| connections.iter_mut().find(|c| c.id == connection)) } -} - -impl NetworkBehaviour for RequestResponse -where - TCodec: RequestResponseCodec + Send + Clone + 'static, -{ - type ConnectionHandler = RequestResponseHandler; - type OutEvent = RequestResponseEvent; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - RequestResponseHandler::new( - self.inbound_protocols.clone(), - self.codec.clone(), - self.config.connection_keep_alive, - self.config.request_timeout, - self.next_inbound_id.clone(), - ) - } - - fn addresses_of_peer(&mut self, peer: &PeerId) -> Vec { - let mut addresses = Vec::new(); - if let Some(connections) = self.connected.get(peer) { - addresses.extend(connections.iter().filter_map(|c| c.address.clone())) - } - if let Some(more) = self.addresses.get(peer) { - addresses.extend(more.into_iter().cloned()); - } - addresses - } - fn inject_address_change( + /// Called on the [`FromSwarm::ConnectionEstablished`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_established( &mut self, - peer: &PeerId, - conn: &ConnectionId, - _old: &ConnectedPoint, - new: &ConnectedPoint, - ) { - let new_address = match new { - ConnectedPoint::Dialer { address, .. } => Some(address.clone()), - ConnectedPoint::Listener { .. } => None, - }; - let connections = self - .connected - .get_mut(peer) - .expect("Address change can only happen on an established connection."); - - let connection = connections - .iter_mut() - .find(|c| &c.id == conn) - .expect("Address change can only happen on an established connection."); - connection.address = new_address; - } - - fn inject_connection_established( - &mut self, - peer: &PeerId, - conn: &ConnectionId, - endpoint: &ConnectedPoint, - _errors: Option<&Vec>, - other_established: usize, + ConnectionEstablished { + peer_id, + connection_id, + endpoint, + other_established, + .. + }: ConnectionEstablished, ) { let address = match endpoint { ConnectedPoint::Dialer { address, .. } => Some(address.clone()), ConnectedPoint::Listener { .. } => None, }; self.connected - .entry(*peer) + .entry(peer_id) .or_default() - .push(Connection::new(*conn, address)); + .push(Connection::new(connection_id, address)); if other_established == 0 { - if let Some(pending) = self.pending_outbound_requests.remove(peer) { + if let Some(pending) = self.pending_outbound_requests.remove(&peer_id) { for request in pending { - let request = self.try_send_request(peer, request); + let request = self.try_send_request(&peer_id, request); assert!(request.is_none()); } } } } - fn inject_connection_closed( + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_closed( &mut self, - peer_id: &PeerId, - conn: &ConnectionId, - _: &ConnectedPoint, - _: ::Handler, - remaining_established: usize, + ConnectionClosed { + peer_id, + connection_id, + remaining_established, + .. + }: ConnectionClosed<::ConnectionHandler>, ) { let connections = self .connected - .get_mut(peer_id) + .get_mut(&peer_id) .expect("Expected some established connection to peer before closing."); let connection = connections .iter() - .position(|c| &c.id == conn) + .position(|c| c.id == connection_id) .map(|p: usize| connections.remove(p)) .expect("Expected connection to be established before closing."); debug_assert_eq!(connections.is_empty(), remaining_established == 0); if connections.is_empty() { - self.connected.remove(peer_id); + self.connected.remove(&peer_id); } for request_id in connection.pending_outbound_responses { self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer: *peer_id, + peer: peer_id, request_id, error: InboundFailure::ConnectionClosed, }, @@ -677,7 +634,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::OutboundFailure { - peer: *peer_id, + peer: peer_id, request_id, error: OutboundFailure::ConnectionClosed, }, @@ -685,13 +642,43 @@ where } } - fn inject_dial_failure( + /// Called on the [`FromSwarm::AddressChange`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_address_change( &mut self, - peer: Option, - _: Self::ConnectionHandler, - _: &DialError, + AddressChange { + peer_id, + connection_id, + new, + .. + }: AddressChange, ) { - if let Some(peer) = peer { + let new_address = match new { + ConnectedPoint::Dialer { address, .. } => Some(address.clone()), + ConnectedPoint::Listener { .. } => None, + }; + let connections = self + .connected + .get_mut(&peer_id) + .expect("Address change can only happen on an established connection."); + + let connection = connections + .iter_mut() + .find(|c| &c.id == &connection_id) + .expect("Address change can only happen on an established connection."); + connection.address = new_address; + } + + /// Called on the [`FromSwarm::DialFailure`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_dial_failure( + &mut self, + DialFailure { + peer_id, + .. + }: DialFailure<::ConnectionHandler>, + ) { + if let Some(peer) = peer_id { // If there are pending outgoing requests when a dial failure occurs, // it is implied that we are not connected to the peer, since pending // outgoing requests are drained when a connection is established and @@ -712,19 +699,67 @@ where } } } +} - fn inject_event( +impl NetworkBehaviour for RequestResponse +where + TCodec: RequestResponseCodec + Send + Clone + 'static, +{ + type ConnectionHandler = RequestResponseHandler; + type OutEvent = RequestResponseEvent; + + fn new_handler(&mut self) -> Self::ConnectionHandler { + RequestResponseHandler::new( + self.inbound_protocols.clone(), + self.codec.clone(), + self.config.connection_keep_alive, + self.config.request_timeout, + self.next_inbound_id.clone(), + ) + } + + fn addresses_of_peer(&mut self, peer: &PeerId) -> Vec { + let mut addresses = Vec::new(); + if let Some(connections) = self.connected.get(peer) { + addresses.extend(connections.iter().filter_map(|c| c.address.clone())) + } + if let Some(more) = self.addresses.get(peer) { + addresses.extend(more.into_iter().cloned()); + } + addresses + } + + fn on_swarm_event( &mut self, - peer: PeerId, - connection: ConnectionId, - event: RequestResponseHandlerEvent, + event: libp2p_swarm::behaviour::FromSwarm, + ) { + match event { + FromSwarm::ConnectionEstablished(connection_established) => { + self.on_connection_established(connection_established) + } + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), + FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), + _ => {}, + } + } + + fn on_connection_handler_event( + &mut self, + peer_id: PeerId, + connection_id: ConnectionId, + event: <::Handler as + libp2p_swarm::ConnectionHandler>::OutEvent, ) { match event { RequestResponseHandlerEvent::Response { request_id, response, } => { - let removed = self.remove_pending_inbound_response(&peer, connection, &request_id); + let removed = + self.remove_pending_inbound_response(&peer_id, connection_id, &request_id); debug_assert!( removed, "Expect request_id to be pending before receiving response.", @@ -736,7 +771,10 @@ where }; self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( - RequestResponseEvent::Message { peer, message }, + RequestResponseEvent::Message { + peer: peer_id, + message, + }, )); } RequestResponseHandlerEvent::Request { @@ -752,10 +790,13 @@ where }; self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( - RequestResponseEvent::Message { peer, message }, + RequestResponseEvent::Message { + peer: peer_id, + message, + }, )); - match self.get_connection_mut(&peer, connection) { + match self.get_connection_mut(&peer_id, connection_id) { Some(connection) => { let inserted = connection.pending_outbound_responses.insert(request_id); debug_assert!(inserted, "Expect id of new request to be unknown."); @@ -765,7 +806,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer, + peer: peer_id, request_id, error: InboundFailure::ConnectionClosed, }, @@ -774,7 +815,8 @@ where } } RequestResponseHandlerEvent::ResponseSent(request_id) => { - let removed = self.remove_pending_outbound_response(&peer, connection, request_id); + let removed = + self.remove_pending_outbound_response(&peer_id, connection_id, request_id); debug_assert!( removed, "Expect request_id to be pending before response is sent." @@ -782,11 +824,15 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( - RequestResponseEvent::ResponseSent { peer, request_id }, + RequestResponseEvent::ResponseSent { + peer: peer_id, + request_id, + }, )); } RequestResponseHandlerEvent::ResponseOmission(request_id) => { - let removed = self.remove_pending_outbound_response(&peer, connection, request_id); + let removed = + self.remove_pending_outbound_response(&peer_id, connection_id, request_id); debug_assert!( removed, "Expect request_id to be pending before response is omitted.", @@ -795,14 +841,15 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer, + peer: peer_id, request_id, error: InboundFailure::ResponseOmission, }, )); } RequestResponseHandlerEvent::OutboundTimeout(request_id) => { - let removed = self.remove_pending_inbound_response(&peer, connection, &request_id); + let removed = + self.remove_pending_inbound_response(&peer_id, connection_id, &request_id); debug_assert!( removed, "Expect request_id to be pending before request times out." @@ -811,7 +858,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::OutboundFailure { - peer, + peer: peer_id, request_id, error: OutboundFailure::Timeout, }, @@ -822,19 +869,20 @@ where // out to receive the request and for timing out sending the response. In the former // case the request is never added to `pending_outbound_responses` and thus one can // not assert the request_id to be present before removing it. - self.remove_pending_outbound_response(&peer, connection, request_id); + self.remove_pending_outbound_response(&peer_id, connection_id, request_id); self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer, + peer: peer_id, request_id, error: InboundFailure::Timeout, }, )); } RequestResponseHandlerEvent::OutboundUnsupportedProtocols(request_id) => { - let removed = self.remove_pending_inbound_response(&peer, connection, &request_id); + let removed = + self.remove_pending_inbound_response(&peer_id, connection_id, &request_id); debug_assert!( removed, "Expect request_id to be pending before failing to connect.", @@ -843,7 +891,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::OutboundFailure { - peer, + peer: peer_id, request_id, error: OutboundFailure::UnsupportedProtocols, }, @@ -856,7 +904,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer, + peer: peer_id, request_id, error: InboundFailure::UnsupportedProtocols, }, From db4bfad0822a07277a7b549878de4c203c184320 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 15 Oct 2022 11:33:34 +0100 Subject: [PATCH 16/60] autonat/behaviour: add missing on_connection_handler_event --- protocols/autonat/src/behaviour.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index 1c8398ef21b..db5b6f335d3 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -40,7 +40,7 @@ use libp2p_swarm::{ AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr, ExpiredListenAddr, FromSwarm, }, - NetworkBehaviour, NetworkBehaviourAction, PollParameters, + NetworkBehaviour, NetworkBehaviourAction, PollParameters, ConnectionHandler, IntoConnectionHandler, }; use std::{ collections::{HashMap, VecDeque}, @@ -546,6 +546,17 @@ impl NetworkBehaviour for Behaviour { } } } + + fn on_connection_handler_event( + &mut self, + peer_id: PeerId, + connection_id: ConnectionId, + event: <::Handler as + ConnectionHandler>::OutEvent, + ) { + self.inner + .on_connection_handler_event(peer_id, connection_id, event) + } } type Action = NetworkBehaviourAction< From aebd4a9c2e4bab4eab803485ae6b0f9a66d6f210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 15 Oct 2022 11:34:29 +0100 Subject: [PATCH 17/60] swarm/lib: revert back None -> peer_id on inject_dial_failure call --- swarm/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index adb2205d3fc..eaaad2a7ae8 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -542,7 +542,7 @@ where Err((connection_limit, handler)) => { let error = DialError::ConnectionLimit(connection_limit); #[allow(deprecated)] - self.behaviour.inject_dial_failure(None, handler, &error); + self.behaviour.inject_dial_failure(peer_id, handler, &error); Err(error) } } From fb63892dc61eddaf970d496a9d1900e1e6cd033d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 15 Oct 2022 12:42:16 +0100 Subject: [PATCH 18/60] dcutr/behaviour: replace inject_* methods with on_* --- protocols/dcutr/src/behaviour.rs | 145 ++++++++++++++++++------------- 1 file changed, 85 insertions(+), 60 deletions(-) diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 5d93d90b339..418a2f4208b 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -26,9 +26,10 @@ use either::Either; use libp2p_core::connection::{ConnectedPoint, ConnectionId}; use libp2p_core::multiaddr::Protocol; use libp2p_core::{Multiaddr, PeerId}; +use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}; use libp2p_swarm::dial_opts::{self, DialOpts}; use libp2p_swarm::{ - ConnectionHandler, ConnectionHandlerUpgrErr, DialError, IntoConnectionHandler, + ConnectionHandler, ConnectionHandlerUpgrErr, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use std::collections::{HashMap, HashSet, VecDeque}; @@ -81,30 +82,20 @@ impl Behaviour { direct_connections: Default::default(), } } -} - -impl NetworkBehaviour for Behaviour { - type ConnectionHandler = handler::Prototype; - type OutEvent = Event; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - handler::Prototype::UnknownConnection - } - fn addresses_of_peer(&mut self, _peer_id: &PeerId) -> Vec { - vec![] - } - - fn inject_connection_established( + /// Called on the [`FromSwarm::ConnectionEstablished`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_established( &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - connected_point: &ConnectedPoint, - _failed_addresses: Option<&Vec>, - _other_established: usize, + ConnectionEstablished { + peer_id, + connection_id, + endpoint, + .. + }: ConnectionEstablished, ) { - if connected_point.is_relayed() { - if connected_point.is_listener() && !self.direct_connections.contains_key(peer_id) { + if endpoint.is_relayed() { + if endpoint.is_listener() && !self.direct_connections.contains_key(&peer_id) { // TODO: Try dialing the remote peer directly. Specification: // // > The protocol starts with the completion of a relay connection from A to B. Upon @@ -116,14 +107,14 @@ impl NetworkBehaviour for Behaviour { // https://github.com/libp2p/specs/blob/master/relay/DCUtR.md#the-protocol self.queued_actions.extend([ ActionBuilder::Connect { - peer_id: *peer_id, + peer_id: peer_id, attempt: 1, - handler: NotifyHandler::One(*connection_id), + handler: NotifyHandler::One(connection_id), }, NetworkBehaviourAction::GenerateEvent( Event::InitiatedDirectConnectionUpgrade { - remote_peer_id: *peer_id, - local_relayed_addr: match connected_point { + remote_peer_id: peer_id, + local_relayed_addr: match endpoint { ConnectedPoint::Listener { local_addr, .. } => local_addr.clone(), ConnectedPoint::Dialer { .. } => unreachable!("Due to outer if."), }, @@ -134,17 +125,47 @@ impl NetworkBehaviour for Behaviour { } } else { self.direct_connections - .entry(*peer_id) + .entry(peer_id) .or_default() - .insert(*connection_id); + .insert(connection_id); } } - fn inject_dial_failure( + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_closed( &mut self, - peer_id: Option, - handler: Self::ConnectionHandler, - _error: &DialError, + ConnectionClosed { + peer_id, + connection_id, + endpoint, + .. + }: ConnectionClosed<::ConnectionHandler>, + ) { + if !endpoint.is_relayed() { + let connections = self + .direct_connections + .get_mut(&peer_id) + .expect("Peer of direct connection to be tracked."); + connections + .remove(&connection_id) + .then(|| ()) + .expect("Direct connection to be tracked."); + if connections.is_empty() { + self.direct_connections.remove(&peer_id); + } + } + } + + /// Called on the [`FromSwarm::DialFailure`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_dial_failure( + &mut self, + DialFailure { + peer_id, + handler, + .. + }: DialFailure<::ConnectionHandler>, ) { if let handler::Prototype::DirectConnection { relayed_connection_id, @@ -177,37 +198,28 @@ impl NetworkBehaviour for Behaviour { } } } +} - fn inject_connection_closed( - &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - connected_point: &ConnectedPoint, - _handler: <::ConnectionHandler as IntoConnectionHandler>::Handler, - _remaining_established: usize, - ) { - if !connected_point.is_relayed() { - let connections = self - .direct_connections - .get_mut(peer_id) - .expect("Peer of direct connection to be tracked."); - connections - .remove(connection_id) - .then(|| ()) - .expect("Direct connection to be tracked."); - if connections.is_empty() { - self.direct_connections.remove(peer_id); - } - } +impl NetworkBehaviour for Behaviour { + type ConnectionHandler = handler::Prototype; + type OutEvent = Event; + + fn new_handler(&mut self) -> Self::ConnectionHandler { + handler::Prototype::UnknownConnection } - fn inject_event( + fn addresses_of_peer(&mut self, _peer_id: &PeerId) -> Vec { + vec![] + } + + fn on_connection_handler_event( &mut self, event_source: PeerId, - connection: ConnectionId, - handler_event: <::Handler as ConnectionHandler>::OutEvent, + connection_id: ConnectionId, + event: <::Handler as + ConnectionHandler>::OutEvent, ) { - match handler_event { + match event { Either::Left(handler::relayed::Event::InboundConnectRequest { inbound_connect, remote_addr, @@ -215,7 +227,7 @@ impl NetworkBehaviour for Behaviour { self.queued_actions.extend([ ActionBuilder::AcceptInboundConnect { peer_id: event_source, - handler: NotifyHandler::One(connection), + handler: NotifyHandler::One(connection_id), inbound_connect, }, NetworkBehaviourAction::GenerateEvent( @@ -244,7 +256,7 @@ impl NetworkBehaviour for Behaviour { .condition(dial_opts::PeerCondition::Always) .build(), handler: handler::Prototype::DirectConnection { - relayed_connection_id: connection, + relayed_connection_id: connection_id, role: handler::Role::Listener, }, } @@ -272,7 +284,7 @@ impl NetworkBehaviour for Behaviour { .override_role() .build(), handler: handler::Prototype::DirectConnection { - relayed_connection_id: connection, + relayed_connection_id: connection_id, role: handler::Role::Initiator { attempt }, }, } @@ -316,6 +328,19 @@ impl NetworkBehaviour for Behaviour { Poll::Pending } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(connection_established) => { + self.on_connection_established(connection_established) + } + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), + _ => {} + } + } } /// A [`NetworkBehaviourAction`], either complete, or still requiring data from [`PollParameters`] From 790d84873168b2eecb9e3bc1a3d03499fa0a1d95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 15 Oct 2022 14:07:24 +0100 Subject: [PATCH 19/60] floodsub/layer: replace inject_* methods with on_* --- protocols/floodsub/src/layer.rs | 80 ++++++++++++++++++++------------- 1 file changed, 49 insertions(+), 31 deletions(-) diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index 4256e39b7dc..f9a2214de8d 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -27,11 +27,12 @@ use crate::FloodsubConfig; use cuckoofilter::{CuckooError, CuckooFilter}; use fnv::FnvHashSet; use libp2p_core::{connection::ConnectionId, PeerId}; -use libp2p_core::{ConnectedPoint, Multiaddr}; +use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, FromSwarm}; use libp2p_swarm::{ dial_opts::DialOpts, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, OneShotHandler, PollParameters, }; +use libp2p_swarm::{ConnectionHandler, IntoConnectionHandler}; use log::warn; use smallvec::SmallVec; use std::collections::hash_map::{DefaultHasher, HashMap}; @@ -276,23 +277,16 @@ impl Floodsub { }); } } -} -impl NetworkBehaviour for Floodsub { - type ConnectionHandler = OneShotHandler; - type OutEvent = FloodsubEvent; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - Default::default() - } - - fn inject_connection_established( + /// Called on the [`FromSwarm::ConnectionEstablished`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_established( &mut self, - id: &PeerId, - _: &ConnectionId, - _: &ConnectedPoint, - _: Option<&Vec>, - other_established: usize, + ConnectionEstablished { + peer_id, + other_established, + .. + }: ConnectionEstablished, ) { if other_established > 0 { // We only care about the first time a peer connects. @@ -300,11 +294,11 @@ impl NetworkBehaviour for Floodsub { } // We need to send our subscriptions to the newly-connected node. - if self.target_peers.contains(id) { + if self.target_peers.contains(&peer_id) { for topic in self.subscribed_topics.iter().cloned() { self.events .push_back(NetworkBehaviourAction::NotifyHandler { - peer_id: *id, + peer_id, handler: NotifyHandler::Any, event: FloodsubRpc { messages: Vec::new(), @@ -317,41 +311,53 @@ impl NetworkBehaviour for Floodsub { } } - self.connected_peers.insert(*id, SmallVec::new()); + self.connected_peers.insert(peer_id, SmallVec::new()); } - fn inject_connection_closed( + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_closed( &mut self, - id: &PeerId, - _: &ConnectionId, - _: &ConnectedPoint, - _: Self::ConnectionHandler, - remaining_established: usize, + ConnectionClosed { + peer_id, + remaining_established, + .. + }: ConnectionClosed<::ConnectionHandler>, ) { if remaining_established > 0 { // we only care about peer disconnections return; } - let was_in = self.connected_peers.remove(id); + let was_in = self.connected_peers.remove(&peer_id); debug_assert!(was_in.is_some()); // We can be disconnected by the remote in case of inactivity for example, so we always // try to reconnect. - if self.target_peers.contains(id) { + if self.target_peers.contains(&peer_id) { let handler = self.new_handler(); self.events.push_back(NetworkBehaviourAction::Dial { - opts: DialOpts::peer_id(*id).build(), + opts: DialOpts::peer_id(peer_id).build(), handler, }); } } +} - fn inject_event( +impl NetworkBehaviour for Floodsub { + type ConnectionHandler = OneShotHandler; + type OutEvent = FloodsubEvent; + + fn new_handler(&mut self) -> Self::ConnectionHandler { + Default::default() + } + + fn on_connection_handler_event( &mut self, propagation_source: PeerId, - _connection: ConnectionId, - event: InnerMessage, + _connection_id: ConnectionId, + event: <::Handler as + ConnectionHandler>::OutEvent, ) { // We ignore successful sends or timeouts. let event = match event { @@ -477,6 +483,18 @@ impl NetworkBehaviour for Floodsub { Poll::Pending } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(connection_established) => { + self.on_connection_established(connection_established) + } + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + _ => {} + } + } } /// Transmission between the `OneShotHandler` and the `FloodsubHandler`. From d24c92cc820c3200ef0c2fd383060c66b3f9a0a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 15 Oct 2022 14:40:21 +0100 Subject: [PATCH 20/60] gossipsub/behaviour: replace inject_* methods with on_* --- protocols/gossipsub/src/behaviour.rs | 198 ++++++++++++--------- protocols/gossipsub/src/behaviour/tests.rs | 125 ++++++------- 2 files changed, 176 insertions(+), 147 deletions(-) diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index 43f2f79466d..4ed55bb890f 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -38,10 +38,12 @@ use rand::{seq::SliceRandom, thread_rng}; use libp2p_core::{ connection::ConnectionId, identity::Keypair, multiaddr::Protocol::Ip4, - multiaddr::Protocol::Ip6, ConnectedPoint, Multiaddr, PeerId, + multiaddr::Protocol::Ip6, Multiaddr, PeerId, }; use libp2p_swarm::{ - dial_opts::DialOpts, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, + behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, FromSwarm}, + dial_opts::DialOpts, + ConnectionHandler, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use wasm_timer::Instant; @@ -3028,57 +3030,32 @@ where Ok(rpc_list) } -} - -fn get_ip_addr(addr: &Multiaddr) -> Option { - addr.iter().find_map(|p| match p { - Ip4(addr) => Some(IpAddr::V4(addr)), - Ip6(addr) => Some(IpAddr::V6(addr)), - _ => None, - }) -} -impl NetworkBehaviour for Gossipsub -where - C: Send + 'static + DataTransform, - F: Send + 'static + TopicSubscriptionFilter, -{ - type ConnectionHandler = GossipsubHandler; - type OutEvent = GossipsubEvent; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - let protocol_config = ProtocolConfig::new( - self.config.protocol_id().clone(), - self.config.custom_id_version().clone(), - self.config.max_transmit_size(), - self.config.validation_mode().clone(), - self.config.support_floodsub(), - ); - - GossipsubHandler::new(protocol_config, self.config.idle_timeout()) - } - - fn inject_connection_established( + /// Called on the [`FromSwarm::ConnectionEstablished`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_established( &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - endpoint: &ConnectedPoint, - _: Option<&Vec>, - other_established: usize, + ConnectionEstablished { + peer_id, + connection_id, + endpoint, + other_established, + .. + }: ConnectionEstablished, ) { // Diverging from the go implementation we only want to consider a peer as outbound peer // if its first connection is outbound. - if endpoint.is_dialer() && other_established == 0 && !self.px_peers.contains(peer_id) { + if endpoint.is_dialer() && other_established == 0 && !self.px_peers.contains(&peer_id) { // The first connection is outbound and it is not a peer from peer exchange => mark // it as outbound peer - self.outbound_peers.insert(*peer_id); + self.outbound_peers.insert(peer_id); } // Add the IP to the peer scoring system if let Some((peer_score, ..)) = &mut self.peer_score { if let Some(ip) = get_ip_addr(endpoint.get_remote_address()) { - peer_score.add_ip(peer_id, ip); + peer_score.add_ip(&peer_id, ip); } else { trace!( "Couldn't extract ip from endpoint of peer {} with endpoint {:?}", @@ -3094,17 +3071,17 @@ where // update the type of peer that this is in order to determine which kind of routing should // occur. self.connected_peers - .entry(*peer_id) + .entry(peer_id) .or_insert(PeerConnections { kind: PeerKind::Floodsub, connections: vec![], }) .connections - .push(*connection_id); + .push(connection_id); if other_established == 0 { // Ignore connections from blacklisted peers. - if self.blacklisted_peers.contains(peer_id) { + if self.blacklisted_peers.contains(&peer_id) { debug!("Ignoring connection from blacklisted peer: {}", peer_id); } else { debug!("New peer connected: {}", peer_id); @@ -3121,7 +3098,7 @@ where // send our subscriptions to the peer if self .send_message( - *peer_id, + peer_id, GossipsubRpc { messages: Vec::new(), subscriptions, @@ -3137,26 +3114,30 @@ where } // Insert an empty set of the topics of this peer until known. - self.peer_topics.insert(*peer_id, Default::default()); + self.peer_topics.insert(peer_id, Default::default()); if let Some((peer_score, ..)) = &mut self.peer_score { - peer_score.add_peer(*peer_id); + peer_score.add_peer(peer_id); } } } - fn inject_connection_closed( + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_closed( &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - endpoint: &ConnectedPoint, - _: ::Handler, - remaining_established: usize, + ConnectionClosed { + peer_id, + connection_id, + endpoint, + remaining_established, + .. + }: ConnectionClosed<::ConnectionHandler>, ) { // Remove IP from peer scoring system if let Some((peer_score, ..)) = &mut self.peer_score { if let Some(ip) = get_ip_addr(endpoint.get_remote_address()) { - peer_score.remove_ip(peer_id, &ip); + peer_score.remove_ip(&peer_id, &ip); } else { trace!( "Couldn't extract ip from endpoint of peer {} with endpoint {:?}", @@ -3168,24 +3149,24 @@ where if remaining_established != 0 { // Remove the connection from the list - if let Some(connections) = self.connected_peers.get_mut(peer_id) { + if let Some(connections) = self.connected_peers.get_mut(&peer_id) { let index = connections .connections .iter() - .position(|v| v == connection_id) + .position(|v| v == &connection_id) .expect("Previously established connection to peer must be present"); connections.connections.remove(index); // If there are more connections and this peer is in a mesh, inform the first connection // handler. if !connections.connections.is_empty() { - if let Some(topics) = self.peer_topics.get(peer_id) { + if let Some(topics) = self.peer_topics.get(&peer_id) { for topic in topics { if let Some(mesh_peers) = self.mesh.get(topic) { - if mesh_peers.contains(peer_id) { + if mesh_peers.contains(&peer_id) { self.events .push_back(NetworkBehaviourAction::NotifyHandler { - peer_id: *peer_id, + peer_id, event: Arc::new(GossipsubHandlerIn::JoinedMesh), handler: NotifyHandler::One(connections.connections[0]), }); @@ -3200,11 +3181,11 @@ where // remove from mesh, topic_peers, peer_topic and the fanout debug!("Peer disconnected: {}", peer_id); { - let topics = match self.peer_topics.get(peer_id) { + let topics = match self.peer_topics.get(&peer_id) { Some(topics) => topics, None => { debug_assert!( - self.blacklisted_peers.contains(peer_id), + self.blacklisted_peers.contains(&peer_id), "Disconnected node not in connected list" ); return; @@ -3216,7 +3197,7 @@ where // check the mesh for the topic if let Some(mesh_peers) = self.mesh.get_mut(topic) { // check if the peer is in the mesh and remove it - if mesh_peers.remove(peer_id) { + if mesh_peers.remove(&peer_id) { if let Some(m) = self.metrics.as_mut() { m.peers_removed(topic, Churn::Dc, 1); m.set_mesh_peers(topic, mesh_peers.len()); @@ -3226,7 +3207,7 @@ where // remove from topic_peers if let Some(peer_list) = self.topic_peers.get_mut(topic) { - if !peer_list.remove(peer_id) { + if !peer_list.remove(&peer_id) { // debugging purposes warn!( "Disconnected node: {} not in topic_peers peer list", @@ -3246,72 +3227,103 @@ where // remove from fanout self.fanout .get_mut(topic) - .map(|peers| peers.remove(peer_id)); + .map(|peers| peers.remove(&peer_id)); } } // Forget px and outbound status for this peer - self.px_peers.remove(peer_id); - self.outbound_peers.remove(peer_id); + self.px_peers.remove(&peer_id); + self.outbound_peers.remove(&peer_id); // Remove peer from peer_topics and connected_peers // NOTE: It is possible the peer has already been removed from all mappings if it does not // support the protocol. - self.peer_topics.remove(peer_id); + self.peer_topics.remove(&peer_id); // If metrics are enabled, register the disconnection of a peer based on its protocol. if let Some(metrics) = self.metrics.as_mut() { let peer_kind = &self .connected_peers - .get(peer_id) + .get(&peer_id) .expect("Connected peer must be registered") .kind; metrics.peer_protocol_disconnected(peer_kind.clone()); } - self.connected_peers.remove(peer_id); + self.connected_peers.remove(&peer_id); if let Some((peer_score, ..)) = &mut self.peer_score { - peer_score.remove_peer(peer_id); + peer_score.remove_peer(&peer_id); } } } - fn inject_address_change( + /// Called on the [`FromSwarm::AddressChange`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_address_change( &mut self, - peer: &PeerId, - _: &ConnectionId, - endpoint_old: &ConnectedPoint, - endpoint_new: &ConnectedPoint, + AddressChange { + peer_id, old, new, .. + }: AddressChange, ) { // Exchange IP in peer scoring system if let Some((peer_score, ..)) = &mut self.peer_score { - if let Some(ip) = get_ip_addr(endpoint_old.get_remote_address()) { - peer_score.remove_ip(peer, &ip); + if let Some(ip) = get_ip_addr(old.get_remote_address()) { + peer_score.remove_ip(&peer_id, &ip); } else { trace!( "Couldn't extract ip from endpoint of peer {} with endpoint {:?}", - peer, - endpoint_old + &peer_id, + old ) } - if let Some(ip) = get_ip_addr(endpoint_new.get_remote_address()) { - peer_score.add_ip(peer, ip); + if let Some(ip) = get_ip_addr(new.get_remote_address()) { + peer_score.add_ip(&peer_id, ip); } else { trace!( "Couldn't extract ip from endpoint of peer {} with endpoint {:?}", - peer, - endpoint_new + peer_id, + new ) } } } +} + +fn get_ip_addr(addr: &Multiaddr) -> Option { + addr.iter().find_map(|p| match p { + Ip4(addr) => Some(IpAddr::V4(addr)), + Ip6(addr) => Some(IpAddr::V6(addr)), + _ => None, + }) +} + +impl NetworkBehaviour for Gossipsub +where + C: Send + 'static + DataTransform, + F: Send + 'static + TopicSubscriptionFilter, +{ + type ConnectionHandler = GossipsubHandler; + type OutEvent = GossipsubEvent; - fn inject_event( + fn new_handler(&mut self) -> Self::ConnectionHandler { + let protocol_config = ProtocolConfig::new( + self.config.protocol_id().clone(), + self.config.custom_id_version().clone(), + self.config.max_transmit_size(), + self.config.validation_mode().clone(), + self.config.support_floodsub(), + ); + + GossipsubHandler::new(protocol_config, self.config.idle_timeout()) + } + + fn on_connection_handler_event( &mut self, propagation_source: PeerId, - _: ConnectionId, - handler_event: HandlerEvent, + _connection_id: ConnectionId, + handler_event: <::Handler as + ConnectionHandler>::OutEvent, ) { match handler_event { HandlerEvent::PeerKind(kind) => { @@ -3333,7 +3345,8 @@ where )); } else if let Some(conn) = self.connected_peers.get_mut(&propagation_source) { // Only change the value if the old value is Floodsub (the default set in - // inject_connection_established). All other PeerKind changes are ignored. + // `NetworkBehaviour::on_event` with FromSwarm::ConnectionEstablished). + // All other PeerKind changes are ignored. debug!( "New peer type found: {} for peer: {}", kind, propagation_source @@ -3458,6 +3471,19 @@ where Poll::Pending } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(connection_established) => { + self.on_connection_established(connection_established) + } + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), + _ => {} + } + } } /// This is called when peers are added to any mesh. It checks if the peer existed diff --git a/protocols/gossipsub/src/behaviour/tests.rs b/protocols/gossipsub/src/behaviour/tests.rs index 71f4aae9b50..a1e8acca8da 100644 --- a/protocols/gossipsub/src/behaviour/tests.rs +++ b/protocols/gossipsub/src/behaviour/tests.rs @@ -31,7 +31,7 @@ use crate::{ }; use async_std::net::Ipv4Addr; use byteorder::{BigEndian, ByteOrder}; -use libp2p_core::Endpoint; +use libp2p_core::{ConnectedPoint, Endpoint}; use rand::Rng; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -181,25 +181,27 @@ where F: TopicSubscriptionFilter + Clone + Default + Send + 'static, { let peer = PeerId::random(); - gs.inject_connection_established( - &peer, - &ConnectionId::new(0), - &if outbound { - ConnectedPoint::Dialer { - address, - role_override: Endpoint::Dialer, - } - } else { - ConnectedPoint::Listener { - local_addr: Multiaddr::empty(), - send_back_addr: address, - } - }, - None, - 0, // first connection - ); + let endpoint = if outbound { + ConnectedPoint::Dialer { + address, + role_override: Endpoint::Dialer, + } + } else { + ConnectedPoint::Listener { + local_addr: Multiaddr::empty(), + send_back_addr: address, + } + }; + + gs.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id: peer, + connection_id: ConnectionId::new(0), + endpoint: &endpoint, + failed_addresses: &[], + other_established: 0, // first connection + })); if let Some(kind) = kind { - gs.inject_event(peer, ConnectionId::new(1), HandlerEvent::PeerKind(kind)); + gs.on_connection_handler_event(peer, ConnectionId::new(1), HandlerEvent::PeerKind(kind)); } if explicit { gs.add_explicit_peer(&peer); @@ -232,16 +234,16 @@ where }; // this is not relevant // peer_connections.connections should never be empty. let mut active_connections = peer_connections.connections.len(); - for conn_id in peer_connections.connections.clone() { + for connection_id in peer_connections.connections.clone() { let handler = gs.new_handler(); active_connections = active_connections.checked_sub(1).unwrap(); - gs.inject_connection_closed( - peer_id, - &conn_id, - &fake_endpoint, + gs.on_swarm_event(FromSwarm::ConnectionClosed(ConnectionClosed { + peer_id: *peer_id, + connection_id, + endpoint: &fake_endpoint, handler, - active_connections, - ); + remaining_established: active_connections, + })); } } } @@ -545,16 +547,16 @@ fn test_join() { for _ in 0..3 { let random_peer = PeerId::random(); // inform the behaviour of a new peer - gs.inject_connection_established( - &random_peer, - &ConnectionId::new(1), - &ConnectedPoint::Dialer { + gs.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id: random_peer, + connection_id: ConnectionId::new(1), + endpoint: &ConnectedPoint::Dialer { address: "/ip4/127.0.0.1".parse::().unwrap(), role_override: Endpoint::Dialer, }, - None, - 0, - ); + failed_addresses: &[], + other_established: 0, + })); // add the new peer to the fanout let fanout_peers = gs.fanout.get_mut(&topic_hashes[1]).unwrap(); @@ -2351,9 +2353,10 @@ fn test_add_outbound_peers_if_min_is_not_satisfied() { //TODO add a test that ensures that new outbound connections are recognized as such. // This is at the moment done in behaviour with relying on the fact that the call to -// `inject_connection_established` for the first connection is done before `inject_connected` -// gets called. For all further connections `inject_connection_established` should get called -// after `inject_connected`. +// `NetworkBehaviour::on_swarm_event` with `FromSwarm::ConnectionEstablished` +// for the first connection is done before `inject_connected` +// gets called. For all further connections `NetworkBehaviour::on_swarm_event` +// should get called wit `FromSwarm::ConnectionEstablished` after `inject_connected`. #[test] fn test_prune_negative_scored_peers() { @@ -2983,7 +2986,7 @@ fn test_ignore_rpc_from_peers_below_graylist_threshold() { gs.events.clear(); //receive from p1 - gs.inject_event( + gs.on_connection_handler_event( p1, ConnectionId::new(0), HandlerEvent::Message { @@ -3009,7 +3012,7 @@ fn test_ignore_rpc_from_peers_below_graylist_threshold() { }; //receive from p2 - gs.inject_event( + gs.on_connection_handler_event( p2, ConnectionId::new(0), HandlerEvent::Message { @@ -3621,7 +3624,7 @@ fn test_scoring_p4_invalid_signature() { //peer 0 delivers message with invalid signature let m = random_message(&mut seq, &topics); - gs.inject_event( + gs.on_connection_handler_event( peers[0], ConnectionId::new(0), HandlerEvent::Message { @@ -4105,16 +4108,16 @@ fn test_scoring_p6() { //add additional connection for 3 others with addr for id in others.iter().take(3) { - gs.inject_connection_established( - id, - &ConnectionId::new(0), - &ConnectedPoint::Dialer { + gs.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id: *id, + connection_id: ConnectionId::new(0), + endpoint: &ConnectedPoint::Dialer { address: addr.clone(), role_override: Endpoint::Dialer, }, - None, - 0, - ); + failed_addresses: &[], + other_established: 0, + })); } //penalties apply squared @@ -4126,16 +4129,16 @@ fn test_scoring_p6() { //add additional connection for 3 of the peers to addr2 for peer in peers.iter().take(3) { - gs.inject_connection_established( - peer, - &ConnectionId::new(0), - &ConnectedPoint::Dialer { + gs.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id: *peer, + connection_id: ConnectionId::new(0), + endpoint: &ConnectedPoint::Dialer { address: addr2.clone(), role_override: Endpoint::Dialer, }, - None, - 1, - ); + failed_addresses: &[], + other_established: 1, + })); } //double penalties for the first three of each @@ -4156,16 +4159,16 @@ fn test_scoring_p6() { ); //two times same ip doesn't count twice - gs.inject_connection_established( - &peers[0], - &ConnectionId::new(0), - &ConnectedPoint::Dialer { + gs.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id: peers[0], + connection_id: ConnectionId::new(0), + endpoint: &ConnectedPoint::Dialer { address: addr, role_override: Endpoint::Dialer, }, - None, - 2, - ); + failed_addresses: &[], + other_established: 2, + })); //nothing changed //double penalties for the first three of each @@ -5203,7 +5206,7 @@ fn test_subscribe_and_graft_with_negative_score() { _ => None, }); for message in messages_to_p1 { - gs1.inject_event( + gs1.on_connection_handler_event( p2, connection_id, HandlerEvent::Message { From e88c75d22bcb86bb43d7e36ef81c7213b4cd71fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 15 Oct 2022 15:26:43 +0100 Subject: [PATCH 21/60] identify/behaviour: replace inject_* methods with on_* --- protocols/identify/src/behaviour.rs | 147 ++++++++++++++-------------- 1 file changed, 75 insertions(+), 72 deletions(-) diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index eb81c64ccba..8d922c4f3e2 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -22,9 +22,12 @@ use crate::handler::{self, Proto, Push}; use crate::protocol::{Info, ReplySubstream, UpgradeError}; use futures::prelude::*; use libp2p_core::{ - connection::ConnectionId, multiaddr::Protocol, transport::ListenerId, ConnectedPoint, + connection::ConnectionId, multiaddr::Protocol, ConnectedPoint, Multiaddr, PeerId, PublicKey, }; +use libp2p_swarm::behaviour::{ + ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm, +}; use libp2p_swarm::{ dial_opts::DialOpts, AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError, IntoConnectionHandler, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, @@ -206,23 +209,18 @@ impl Behaviour { } } } -} - -impl NetworkBehaviour for Behaviour { - type ConnectionHandler = Proto; - type OutEvent = Event; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - Proto::new(self.config.initial_delay, self.config.interval) - } - fn inject_connection_established( + /// Called on the [`FromSwarm::ConnectionEstablished`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_established( &mut self, - peer_id: &PeerId, - conn: &ConnectionId, - endpoint: &ConnectedPoint, - failed_addresses: Option<&Vec>, - _other_established: usize, + ConnectionEstablished { + peer_id, + connection_id, + endpoint, + failed_addresses, + .. + }: ConnectionEstablished, ) { let addr = match endpoint { ConnectedPoint::Dialer { address, .. } => address.clone(), @@ -230,70 +228,27 @@ impl NetworkBehaviour for Behaviour { }; self.connected - .entry(*peer_id) + .entry(peer_id) .or_default() - .insert(*conn, addr); + .insert(connection_id, addr); - if let Some(entry) = self.discovered_peers.get_mut(peer_id) { - for addr in failed_addresses - .into_iter() - .flat_map(|addresses| addresses.iter()) - { + if let Some(entry) = self.discovered_peers.get_mut(&peer_id) { + for addr in failed_addresses { entry.remove(addr); } } } +} - fn inject_connection_closed( - &mut self, - peer_id: &PeerId, - conn: &ConnectionId, - _: &ConnectedPoint, - _: ::Handler, - remaining_established: usize, - ) { - if remaining_established == 0 { - self.connected.remove(peer_id); - self.pending_push.remove(peer_id); - } else if let Some(addrs) = self.connected.get_mut(peer_id) { - addrs.remove(conn); - } - } - - fn inject_dial_failure( - &mut self, - peer_id: Option, - _: Self::ConnectionHandler, - error: &DialError, - ) { - if let Some(peer_id) = peer_id { - if !self.connected.contains_key(&peer_id) { - self.pending_push.remove(&peer_id); - } - } - - if let Some(entry) = peer_id.and_then(|id| self.discovered_peers.get_mut(&id)) { - if let DialError::Transport(errors) = error { - for (addr, _error) in errors { - entry.remove(addr); - } - } - } - } - - fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) { - if self.config.push_listen_addr_updates { - self.pending_push.extend(self.connected.keys()); - } - } +impl NetworkBehaviour for Behaviour { + type ConnectionHandler = Proto; + type OutEvent = Event; - fn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) { - if self.config.push_listen_addr_updates { - self.pending_push.extend(self.connected.keys()); - } + fn new_handler(&mut self) -> Self::ConnectionHandler { + Proto::new(self.config.initial_delay, self.config.interval) } - fn inject_event( + fn on_connection_handler_event( &mut self, peer_id: PeerId, connection: ConnectionId, @@ -333,8 +288,9 @@ impl NetworkBehaviour for Behaviour { .get(&peer_id) .and_then(|addrs| addrs.get(&connection)) .expect( - "`inject_event` is only called with an established connection \ - and `inject_connection_established` ensures there is an entry; qed", + "`on_connection_handler_event` is only called \ + with an established connection and calling `NetworkBehaviour::on_event` \ + with `FromSwarm::ConnectionEstablished ensures there is an entry; qed", ); self.pending_replies.push_back(Reply::Queued { peer: peer_id, @@ -452,6 +408,53 @@ impl NetworkBehaviour for Behaviour { fn addresses_of_peer(&mut self, peer: &PeerId) -> Vec { self.discovered_peers.get(peer) } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(connection_established) => { + self.on_connection_established(connection_established) + } + FromSwarm::ConnectionClosed(ConnectionClosed { + peer_id, + connection_id, + remaining_established, + .. + }) => { + if remaining_established == 0 { + self.connected.remove(&peer_id); + self.pending_push.remove(&peer_id); + } else if let Some(addrs) = self.connected.get_mut(&peer_id) { + addrs.remove(&connection_id); + } + } + FromSwarm::DialFailure(DialFailure { peer_id, error, .. }) => { + if let Some(peer_id) = peer_id { + if !self.connected.contains_key(&peer_id) { + self.pending_push.remove(&peer_id); + } + } + + if let Some(entry) = peer_id.and_then(|id| self.discovered_peers.get_mut(&id)) { + if let DialError::Transport(errors) = error { + for (addr, _error) in errors { + entry.remove(addr); + } + } + } + } + FromSwarm::NewListenAddr(_) => { + if self.config.push_listen_addr_updates { + self.pending_push.extend(self.connected.keys()); + } + } + FromSwarm::ExpiredListenAddr(_) => { + if self.config.push_listen_addr_updates { + self.pending_push.extend(self.connected.keys()); + } + } + _ => {} + } + } } /// Event emitted by the `Identify` behaviour. From 0ccb5771e64e171874ab27a38787a0ecc4df2c55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 15 Oct 2022 15:53:42 +0100 Subject: [PATCH 22/60] kad/behaviour: replace inject_* methods with on_* --- protocols/kad/src/behaviour.rs | 301 +++++++++++++++------------- protocols/kad/src/behaviour/test.rs | 24 ++- 2 files changed, 176 insertions(+), 149 deletions(-) diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index b267f87d386..53266414c5e 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -39,8 +39,10 @@ use crate::record::{ use crate::K_VALUE; use fnv::{FnvHashMap, FnvHashSet}; use instant::Instant; -use libp2p_core::{ - connection::ConnectionId, transport::ListenerId, ConnectedPoint, Multiaddr, PeerId, +use libp2p_core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId}; +use libp2p_swarm::behaviour::{ + AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredListenAddr, + FromSwarm, NewExternalAddr, NewListenAddr, }; use libp2p_swarm::{ dial_opts::{self, DialOpts}, @@ -1771,62 +1773,20 @@ where } } } -} - -/// Exponentially decrease the given duration (base 2). -fn exp_decrease(ttl: Duration, exp: u32) -> Duration { - Duration::from_secs(ttl.as_secs().checked_shr(exp).unwrap_or(0)) -} - -impl NetworkBehaviour for Kademlia -where - for<'a> TStore: RecordStore<'a>, - TStore: Send + 'static, -{ - type ConnectionHandler = KademliaHandlerProto; - type OutEvent = KademliaEvent; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - KademliaHandlerProto::new(KademliaHandlerConfig { - protocol_config: self.protocol_config.clone(), - allow_listening: true, - idle_timeout: self.connection_idle_timeout, - }) - } - - fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec { - // We should order addresses from decreasing likelyhood of connectivity, so start with - // the addresses of that peer in the k-buckets. - let key = kbucket::Key::from(*peer_id); - let mut peer_addrs = - if let kbucket::Entry::Present(mut entry, _) = self.kbuckets.entry(&key) { - let addrs = entry.value().iter().cloned().collect::>(); - debug_assert!(!addrs.is_empty(), "Empty peer addresses in routing table."); - addrs - } else { - Vec::new() - }; - - // We add to that a temporary list of addresses from the ongoing queries. - for query in self.queries.iter() { - if let Some(addrs) = query.inner.addresses.get(peer_id) { - peer_addrs.extend(addrs.iter().cloned()) - } - } - peer_addrs - } - - fn inject_connection_established( + /// Called on the [`FromSwarm::ConnectionEstablished`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_established( &mut self, - peer_id: &PeerId, - _: &ConnectionId, - _: &ConnectedPoint, - errors: Option<&Vec>, - other_established: usize, + ConnectionEstablished { + peer_id, + failed_addresses, + other_established, + .. + }: ConnectionEstablished, ) { - for addr in errors.map(|a| a.iter()).into_iter().flatten() { - self.address_failed(*peer_id, addr); + for addr in failed_addresses { + self.address_failed(peer_id, addr); } // When a connection is established, we don't know yet whether the @@ -1842,7 +1802,7 @@ where q.inner .pending_rpcs .iter() - .position(|(p, _)| p == peer_id) + .position(|(p, _)| p == &peer_id) .map(|p| q.inner.pending_rpcs.remove(p)) }) { self.queued_events @@ -1853,38 +1813,104 @@ where }); } - self.connected_peers.insert(*peer_id); + self.connected_peers.insert(peer_id); } } - fn inject_address_change( + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_closed( &mut self, - peer: &PeerId, - _: &ConnectionId, - old: &ConnectedPoint, - new: &ConnectedPoint, + ConnectionClosed { + peer_id, + remaining_established, + .. + }: ConnectionClosed<::ConnectionHandler>, + ) { + if remaining_established == 0 { + for query in self.queries.iter_mut() { + query.on_failure(&peer_id); + } + self.connection_updated(peer_id, None, NodeStatus::Disconnected); + self.connected_peers.remove(&peer_id); + } + } + + /// Called on the [`FromSwarm::DialFailure`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_dial_failure( + &mut self, + DialFailure { peer_id, error, .. }: DialFailure< + ::ConnectionHandler, + >, + ) { + let peer_id = match peer_id { + Some(id) => id, + // Not interested in dial failures to unknown peers. + None => return, + }; + + match error { + DialError::Banned + | DialError::ConnectionLimit(_) + | DialError::LocalPeerId + | DialError::InvalidPeerId { .. } + | DialError::WrongPeerId { .. } + | DialError::Aborted + | DialError::ConnectionIo(_) + | DialError::Transport(_) + | DialError::NoAddresses => { + if let DialError::Transport(addresses) = error { + for (addr, _) in addresses { + self.address_failed(peer_id, addr) + } + } + + for query in self.queries.iter_mut() { + query.on_failure(&peer_id); + } + } + DialError::DialPeerConditionFalse( + dial_opts::PeerCondition::Disconnected | dial_opts::PeerCondition::NotDialing, + ) => { + // We might (still) be connected, or about to be connected, thus do not report the + // failure to the queries. + } + DialError::DialPeerConditionFalse(dial_opts::PeerCondition::Always) => { + unreachable!("DialPeerCondition::Always can not trigger DialPeerConditionFalse."); + } + } + } + + /// Called on the [`FromSwarm::AddressChange`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_address_change( + &mut self, + AddressChange { + peer_id, old, new, .. + }: AddressChange, ) { let (old, new) = (old.get_remote_address(), new.get_remote_address()); // Update routing table. - if let Some(addrs) = self.kbuckets.entry(&kbucket::Key::from(*peer)).value() { + if let Some(addrs) = self.kbuckets.entry(&kbucket::Key::from(peer_id)).value() { if addrs.replace(old, new) { debug!( "Address '{}' replaced with '{}' for peer '{}'.", - old, new, peer + old, new, peer_id ); } else { debug!( "Address '{}' not replaced with '{}' for peer '{}' as old address wasn't \ present.", - old, new, peer, + old, new, peer_id, ); } } else { debug!( "Address '{}' not replaced with '{}' for peer '{}' as peer is not present in the \ routing table.", - old, new, peer, + old, new, peer_id, ); } @@ -1903,7 +1929,7 @@ where // large performance impact. If so, the code below might be worth // revisiting. for query in self.queries.iter_mut() { - if let Some(addrs) = query.inner.addresses.get_mut(peer) { + if let Some(addrs) = query.inner.addresses.get_mut(&peer_id) { for addr in addrs.iter_mut() { if addr == old { *addr = new.clone(); @@ -1912,72 +1938,56 @@ where } } } +} - fn inject_dial_failure( - &mut self, - peer_id: Option, - _: Self::ConnectionHandler, - error: &DialError, - ) { - let peer_id = match peer_id { - Some(id) => id, - // Not interested in dial failures to unknown peers. - None => return, - }; +/// Exponentially decrease the given duration (base 2). +fn exp_decrease(ttl: Duration, exp: u32) -> Duration { + Duration::from_secs(ttl.as_secs().checked_shr(exp).unwrap_or(0)) +} - match error { - DialError::Banned - | DialError::ConnectionLimit(_) - | DialError::LocalPeerId - | DialError::InvalidPeerId { .. } - | DialError::WrongPeerId { .. } - | DialError::Aborted - | DialError::ConnectionIo(_) - | DialError::Transport(_) - | DialError::NoAddresses => { - if let DialError::Transport(addresses) = error { - for (addr, _) in addresses { - self.address_failed(peer_id, addr) - } - } +impl NetworkBehaviour for Kademlia +where + for<'a> TStore: RecordStore<'a>, + TStore: Send + 'static, +{ + type ConnectionHandler = KademliaHandlerProto; + type OutEvent = KademliaEvent; - for query in self.queries.iter_mut() { - query.on_failure(&peer_id); - } - } - DialError::DialPeerConditionFalse( - dial_opts::PeerCondition::Disconnected | dial_opts::PeerCondition::NotDialing, - ) => { - // We might (still) be connected, or about to be connected, thus do not report the - // failure to the queries. - } - DialError::DialPeerConditionFalse(dial_opts::PeerCondition::Always) => { - unreachable!("DialPeerCondition::Always can not trigger DialPeerConditionFalse."); - } - } + fn new_handler(&mut self) -> Self::ConnectionHandler { + KademliaHandlerProto::new(KademliaHandlerConfig { + protocol_config: self.protocol_config.clone(), + allow_listening: true, + idle_timeout: self.connection_idle_timeout, + }) } - fn inject_connection_closed( - &mut self, - id: &PeerId, - _: &ConnectionId, - _: &ConnectedPoint, - _: ::Handler, - remaining_established: usize, - ) { - if remaining_established == 0 { - for query in self.queries.iter_mut() { - query.on_failure(id); + fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec { + // We should order addresses from decreasing likelyhood of connectivity, so start with + // the addresses of that peer in the k-buckets. + let key = kbucket::Key::from(*peer_id); + let mut peer_addrs = + if let kbucket::Entry::Present(mut entry, _) = self.kbuckets.entry(&key) { + let addrs = entry.value().iter().cloned().collect::>(); + debug_assert!(!addrs.is_empty(), "Empty peer addresses in routing table."); + addrs + } else { + Vec::new() + }; + + // We add to that a temporary list of addresses from the ongoing queries. + for query in self.queries.iter() { + if let Some(addrs) = query.inner.addresses.get(peer_id) { + peer_addrs.extend(addrs.iter().cloned()) } - self.connection_updated(*id, None, NodeStatus::Disconnected); - self.connected_peers.remove(id); } + + peer_addrs } - fn inject_event( + fn on_connection_handler_event( &mut self, source: PeerId, - connection: ConnectionId, + connection_id: ConnectionId, event: KademliaHandlerEvent, ) { match event { @@ -2009,7 +2019,7 @@ where self.queued_events .push_back(NetworkBehaviourAction::NotifyHandler { peer_id: source, - handler: NotifyHandler::One(connection), + handler: NotifyHandler::One(connection_id), event: KademliaHandlerIn::FindNodeRes { closer_peers, request_id, @@ -2041,7 +2051,7 @@ where self.queued_events .push_back(NetworkBehaviourAction::NotifyHandler { peer_id: source, - handler: NotifyHandler::One(connection), + handler: NotifyHandler::One(connection_id), event: KademliaHandlerIn::GetProvidersRes { closer_peers, provider_peers, @@ -2118,7 +2128,7 @@ where self.queued_events .push_back(NetworkBehaviourAction::NotifyHandler { peer_id: source, - handler: NotifyHandler::One(connection), + handler: NotifyHandler::One(connection_id), event: KademliaHandlerIn::GetRecordRes { record, closer_peers, @@ -2190,7 +2200,7 @@ where } KademliaHandlerEvent::PutRecord { record, request_id } => { - self.record_received(source, connection, request_id, record); + self.record_received(source, connection_id, request_id, record); } KademliaHandlerEvent::PutRecordRes { user_data, .. } => { @@ -2225,20 +2235,6 @@ where }; } - fn inject_new_listen_addr(&mut self, _id: ListenerId, addr: &Multiaddr) { - self.local_addrs.insert(addr.clone()); - } - - fn inject_expired_listen_addr(&mut self, _id: ListenerId, addr: &Multiaddr) { - self.local_addrs.remove(addr); - } - - fn inject_new_external_addr(&mut self, addr: &Multiaddr) { - if self.local_addrs.len() < MAX_LOCAL_EXTERNAL_ADDRS { - self.local_addrs.insert(addr.clone()); - } - } - fn poll( &mut self, cx: &mut Context<'_>, @@ -2360,6 +2356,31 @@ where } } } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(connection_established) => { + self.on_connection_established(connection_established) + } + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), + FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), + FromSwarm::ExpiredListenAddr(ExpiredListenAddr { addr, .. }) => { + self.local_addrs.remove(addr); + } + FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => { + if self.local_addrs.len() < MAX_LOCAL_EXTERNAL_ADDRS { + self.local_addrs.insert(addr.clone()); + } + } + FromSwarm::NewListenAddr(NewListenAddr { addr, .. }) => { + self.local_addrs.insert(addr.clone()); + } + _ => {} + } + } } /// A quorum w.r.t. the configured replication factor specifies the minimum diff --git a/protocols/kad/src/behaviour/test.rs b/protocols/kad/src/behaviour/test.rs index c61ffaf158f..947dbcc3c9d 100644 --- a/protocols/kad/src/behaviour/test.rs +++ b/protocols/kad/src/behaviour/test.rs @@ -1277,7 +1277,7 @@ fn manual_bucket_inserts() { } #[test] -fn network_behaviour_inject_address_change() { +fn network_behaviour_on_address_change() { let local_peer_id = PeerId::random(); let remote_peer_id = PeerId::random(); @@ -1293,7 +1293,13 @@ fn network_behaviour_inject_address_change() { }; // Mimick a connection being established. - kademlia.inject_connection_established(&remote_peer_id, &connection_id, &endpoint, None, 0); + kademlia.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id: remote_peer_id, + connection_id, + endpoint: &endpoint, + failed_addresses: &[], + other_established: 0, + })); // At this point the remote is not yet known to support the // configured protocol name, so the peer is not yet in the @@ -1302,7 +1308,7 @@ fn network_behaviour_inject_address_change() { // Mimick the connection handler confirming the protocol for // the test connection, so that the peer is added to the routing table. - kademlia.inject_event( + kademlia.on_connection_handler_event( remote_peer_id, connection_id, KademliaHandlerEvent::ProtocolConfirmed { endpoint }, @@ -1313,18 +1319,18 @@ fn network_behaviour_inject_address_change() { kademlia.addresses_of_peer(&remote_peer_id), ); - kademlia.inject_address_change( - &remote_peer_id, - &connection_id, - &ConnectedPoint::Dialer { + kademlia.on_swarm_event(FromSwarm::AddressChange(AddressChange { + peer_id: remote_peer_id, + connection_id, + old: &ConnectedPoint::Dialer { address: old_address, role_override: Endpoint::Dialer, }, - &ConnectedPoint::Dialer { + new: &ConnectedPoint::Dialer { address: new_address.clone(), role_override: Endpoint::Dialer, }, - ); + })); assert_eq!( vec![new_address], From e18046a04fa0ad255563619f3a7e79e8823f4fb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 10:06:46 +0100 Subject: [PATCH 23/60] mdns/behaviour: replace inject_* methods with on_* --- protocols/mdns/src/behaviour.rs | 39 +++++++++++++++++---------------- 1 file changed, 20 insertions(+), 19 deletions(-) diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index b19845ac1d7..2c28b27a0e4 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -27,8 +27,8 @@ use crate::behaviour::{socket::AsyncSocket, timer::Builder}; use crate::MdnsConfig; use futures::Stream; use if_watch::{IfEvent, IfWatcher}; -use libp2p_core::transport::ListenerId; use libp2p_core::{Multiaddr, PeerId}; +use libp2p_swarm::behaviour::{ConnectionClosed, FromSwarm}; use libp2p_swarm::{ dummy, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, }; @@ -133,7 +133,7 @@ where .collect() } - fn inject_event( + fn on_connection_handler_event( &mut self, _: PeerId, _: libp2p_core::connection::ConnectionId, @@ -142,23 +142,24 @@ where void::unreachable(ev) } - fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) { - log::trace!("waking interface state because listening address changed"); - for iface in self.iface_states.values_mut() { - iface.fire_timer(); - } - } - - fn inject_connection_closed( - &mut self, - peer: &PeerId, - _: &libp2p_core::connection::ConnectionId, - _: &libp2p_core::ConnectedPoint, - _: Self::ConnectionHandler, - remaining_established: usize, - ) { - if remaining_established == 0 { - self.expire_node(peer); + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionClosed(ConnectionClosed { + peer_id, + remaining_established, + .. + }) => { + if remaining_established == 0 { + self.expire_node(&peer_id); + } + } + FromSwarm::NewListener(_) => { + log::trace!("waking interface state because listening address changed"); + for iface in self.iface_states.values_mut() { + iface.fire_timer(); + } + } + _ => {} } } From 133ca33c99da86e0b933175da5c00d5a98c8f13f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 10:09:10 +0100 Subject: [PATCH 24/60] ping/lib: replace inject_* methods with on_*, on NetworkBehaviour trait. --- protocols/ping/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protocols/ping/src/lib.rs b/protocols/ping/src/lib.rs index 42234488964..22a2b0418c5 100644 --- a/protocols/ping/src/lib.rs +++ b/protocols/ping/src/lib.rs @@ -119,7 +119,7 @@ impl NetworkBehaviour for Behaviour { Handler::new(self.config.clone()) } - fn inject_event(&mut self, peer: PeerId, _: ConnectionId, result: Result) { + fn on_connection_handler_event(&mut self, peer: PeerId, _: ConnectionId, result: Result) { self.events.push_front(Event { peer, result }) } From df73ad1eb40ed284998d0d6fc9e2735cacb0cce1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 10:44:17 +0100 Subject: [PATCH 25/60] relay: replace inject_* methods with on_* on Client and Relay NetworkBehaviour implementations --- protocols/relay/src/v2/client.rs | 83 ++++++++++++++++++-------------- protocols/relay/src/v2/relay.rs | 66 ++++++++++++++----------- 2 files changed, 85 insertions(+), 64 deletions(-) diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index 68e69e20a28..1328eeb02ba 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -32,10 +32,10 @@ use futures::future::{BoxFuture, FutureExt}; use futures::io::{AsyncRead, AsyncWrite}; use futures::ready; use futures::stream::StreamExt; -use libp2p_core::connection::{ConnectedPoint, ConnectionId}; -use libp2p_core::{Multiaddr, PeerId}; +use libp2p_core::connection::ConnectionId; +use libp2p_core::PeerId; +use libp2p_swarm::behaviour::{ConnectionEstablished, FromSwarm, ConnectionClosed}; use libp2p_swarm::dial_opts::DialOpts; -use libp2p_swarm::dummy; use libp2p_swarm::{ ConnectionHandlerUpgrErr, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, @@ -113,47 +113,25 @@ impl Client { }; (transport, behaviour) } -} - -impl NetworkBehaviour for Client { - type ConnectionHandler = handler::Prototype; - type OutEvent = Event; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - handler::Prototype::new(self.local_peer_id, None) - } - - fn inject_connection_established( - &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - endpoint: &ConnectedPoint, - _failed_addresses: Option<&Vec>, - _other_established: usize, - ) { - if !endpoint.is_relayed() { - self.directly_connected_peers - .entry(*peer_id) - .or_default() - .push(*connection_id); - } - } - fn inject_connection_closed( + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_closed( &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - endpoint: &ConnectedPoint, - _handler: Either, - _remaining_established: usize, + ConnectionClosed { + peer_id, + connection_id, + endpoint, + .. + }: ConnectionClosed<::ConnectionHandler>, ) { if !endpoint.is_relayed() { - match self.directly_connected_peers.entry(*peer_id) { + match self.directly_connected_peers.entry(peer_id) { hash_map::Entry::Occupied(mut connections) => { let position = connections .get() .iter() - .position(|c| c == connection_id) + .position(|c| c == &connection_id) .expect("Connection to be known."); connections.get_mut().remove(position); @@ -167,8 +145,39 @@ impl NetworkBehaviour for Client { }; } } +} + +impl NetworkBehaviour for Client { + type ConnectionHandler = handler::Prototype; + type OutEvent = Event; + + fn new_handler(&mut self) -> Self::ConnectionHandler { + handler::Prototype::new(self.local_peer_id, None) + } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id, + connection_id, + endpoint, + .. + }) => { + if !endpoint.is_relayed() { + self.directly_connected_peers + .entry(peer_id) + .or_default() + .push(connection_id); + } + } + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + _ => {} + } + } - fn inject_event( + fn on_connection_handler_event( &mut self, event_source: PeerId, _connection: ConnectionId, diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index 5b1eb810f60..65cc0d12e26 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -27,11 +27,12 @@ use crate::v2::message_proto; use crate::v2::protocol::inbound_hop; use either::Either; use instant::Instant; -use libp2p_core::connection::{ConnectedPoint, ConnectionId}; +use libp2p_core::connection::ConnectionId; use libp2p_core::multiaddr::Protocol; use libp2p_core::PeerId; +use libp2p_swarm::behaviour::{ConnectionClosed, FromSwarm}; use libp2p_swarm::{ - dummy, ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use std::collections::{hash_map, HashMap, HashSet, VecDeque}; @@ -212,32 +213,19 @@ impl Relay { queued_actions: Default::default(), } } -} - -impl NetworkBehaviour for Relay { - type ConnectionHandler = handler::Prototype; - type OutEvent = Event; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - handler::Prototype { - config: handler::Config { - reservation_duration: self.config.reservation_duration, - max_circuit_duration: self.config.max_circuit_duration, - max_circuit_bytes: self.config.max_circuit_bytes, - }, - } - } - fn inject_connection_closed( + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_closed( &mut self, - peer: &PeerId, - connection: &ConnectionId, - _: &ConnectedPoint, - _handler: Either, - _remaining_established: usize, + ConnectionClosed { + peer_id, + connection_id, + .. + }: ConnectionClosed<::ConnectionHandler>, ) { - if let hash_map::Entry::Occupied(mut peer) = self.reservations.entry(*peer) { - peer.get_mut().remove(connection); + if let hash_map::Entry::Occupied(mut peer) = self.reservations.entry(peer_id) { + peer.get_mut().remove(&connection_id); if peer.get().is_empty() { peer.remove(); } @@ -245,7 +233,7 @@ impl NetworkBehaviour for Relay { for circuit in self .circuits - .remove_by_connection(*peer, *connection) + .remove_by_connection(peer_id, connection_id) .iter() // Only emit [`CircuitClosed`] for accepted requests. .filter(|c| matches!(c.status, CircuitStatus::Accepted)) @@ -260,8 +248,32 @@ impl NetworkBehaviour for Relay { ); } } +} + +impl NetworkBehaviour for Relay { + type ConnectionHandler = handler::Prototype; + type OutEvent = Event; + + fn new_handler(&mut self) -> Self::ConnectionHandler { + handler::Prototype { + config: handler::Config { + reservation_duration: self.config.reservation_duration, + max_circuit_duration: self.config.max_circuit_duration, + max_circuit_bytes: self.config.max_circuit_bytes, + }, + } + } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + _ => {} + } + } - fn inject_event( + fn on_connection_handler_event( &mut self, event_source: PeerId, connection: ConnectionId, From 0af96014d6ab80da699ab73d3bb7fe1dfea711f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 10:51:52 +0100 Subject: [PATCH 26/60] rendezvous: replace inject_* methods with on_* on Client and Server NetworkBehaviour implementation. --- protocols/rendezvous/src/client.rs | 2 +- protocols/rendezvous/src/server.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/protocols/rendezvous/src/client.rs b/protocols/rendezvous/src/client.rs index 5ceb945a4f1..93115b5386b 100644 --- a/protocols/rendezvous/src/client.rs +++ b/protocols/rendezvous/src/client.rs @@ -183,7 +183,7 @@ impl NetworkBehaviour for Behaviour { .collect() } - fn inject_event( + fn on_connection_handler_event( &mut self, peer_id: PeerId, connection_id: ConnectionId, diff --git a/protocols/rendezvous/src/server.rs b/protocols/rendezvous/src/server.rs index dd4731d8a8d..e88de1d056c 100644 --- a/protocols/rendezvous/src/server.rs +++ b/protocols/rendezvous/src/server.rs @@ -118,7 +118,7 @@ impl NetworkBehaviour for Behaviour { SubstreamConnectionHandler::new_inbound_only(initial_keep_alive) } - fn inject_event( + fn on_connection_handler_event( &mut self, peer_id: PeerId, connection: ConnectionId, From 44e0e7c8360d96e46e69526b367427d1d924d04b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 11:24:07 +0100 Subject: [PATCH 27/60] general: update changelogs --- protocols/autonat/CHANGELOG.md | 5 +++++ protocols/dcutr/CHANGELOG.md | 5 +++++ protocols/floodsub/CHANGELOG.md | 5 +++++ protocols/gossipsub/CHANGELOG.md | 5 +++++ protocols/identify/CHANGELOG.md | 5 +++++ protocols/kad/CHANGELOG.md | 5 +++++ protocols/mdns/CHANGELOG.md | 5 +++++ protocols/ping/CHANGELOG.md | 5 +++++ protocols/relay/CHANGELOG.md | 5 +++++ protocols/rendezvous/CHANGELOG.md | 5 +++++ swarm/CHANGELOG.md | 10 ++++++++++ 11 files changed, 60 insertions(+) diff --git a/protocols/autonat/CHANGELOG.md b/protocols/autonat/CHANGELOG.md index 6f55afa4c06..6b9786c35b2 100644 --- a/protocols/autonat/CHANGELOG.md +++ b/protocols/autonat/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.8.1 - [unreleased] + +- replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.8.0 - Update to `libp2p-core` `v0.37.0`. diff --git a/protocols/dcutr/CHANGELOG.md b/protocols/dcutr/CHANGELOG.md index 0d49f90d008..cac738ec886 100644 --- a/protocols/dcutr/CHANGELOG.md +++ b/protocols/dcutr/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.7.1 - [unreleased] + +- replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.7.0 - Update to `libp2p-core` `v0.37.0`. diff --git a/protocols/floodsub/CHANGELOG.md b/protocols/floodsub/CHANGELOG.md index dd42387eda2..fcbc946112b 100644 --- a/protocols/floodsub/CHANGELOG.md +++ b/protocols/floodsub/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.40.1 - [unreleased] + +- replace `Floodsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.40.0 - Bump rand to 0.8 and quickcheck to 1. See [PR 2857]. diff --git a/protocols/gossipsub/CHANGELOG.md b/protocols/gossipsub/CHANGELOG.md index 555c146af11..a3f1f8d66f6 100644 --- a/protocols/gossipsub/CHANGELOG.md +++ b/protocols/gossipsub/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.42.1 - [unreleased] + +- replace `Gossipsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.42.0 - Bump rand to 0.8 and quickcheck to 1. See [PR 2857]. diff --git a/protocols/identify/CHANGELOG.md b/protocols/identify/CHANGELOG.md index f60ace8ace0..e1b4ff6b526 100644 --- a/protocols/identify/CHANGELOG.md +++ b/protocols/identify/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.40.1 - [unreleased] + +- replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.40.0 - Update dependencies. diff --git a/protocols/kad/CHANGELOG.md b/protocols/kad/CHANGELOG.md index 9a76bb9c9df..cf044eac280 100644 --- a/protocols/kad/CHANGELOG.md +++ b/protocols/kad/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.41.1 - [unreleased] + +- replace `Kademlia`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.41.0 - Remove deprecated `set_protocol_name()` from `KademliaConfig` & `KademliaProtocolConfig`. diff --git a/protocols/mdns/CHANGELOG.md b/protocols/mdns/CHANGELOG.md index 66a2ee57394..e19c0f745a9 100644 --- a/protocols/mdns/CHANGELOG.md +++ b/protocols/mdns/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.41.1 - [unreleased] + +- replace `GenMdns`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.41.0 - Remove default features. If you previously depended on `async-io` you need to enable this explicitly now. See [PR 2918]. diff --git a/protocols/ping/CHANGELOG.md b/protocols/ping/CHANGELOG.md index bcdcdf9ab0e..08b721b3219 100644 --- a/protocols/ping/CHANGELOG.md +++ b/protocols/ping/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.40.1 - [unreleased] + +- replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.40.0 - Bump rand to 0.8 and quickcheck to 1. See [PR 2857]. diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index b21d4123b08..7d335032bf6 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.13.1 - [unreleased] + +- replace `Client` and `Relay`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.13.0 - Update to `libp2p-core` `v0.37.0`. diff --git a/protocols/rendezvous/CHANGELOG.md b/protocols/rendezvous/CHANGELOG.md index 1b858855108..a832c44b740 100644 --- a/protocols/rendezvous/CHANGELOG.md +++ b/protocols/rendezvous/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.10.1 - [unreleased] + +- replace `Client` and `Server`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.10.0 - Update to `libp2p-core` `v0.37.0`. diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 1758579dc21..234c78db635 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -1,3 +1,13 @@ +# 0.40.1 - [unreleased] + +- Add new `on_swarm_event` method to `NetworkBehaviour` that accepts a `FromSwarm` enum and update + `inject_*` methods to call `on_swarm_event` with the respective `FromSwarm` variant and deprecate + them. See [PR 3011]. + +- Add new `on_connection_handler_event` method with the same signature as `inject_event`, make the + default implementation of `inject_event` call `on_connection_handler_event` and deprecate it. + See [PR 3011]. + # 0.40.0 - Bump rand to 0.8 and quickcheck to 1. See [PR 2857]. From c037679e74e527790b8458bb4f6a03a70c6fe4d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 11:49:58 +0100 Subject: [PATCH 28/60] request-response: update changelog --- protocols/request-response/CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/protocols/request-response/CHANGELOG.md b/protocols/request-response/CHANGELOG.md index a48d74ee82f..b6a65548588 100644 --- a/protocols/request-response/CHANGELOG.md +++ b/protocols/request-response/CHANGELOG.md @@ -1,3 +1,8 @@ +# 0.22.1 - [unreleased] + +- replace `RequestResponse`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011]. + # 0.22.0 - Bump rand to 0.8 and quickcheck to 1. See [PR 2857]. From 92edc14eed5d3410022206a5ce91c830b38d9f6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 19:55:13 +0100 Subject: [PATCH 29/60] general: apply cargo fmt and clippy --- protocols/autonat/src/behaviour.rs | 3 +- protocols/dcutr/src/behaviour.rs | 8 ++--- protocols/identify/src/behaviour.rs | 7 ++-- protocols/relay/src/v2/client.rs | 2 +- protocols/request-response/src/lib.rs | 12 +++---- swarm/tests/public_api.rs | 52 ++++++++++++++------------- 6 files changed, 39 insertions(+), 45 deletions(-) diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index db5b6f335d3..0148b0fc882 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -40,7 +40,8 @@ use libp2p_swarm::{ AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr, ExpiredListenAddr, FromSwarm, }, - NetworkBehaviour, NetworkBehaviourAction, PollParameters, ConnectionHandler, IntoConnectionHandler, + ConnectionHandler, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, + PollParameters, }; use std::{ collections::{HashMap, VecDeque}, diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 418a2f4208b..315e75a8209 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -29,8 +29,8 @@ use libp2p_core::{Multiaddr, PeerId}; use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}; use libp2p_swarm::dial_opts::{self, DialOpts}; use libp2p_swarm::{ - ConnectionHandler, ConnectionHandlerUpgrErr, IntoConnectionHandler, - NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, + ConnectionHandler, ConnectionHandlerUpgrErr, IntoConnectionHandler, NetworkBehaviour, + NetworkBehaviourAction, NotifyHandler, PollParameters, }; use std::collections::{HashMap, HashSet, VecDeque}; use std::task::{Context, Poll}; @@ -162,9 +162,7 @@ impl Behaviour { fn on_dial_failure( &mut self, DialFailure { - peer_id, - handler, - .. + peer_id, handler, .. }: DialFailure<::ConnectionHandler>, ) { if let handler::Prototype::DirectConnection { diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index 8d922c4f3e2..fa3cdebeb6c 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -22,12 +22,9 @@ use crate::handler::{self, Proto, Push}; use crate::protocol::{Info, ReplySubstream, UpgradeError}; use futures::prelude::*; use libp2p_core::{ - connection::ConnectionId, multiaddr::Protocol, ConnectedPoint, - Multiaddr, PeerId, PublicKey, -}; -use libp2p_swarm::behaviour::{ - ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm, + connection::ConnectionId, multiaddr::Protocol, ConnectedPoint, Multiaddr, PeerId, PublicKey, }; +use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}; use libp2p_swarm::{ dial_opts::DialOpts, AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError, IntoConnectionHandler, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index 1328eeb02ba..f883a90e8af 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -34,7 +34,7 @@ use futures::ready; use futures::stream::StreamExt; use libp2p_core::connection::ConnectionId; use libp2p_core::PeerId; -use libp2p_swarm::behaviour::{ConnectionEstablished, FromSwarm, ConnectionClosed}; +use libp2p_swarm::behaviour::{ConnectionClosed, ConnectionEstablished, FromSwarm}; use libp2p_swarm::dial_opts::DialOpts; use libp2p_swarm::{ ConnectionHandlerUpgrErr, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index 85c25c163c6..20afd6f8019 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -68,8 +68,7 @@ use libp2p_core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId}; use libp2p_swarm::{ behaviour::{AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm}, dial_opts::DialOpts, - IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, - PollParameters, + IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use smallvec::SmallVec; use std::{ @@ -664,7 +663,7 @@ where let connection = connections .iter_mut() - .find(|c| &c.id == &connection_id) + .find(|c| c.id == connection_id) .expect("Address change can only happen on an established connection."); connection.address = new_address; } @@ -673,10 +672,7 @@ where /// [event](`NetworkBehaviour::on_swarm_event`). fn on_dial_failure( &mut self, - DialFailure { - peer_id, - .. - }: DialFailure<::ConnectionHandler>, + DialFailure { peer_id, .. }: DialFailure<::ConnectionHandler>, ) { if let Some(peer) = peer_id { // If there are pending outgoing requests when a dial failure occurs, @@ -742,7 +738,7 @@ where } FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), - _ => {}, + _ => {} } } diff --git a/swarm/tests/public_api.rs b/swarm/tests/public_api.rs index ca9d05a8d84..ff0804acc57 100644 --- a/swarm/tests/public_api.rs +++ b/swarm/tests/public_api.rs @@ -1,64 +1,66 @@ use libp2p::core::transport::ListenerId; use libp2p::swarm::behaviour::FromSwarm; use libp2p::swarm::dummy; +use libp2p_swarm::behaviour::{ConnectionEstablished, ConnectionClosed, AddressChange, DialFailure, ListenFailure, NewListener, NewListenAddr, ExpiredListenAddr, ListenerError, ListenerClosed, NewExternalAddr, ExpiredExternalAddr}; #[test] // test to break compilation everytime a variant changes, // forcing us to revisit each implementation fn swarm_event_variants() { - let event: FromSwarm<'_, dummy::ConnectionHandler> = FromSwarm::ListenerClosed { - listener_id: ListenerId::new(), - reason: Ok(()), - }; + let event: FromSwarm<'_, dummy::ConnectionHandler> = + FromSwarm::ListenerClosed(libp2p_swarm::behaviour::ListenerClosed { + listener_id: ListenerId::new(), + reason: Ok(()), + }); match event { - FromSwarm::ConnectionEstablished { + FromSwarm::ConnectionEstablished( ConnectionEstablished { peer_id: _, connection_id: _, endpoint: _, failed_addresses: _, other_established: _, - } => {} - FromSwarm::ConnectionClosed { + }) => {} + FromSwarm::ConnectionClosed(ConnectionClosed { peer_id: _, connection_id: _, endpoint: _, handler: _, remaining_established: _, - } => {} - FromSwarm::AddressChange { + }) => {} + FromSwarm::AddressChange(AddressChange { peer_id: _, connection_id: _, old: _, new: _, - } => {} - FromSwarm::DialFailure { + }) => {} + FromSwarm::DialFailure(DialFailure { peer_id: _, handler: _, error: _, - } => {} - FromSwarm::ListenFailure { + }) => {} + FromSwarm::ListenFailure(ListenFailure { local_addr: _, send_back_addr: _, handler: _, - } => {} - FromSwarm::NewListener { listener_id: _ } => {} - FromSwarm::NewListenAddr { + }) => {} + FromSwarm::NewListener(NewListener { listener_id: _ }) => {} + FromSwarm::NewListenAddr(NewListenAddr { listener_id: _, addr: _, - } => {} - FromSwarm::ExpiredListenAddr { + }) => {} + FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id: _, addr: _, - } => {} - FromSwarm::ListenerError { + }) => {} + FromSwarm::ListenerError(ListenerError { listener_id: _, err: _, - } => {} - FromSwarm::ListenerClosed { + }) => {} + FromSwarm::ListenerClosed(ListenerClosed { listener_id: _, reason: _, - } => {} - FromSwarm::NewExternalAddr { addr: _ } => {} - FromSwarm::ExpiredExternalAddr { addr: _ } => {} + }) => {} + FromSwarm::NewExternalAddr(NewExternalAddr { addr: _ }) => {} + FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr: _ }) => {} } } From 1da43f13a8de23862a8e1e92203fc6a9b89f3e1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 20:15:00 +0100 Subject: [PATCH 30/60] general: apply cargo fmt and clipy --- protocols/dcutr/src/behaviour.rs | 2 +- swarm/tests/public_api.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 315e75a8209..8caab1bbfe8 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -107,7 +107,7 @@ impl Behaviour { // https://github.com/libp2p/specs/blob/master/relay/DCUtR.md#the-protocol self.queued_actions.extend([ ActionBuilder::Connect { - peer_id: peer_id, + peer_id, attempt: 1, handler: NotifyHandler::One(connection_id), }, diff --git a/swarm/tests/public_api.rs b/swarm/tests/public_api.rs index ff0804acc57..5ebaffeb5cf 100644 --- a/swarm/tests/public_api.rs +++ b/swarm/tests/public_api.rs @@ -1,7 +1,11 @@ use libp2p::core::transport::ListenerId; use libp2p::swarm::behaviour::FromSwarm; use libp2p::swarm::dummy; -use libp2p_swarm::behaviour::{ConnectionEstablished, ConnectionClosed, AddressChange, DialFailure, ListenFailure, NewListener, NewListenAddr, ExpiredListenAddr, ListenerError, ListenerClosed, NewExternalAddr, ExpiredExternalAddr}; +use libp2p_swarm::behaviour::{ + AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr, + ExpiredListenAddr, ListenFailure, ListenerClosed, ListenerError, NewExternalAddr, + NewListenAddr, NewListener, +}; #[test] // test to break compilation everytime a variant changes, @@ -13,7 +17,7 @@ fn swarm_event_variants() { reason: Ok(()), }); match event { - FromSwarm::ConnectionEstablished( ConnectionEstablished { + FromSwarm::ConnectionEstablished(ConnectionEstablished { peer_id: _, connection_id: _, endpoint: _, From 29f5badd34d6c92f1937c3bc1d662a85f3727a73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 20:35:14 +0100 Subject: [PATCH 31/60] swarm/test: replace inject_* with on_* methods on NetworkBehaviour implementation. --- swarm/src/lib.rs | 16 +-- swarm/src/test.rs | 287 ++++++++++++++++++++++++---------------------- 2 files changed, 161 insertions(+), 142 deletions(-) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index eaaad2a7ae8..cb3e5c22e14 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -1749,7 +1749,7 @@ mod tests { // The banned connection was established. Check that it was not reported to // the behaviour of the banning swarm. assert_eq!( - swarm2.behaviour.inject_connection_established.len(), s2_expected_conns, + swarm2.behaviour.on_connection_established.len(), s2_expected_conns, "No additional closed connections should be reported for the banned peer" ); @@ -1763,7 +1763,7 @@ mod tests { if swarm2.network_info().num_peers() == 0 { // The banned connection has closed. Check that it was not reported. assert_eq!( - swarm2.behaviour.inject_connection_closed.len(), s2_expected_conns, + swarm2.behaviour.on_connection_closed.len(), s2_expected_conns, "No additional closed connections should be reported for the banned peer" ); assert!(swarm2.banned_peer_connections.is_empty()); @@ -1778,7 +1778,7 @@ mod tests { } } Stage::Reconnecting => { - if swarm1.behaviour.inject_connection_established.len() == s1_expected_conns + if swarm1.behaviour.on_connection_established.len() == s1_expected_conns && swarm2.behaviour.assert_connected(s2_expected_conns, 2) { return Poll::Ready(()); @@ -1963,7 +1963,7 @@ mod tests { State::Connecting => { if swarms_connected(&swarm1, &swarm2, num_connections) { disconnected_conn_id = { - let conn_id = swarm2.behaviour.inject_connection_established + let conn_id = swarm2.behaviour.on_connection_established [num_connections / 2] .1; swarm2.behaviour.inner().next_action.replace( @@ -1981,20 +1981,20 @@ mod tests { for s in &[&swarm1, &swarm2] { assert!(s .behaviour - .inject_connection_closed + .on_connection_closed .iter() .all(|(.., remaining_conns)| *remaining_conns > 0)); assert_eq!( - s.behaviour.inject_connection_established.len(), + s.behaviour.on_connection_established.len(), num_connections ); s.behaviour.assert_connected(num_connections, 1); } if [&swarm1, &swarm2] .iter() - .all(|s| s.behaviour.inject_connection_closed.len() == 1) + .all(|s| s.behaviour.on_connection_closed.len() == 1) { - let conn_id = swarm2.behaviour.inject_connection_closed[0].1; + let conn_id = swarm2.behaviour.on_connection_closed[0].1; assert_eq!(Some(conn_id), disconnected_conn_id); return Poll::Ready(()); } diff --git a/swarm/src/test.rs b/swarm/src/test.rs index 093ee420cb5..4abfd2743a7 100644 --- a/swarm/src/test.rs +++ b/swarm/src/test.rs @@ -18,8 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::behaviour::{FromSwarm, ConnectionEstablished, ConnectionClosed, DialFailure, ListenerClosed, ListenerError, ExpiredExternalAddr, NewExternalAddr, ExpiredListenAddr, NewListener, NewListenAddr}; use crate::{ - ConnectionHandler, DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, + ConnectionHandler, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, }; use libp2p_core::{ @@ -76,8 +77,6 @@ where self.addresses.get(p).map_or(Vec::new(), |v| v.clone()) } - fn inject_event(&mut self, _: PeerId, _: ConnectionId, _: THandler::OutEvent) {} - fn poll( &mut self, _: &mut Context, @@ -97,43 +96,45 @@ where inner: TInner, pub addresses_of_peer: Vec, - pub inject_connection_established: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, - pub inject_connection_closed: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, - pub inject_event: Vec<( + pub on_connection_established: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, + pub on_connection_closed: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, + pub on_event: Vec<( PeerId, ConnectionId, <::Handler as ConnectionHandler>::OutEvent, )>, - pub inject_dial_failure: Vec>, - pub inject_new_listener: Vec, - pub inject_new_listen_addr: Vec<(ListenerId, Multiaddr)>, - pub inject_new_external_addr: Vec, - pub inject_expired_listen_addr: Vec<(ListenerId, Multiaddr)>, - pub inject_expired_external_addr: Vec, - pub inject_listener_error: Vec, - pub inject_listener_closed: Vec<(ListenerId, bool)>, + pub on_dial_failure: Vec>, + pub on_new_listener: Vec, + pub on_new_listen_addr: Vec<(ListenerId, Multiaddr)>, + pub on_new_external_addr: Vec, + pub on_expired_listen_addr: Vec<(ListenerId, Multiaddr)>, + pub on_expired_external_addr: Vec, + pub on_listener_error: Vec, + pub on_listener_closed: Vec<(ListenerId, bool)>, pub poll: usize, } impl CallTraceBehaviour where TInner: NetworkBehaviour, + <::Handler as ConnectionHandler>::OutEvent: + Clone, { pub fn new(inner: TInner) -> Self { Self { inner, addresses_of_peer: Vec::new(), - inject_connection_established: Vec::new(), - inject_connection_closed: Vec::new(), - inject_event: Vec::new(), - inject_dial_failure: Vec::new(), - inject_new_listener: Vec::new(), - inject_new_listen_addr: Vec::new(), - inject_new_external_addr: Vec::new(), - inject_expired_listen_addr: Vec::new(), - inject_expired_external_addr: Vec::new(), - inject_listener_error: Vec::new(), - inject_listener_closed: Vec::new(), + on_connection_established: Vec::new(), + on_connection_closed: Vec::new(), + on_event: Vec::new(), + on_dial_failure: Vec::new(), + on_new_listener: Vec::new(), + on_new_listen_addr: Vec::new(), + on_new_external_addr: Vec::new(), + on_expired_listen_addr: Vec::new(), + on_expired_external_addr: Vec::new(), + on_listener_error: Vec::new(), + on_listener_closed: Vec::new(), poll: 0, } } @@ -141,15 +142,15 @@ where #[allow(dead_code)] pub fn reset(&mut self) { self.addresses_of_peer = Vec::new(); - self.inject_connection_established = Vec::new(); - self.inject_connection_closed = Vec::new(); - self.inject_event = Vec::new(); - self.inject_dial_failure = Vec::new(); - self.inject_new_listen_addr = Vec::new(); - self.inject_new_external_addr = Vec::new(); - self.inject_expired_listen_addr = Vec::new(); - self.inject_listener_error = Vec::new(); - self.inject_listener_closed = Vec::new(); + self.on_connection_established = Vec::new(); + self.on_connection_closed = Vec::new(); + self.on_event = Vec::new(); + self.on_dial_failure = Vec::new(); + self.on_new_listen_addr = Vec::new(); + self.on_new_external_addr = Vec::new(); + self.on_expired_listen_addr = Vec::new(); + self.on_listener_error = Vec::new(); + self.on_listener_closed = Vec::new(); self.poll = 0; } @@ -158,12 +159,12 @@ where } pub fn num_connections_to_peer(&self, peer: PeerId) -> usize { - self.inject_connection_established + self.on_connection_established .iter() .filter(|(peer_id, _, _, _)| *peer_id == peer) .count() - self - .inject_connection_closed + .on_connection_closed .iter() .filter(|(peer_id, _, _, _)| *peer_id == peer) .count() @@ -178,9 +179,9 @@ where expected_closed_connections: usize, expected_disconnections: usize, ) -> bool { - if self.inject_connection_closed.len() == expected_closed_connections { + if self.on_connection_closed.len() == expected_closed_connections { assert_eq!( - self.inject_connection_closed + self.on_connection_closed .iter() .filter(|(.., remaining_established)| { *remaining_established == 0 }) .count(), @@ -201,9 +202,9 @@ where expected_established_connections: usize, expected_connections: usize, ) -> bool { - if self.inject_connection_established.len() == expected_established_connections { + if self.on_connection_established.len() == expected_established_connections { assert_eq!( - self.inject_connection_established + self.on_connection_established .iter() .filter(|(.., reported_aditional_connections)| { *reported_aditional_connections == 0 @@ -216,40 +217,25 @@ where false } -} - -impl NetworkBehaviour for CallTraceBehaviour -where - TInner: NetworkBehaviour, - <::Handler as ConnectionHandler>::OutEvent: - Clone, -{ - type ConnectionHandler = TInner::ConnectionHandler; - type OutEvent = TInner::OutEvent; - - fn new_handler(&mut self) -> Self::ConnectionHandler { - self.inner.new_handler() - } - - fn addresses_of_peer(&mut self, p: &PeerId) -> Vec { - self.addresses_of_peer.push(*p); - self.inner.addresses_of_peer(p) - } - fn inject_connection_established( + /// Called on the [`FromSwarm::ConnectionEstablished`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_established( &mut self, - p: &PeerId, - c: &ConnectionId, - e: &ConnectedPoint, - errors: Option<&Vec>, - other_established: usize, + ConnectionEstablished { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + }: ConnectionEstablished, ) { let mut other_peer_connections = self - .inject_connection_established + .on_connection_established .iter() .rev() // take last to first .filter_map(|(peer, .., other_established)| { - if p == peer { + if &peer_id == peer { Some(other_established) } else { None @@ -271,26 +257,33 @@ where } else { assert_eq!(other_established, 0) } - self.inject_connection_established - .push((*p, *c, e.clone(), other_established)); + self.on_connection_established + .push((peer_id, connection_id, endpoint.clone(), other_established)); + let errors = Some(failed_addresses.to_vec()); + #[allow(deprecated)] self.inner - .inject_connection_established(p, c, e, errors, other_established); + .inject_connection_established(&peer_id, &connection_id, endpoint, errors.as_ref(), other_established); } - fn inject_connection_closed( + /// Called on the [`FromSwarm::ConnectionClosed`] + /// [event](`NetworkBehaviour::on_swarm_event`). + fn on_connection_closed( &mut self, - p: &PeerId, - c: &ConnectionId, - e: &ConnectedPoint, - handler: ::Handler, - remaining_established: usize, + ConnectionClosed { + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + }: ConnectionClosed<::ConnectionHandler>, ) { + let mut other_closed_connections = self - .inject_connection_established + .on_connection_established .iter() .rev() // take last to first .filter_map(|(peer, .., remaining_established)| { - if p == peer { + if &peer_id == peer { Some(remaining_established) } else { None @@ -313,87 +306,113 @@ where assert_eq!(remaining_established, 0) } assert!( - self.inject_connection_established + self.on_connection_established .iter() - .any(|(peer, conn_id, endpoint, _)| (peer, conn_id, endpoint) == (p, c, e)), + .any(|(peer, conn_id, endpoint, _)| (peer, conn_id, endpoint) == (&peer_id, + &connection_id, endpoint)), "`inject_connection_closed` is called only for connections for \ which `inject_connection_established` was called first." ); - self.inject_connection_closed - .push((*p, *c, e.clone(), remaining_established)); + self.on_connection_closed + .push((peer_id, connection_id, endpoint.clone(), remaining_established)); + #[allow(deprecated)] self.inner - .inject_connection_closed(p, c, e, handler, remaining_established); + .inject_connection_closed(&peer_id, &connection_id, endpoint, handler, remaining_established); } +} + +impl NetworkBehaviour for CallTraceBehaviour +where + TInner: NetworkBehaviour, + <::Handler as ConnectionHandler>::OutEvent: + Clone, +{ + type ConnectionHandler = TInner::ConnectionHandler; + type OutEvent = TInner::OutEvent; - fn inject_event( + fn new_handler(&mut self) -> Self::ConnectionHandler { + self.inner.new_handler() + } + + fn addresses_of_peer(&mut self, p: &PeerId) -> Vec { + self.addresses_of_peer.push(*p); + self.inner.addresses_of_peer(p) + } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(connection_established) => + self.on_connection_established(connection_established), + FromSwarm::ConnectionClosed(connection_closed) => self.on_connection_closed(connection_closed), + FromSwarm::DialFailure(DialFailure { peer_id, handler, error }) => { + self.on_dial_failure.push(peer_id); + #[allow(deprecated)] + self.inner.inject_dial_failure(peer_id, handler, error); + } + FromSwarm::NewListener(NewListener { listener_id }) => { + self.on_new_listener.push(listener_id); + #[allow(deprecated)] + self.inner.inject_new_listener(listener_id); + } + FromSwarm::NewListenAddr(NewListenAddr { listener_id, addr }) => { + self.on_new_listen_addr.push((listener_id, addr.clone())); + #[allow(deprecated)] + self.inner.inject_new_listen_addr(listener_id, addr); + } + FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id, addr }) => { + self.on_expired_listen_addr.push((listener_id, addr.clone())); + #[allow(deprecated)] + self.inner.inject_expired_listen_addr(listener_id, addr); + } + FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => { + self.on_new_external_addr.push(addr.clone()); + #[allow(deprecated)] + self.inner.inject_new_external_addr(addr); + } + FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }) => { + self.on_expired_external_addr.push(addr.clone()); + #[allow(deprecated)] + self.inner.inject_expired_external_addr(addr); + } + FromSwarm::ListenerError(ListenerError { listener_id, err }) => { + self.on_listener_error.push(listener_id); + #[allow(deprecated)] + self.inner.inject_listener_error(listener_id, err); + } + FromSwarm::ListenerClosed(ListenerClosed { listener_id, reason }) => { + self.on_listener_closed.push((listener_id, reason.is_ok())); + #[allow(deprecated)] + self.inner.inject_listener_closed(listener_id, reason); + } + _ => {}, + } + } + + fn on_connection_handler_event( &mut self, p: PeerId, c: ConnectionId, e: <::Handler as ConnectionHandler>::OutEvent, ) { assert!( - self.inject_connection_established + self.on_connection_established .iter() .any(|(peer_id, conn_id, ..)| *peer_id == p && c == *conn_id), - "`inject_event` is called for reported connections." + "`on_connection_handler_event` is called for reported connections." ); assert!( !self - .inject_connection_closed + .on_connection_closed .iter() .any(|(peer_id, conn_id, ..)| *peer_id == p && c == *conn_id), - "`inject_event` is never called for closed connections." + "`on_connection_handler_event` is never called for closed connections." ); - self.inject_event.push((p, c, e.clone())); + self.on_event.push((p, c, e.clone())); + #[allow(deprecated)] self.inner.inject_event(p, c, e); } - fn inject_dial_failure( - &mut self, - p: Option, - handler: Self::ConnectionHandler, - error: &DialError, - ) { - self.inject_dial_failure.push(p); - self.inner.inject_dial_failure(p, handler, error); - } - - fn inject_new_listener(&mut self, id: ListenerId) { - self.inject_new_listener.push(id); - self.inner.inject_new_listener(id); - } - - fn inject_new_listen_addr(&mut self, id: ListenerId, a: &Multiaddr) { - self.inject_new_listen_addr.push((id, a.clone())); - self.inner.inject_new_listen_addr(id, a); - } - - fn inject_expired_listen_addr(&mut self, id: ListenerId, a: &Multiaddr) { - self.inject_expired_listen_addr.push((id, a.clone())); - self.inner.inject_expired_listen_addr(id, a); - } - - fn inject_new_external_addr(&mut self, a: &Multiaddr) { - self.inject_new_external_addr.push(a.clone()); - self.inner.inject_new_external_addr(a); - } - - fn inject_expired_external_addr(&mut self, a: &Multiaddr) { - self.inject_expired_external_addr.push(a.clone()); - self.inner.inject_expired_external_addr(a); - } - - fn inject_listener_error(&mut self, l: ListenerId, e: &(dyn std::error::Error + 'static)) { - self.inject_listener_error.push(l); - self.inner.inject_listener_error(l, e); - } - - fn inject_listener_closed(&mut self, l: ListenerId, r: Result<(), &std::io::Error>) { - self.inject_listener_closed.push((l, r.is_ok())); - self.inner.inject_listener_closed(l, r); - } - fn poll( &mut self, cx: &mut Context, From ac345b3e9b7047febed2425cee4d9c2dd4a94035 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 20:36:52 +0100 Subject: [PATCH 32/60] swarm: apply cargo fmt and clipy --- swarm/src/lib.rs | 10 +++---- swarm/src/test.rs | 69 ++++++++++++++++++++++++++++++++++------------- 2 files changed, 53 insertions(+), 26 deletions(-) diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index cb3e5c22e14..70407ee3bce 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -1963,9 +1963,8 @@ mod tests { State::Connecting => { if swarms_connected(&swarm1, &swarm2, num_connections) { disconnected_conn_id = { - let conn_id = swarm2.behaviour.on_connection_established - [num_connections / 2] - .1; + let conn_id = + swarm2.behaviour.on_connection_established[num_connections / 2].1; swarm2.behaviour.inner().next_action.replace( NetworkBehaviourAction::CloseConnection { peer_id: swarm1_id, @@ -1984,10 +1983,7 @@ mod tests { .on_connection_closed .iter() .all(|(.., remaining_conns)| *remaining_conns > 0)); - assert_eq!( - s.behaviour.on_connection_established.len(), - num_connections - ); + assert_eq!(s.behaviour.on_connection_established.len(), num_connections); s.behaviour.assert_connected(num_connections, 1); } if [&swarm1, &swarm2] diff --git a/swarm/src/test.rs b/swarm/src/test.rs index 4abfd2743a7..eea3d4cf551 100644 --- a/swarm/src/test.rs +++ b/swarm/src/test.rs @@ -18,7 +18,10 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::behaviour::{FromSwarm, ConnectionEstablished, ConnectionClosed, DialFailure, ListenerClosed, ListenerError, ExpiredExternalAddr, NewExternalAddr, ExpiredListenAddr, NewListener, NewListenAddr}; +use crate::behaviour::{ + ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr, ExpiredListenAddr, + FromSwarm, ListenerClosed, ListenerError, NewExternalAddr, NewListenAddr, NewListener, +}; use crate::{ ConnectionHandler, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, @@ -257,12 +260,21 @@ where } else { assert_eq!(other_established, 0) } - self.on_connection_established - .push((peer_id, connection_id, endpoint.clone(), other_established)); + self.on_connection_established.push(( + peer_id, + connection_id, + endpoint.clone(), + other_established, + )); let errors = Some(failed_addresses.to_vec()); #[allow(deprecated)] - self.inner - .inject_connection_established(&peer_id, &connection_id, endpoint, errors.as_ref(), other_established); + self.inner.inject_connection_established( + &peer_id, + &connection_id, + endpoint, + errors.as_ref(), + other_established, + ); } /// Called on the [`FromSwarm::ConnectionClosed`] @@ -277,7 +289,6 @@ where remaining_established, }: ConnectionClosed<::ConnectionHandler>, ) { - let mut other_closed_connections = self .on_connection_established .iter() @@ -308,16 +319,25 @@ where assert!( self.on_connection_established .iter() - .any(|(peer, conn_id, endpoint, _)| (peer, conn_id, endpoint) == (&peer_id, - &connection_id, endpoint)), + .any(|(peer, conn_id, endpoint, _)| (peer, conn_id, endpoint) + == (&peer_id, &connection_id, endpoint)), "`inject_connection_closed` is called only for connections for \ which `inject_connection_established` was called first." ); - self.on_connection_closed - .push((peer_id, connection_id, endpoint.clone(), remaining_established)); + self.on_connection_closed.push(( + peer_id, + connection_id, + endpoint.clone(), + remaining_established, + )); #[allow(deprecated)] - self.inner - .inject_connection_closed(&peer_id, &connection_id, endpoint, handler, remaining_established); + self.inner.inject_connection_closed( + &peer_id, + &connection_id, + endpoint, + handler, + remaining_established, + ); } } @@ -341,10 +361,17 @@ where fn on_swarm_event(&mut self, event: FromSwarm) { match event { - FromSwarm::ConnectionEstablished(connection_established) => - self.on_connection_established(connection_established), - FromSwarm::ConnectionClosed(connection_closed) => self.on_connection_closed(connection_closed), - FromSwarm::DialFailure(DialFailure { peer_id, handler, error }) => { + FromSwarm::ConnectionEstablished(connection_established) => { + self.on_connection_established(connection_established) + } + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + FromSwarm::DialFailure(DialFailure { + peer_id, + handler, + error, + }) => { self.on_dial_failure.push(peer_id); #[allow(deprecated)] self.inner.inject_dial_failure(peer_id, handler, error); @@ -360,7 +387,8 @@ where self.inner.inject_new_listen_addr(listener_id, addr); } FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id, addr }) => { - self.on_expired_listen_addr.push((listener_id, addr.clone())); + self.on_expired_listen_addr + .push((listener_id, addr.clone())); #[allow(deprecated)] self.inner.inject_expired_listen_addr(listener_id, addr); } @@ -379,12 +407,15 @@ where #[allow(deprecated)] self.inner.inject_listener_error(listener_id, err); } - FromSwarm::ListenerClosed(ListenerClosed { listener_id, reason }) => { + FromSwarm::ListenerClosed(ListenerClosed { + listener_id, + reason, + }) => { self.on_listener_closed.push((listener_id, reason.is_ok())); #[allow(deprecated)] self.inner.inject_listener_closed(listener_id, reason); } - _ => {}, + _ => {} } } From bdba3afa22a05c59db7ec9b317d7bbd89a60871b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 17 Oct 2022 20:56:09 +0100 Subject: [PATCH 33/60] relay: cargo clippy --- protocols/relay/src/v2/relay.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index 65cc0d12e26..5f19a47db78 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -265,11 +265,8 @@ impl NetworkBehaviour for Relay { } fn on_swarm_event(&mut self, event: FromSwarm) { - match event { - FromSwarm::ConnectionClosed(connection_closed) => { - self.on_connection_closed(connection_closed) - } - _ => {} + if let FromSwarm::ConnectionClosed(connection_closed) = event { + self.on_connection_closed(connection_closed) } } From 18e717ae7ccbfd404bc7de3c78bf59711749dca2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 19 Oct 2022 18:29:15 +0100 Subject: [PATCH 34/60] review: Update CHANGELOG according to Thomas review. --- protocols/autonat/CHANGELOG.md | 4 ++-- protocols/dcutr/CHANGELOG.md | 4 ++-- protocols/floodsub/CHANGELOG.md | 4 ++-- protocols/gossipsub/CHANGELOG.md | 4 ++-- protocols/identify/CHANGELOG.md | 4 ++-- protocols/kad/CHANGELOG.md | 4 ++-- protocols/mdns/CHANGELOG.md | 4 ++-- protocols/ping/CHANGELOG.md | 4 ++-- protocols/relay/CHANGELOG.md | 4 ++-- protocols/rendezvous/CHANGELOG.md | 4 ++-- protocols/request-response/CHANGELOG.md | 4 ++-- swarm/CHANGELOG.md | 4 ++-- 12 files changed, 24 insertions(+), 24 deletions(-) diff --git a/protocols/autonat/CHANGELOG.md b/protocols/autonat/CHANGELOG.md index 6b9786c35b2..7a62b01aa74 100644 --- a/protocols/autonat/CHANGELOG.md +++ b/protocols/autonat/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.8.1 - [unreleased] -- replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.8.0 diff --git a/protocols/dcutr/CHANGELOG.md b/protocols/dcutr/CHANGELOG.md index cac738ec886..812a8eb0689 100644 --- a/protocols/dcutr/CHANGELOG.md +++ b/protocols/dcutr/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.7.1 - [unreleased] -- replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.7.0 diff --git a/protocols/floodsub/CHANGELOG.md b/protocols/floodsub/CHANGELOG.md index fcbc946112b..38f642deac8 100644 --- a/protocols/floodsub/CHANGELOG.md +++ b/protocols/floodsub/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.40.1 - [unreleased] -- replace `Floodsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Floodsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.40.0 diff --git a/protocols/gossipsub/CHANGELOG.md b/protocols/gossipsub/CHANGELOG.md index a3f1f8d66f6..453f9c5d720 100644 --- a/protocols/gossipsub/CHANGELOG.md +++ b/protocols/gossipsub/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.42.1 - [unreleased] -- replace `Gossipsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Gossipsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.42.0 diff --git a/protocols/identify/CHANGELOG.md b/protocols/identify/CHANGELOG.md index e1b4ff6b526..8f3dc1ca795 100644 --- a/protocols/identify/CHANGELOG.md +++ b/protocols/identify/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.40.1 - [unreleased] -- replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.40.0 diff --git a/protocols/kad/CHANGELOG.md b/protocols/kad/CHANGELOG.md index cf044eac280..06cfe90afa5 100644 --- a/protocols/kad/CHANGELOG.md +++ b/protocols/kad/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.41.1 - [unreleased] -- replace `Kademlia`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Kademlia`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.41.0 diff --git a/protocols/mdns/CHANGELOG.md b/protocols/mdns/CHANGELOG.md index e19c0f745a9..4c1f2f90224 100644 --- a/protocols/mdns/CHANGELOG.md +++ b/protocols/mdns/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.41.1 - [unreleased] -- replace `GenMdns`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `GenMdns`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.41.0 diff --git a/protocols/ping/CHANGELOG.md b/protocols/ping/CHANGELOG.md index 08b721b3219..e4ddb5fcc6e 100644 --- a/protocols/ping/CHANGELOG.md +++ b/protocols/ping/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.40.1 - [unreleased] -- replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.40.0 diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index 7d335032bf6..db274592dd6 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.13.1 - [unreleased] -- replace `Client` and `Relay`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Client` and `Relay`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.13.0 diff --git a/protocols/rendezvous/CHANGELOG.md b/protocols/rendezvous/CHANGELOG.md index a832c44b740..ea5157a5856 100644 --- a/protocols/rendezvous/CHANGELOG.md +++ b/protocols/rendezvous/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.10.1 - [unreleased] -- replace `Client` and `Server`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `Client` and `Server`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.10.0 diff --git a/protocols/request-response/CHANGELOG.md b/protocols/request-response/CHANGELOG.md index b6a65548588..f9c0cb47cb3 100644 --- a/protocols/request-response/CHANGELOG.md +++ b/protocols/request-response/CHANGELOG.md @@ -1,7 +1,7 @@ # 0.22.1 - [unreleased] -- replace `RequestResponse`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011]. +- Replace `RequestResponse`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.22.0 diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 234c78db635..797fbad81d6 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -2,11 +2,11 @@ - Add new `on_swarm_event` method to `NetworkBehaviour` that accepts a `FromSwarm` enum and update `inject_*` methods to call `on_swarm_event` with the respective `FromSwarm` variant and deprecate - them. See [PR 3011]. + them. See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). - Add new `on_connection_handler_event` method with the same signature as `inject_event`, make the default implementation of `inject_event` call `on_connection_handler_event` and deprecate it. - See [PR 3011]. + See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). # 0.40.0 From 30dbe46de41765f5d447018c6afd361fdc8326aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 19 Oct 2022 18:41:20 +0100 Subject: [PATCH 35/60] review: remove probably not needed comments --- protocols/autonat/src/behaviour.rs | 8 -------- protocols/dcutr/src/behaviour.rs | 6 ------ protocols/floodsub/src/layer.rs | 4 ---- protocols/gossipsub/src/behaviour.rs | 6 ------ protocols/identify/src/behaviour.rs | 2 -- protocols/kad/src/behaviour.rs | 8 -------- protocols/relay/src/v2/client.rs | 2 -- protocols/relay/src/v2/relay.rs | 2 -- protocols/request-response/src/lib.rs | 8 -------- swarm/src/test.rs | 4 ---- 10 files changed, 50 deletions(-) diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index 0148b0fc882..929bca5e610 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -303,8 +303,6 @@ impl Behaviour { } } - /// Called on the [`FromSwarm::ConnectionEstablished`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, ConnectionEstablished { @@ -356,8 +354,6 @@ impl Behaviour { } } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { @@ -388,8 +384,6 @@ impl Behaviour { } } - /// Called on the [`FromSwarm::DialFailure`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_dial_failure( &mut self, DialFailure { @@ -410,8 +404,6 @@ impl Behaviour { } } - /// Called on the [`FromSwarm::AddressChange`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_address_change( &mut self, AddressChange { diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 8caab1bbfe8..78f005e64a4 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -83,8 +83,6 @@ impl Behaviour { } } - /// Called on the [`FromSwarm::ConnectionEstablished`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, ConnectionEstablished { @@ -131,8 +129,6 @@ impl Behaviour { } } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { @@ -157,8 +153,6 @@ impl Behaviour { } } - /// Called on the [`FromSwarm::DialFailure`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_dial_failure( &mut self, DialFailure { diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index f9a2214de8d..de0a0711f0a 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -278,8 +278,6 @@ impl Floodsub { } } - /// Called on the [`FromSwarm::ConnectionEstablished`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, ConnectionEstablished { @@ -314,8 +312,6 @@ impl Floodsub { self.connected_peers.insert(peer_id, SmallVec::new()); } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index 4ed55bb890f..e8d126ac9ae 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -3031,8 +3031,6 @@ where Ok(rpc_list) } - /// Called on the [`FromSwarm::ConnectionEstablished`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, ConnectionEstablished { @@ -3122,8 +3120,6 @@ where } } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { @@ -3258,8 +3254,6 @@ where } } - /// Called on the [`FromSwarm::AddressChange`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_address_change( &mut self, AddressChange { diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index fa3cdebeb6c..ca3f4d93887 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -207,8 +207,6 @@ impl Behaviour { } } - /// Called on the [`FromSwarm::ConnectionEstablished`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, ConnectionEstablished { diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index 53266414c5e..de15c349ac3 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -1774,8 +1774,6 @@ where } } - /// Called on the [`FromSwarm::ConnectionEstablished`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, ConnectionEstablished { @@ -1817,8 +1815,6 @@ where } } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { @@ -1836,8 +1832,6 @@ where } } - /// Called on the [`FromSwarm::DialFailure`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_dial_failure( &mut self, DialFailure { peer_id, error, .. }: DialFailure< @@ -1882,8 +1876,6 @@ where } } - /// Called on the [`FromSwarm::AddressChange`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_address_change( &mut self, AddressChange { diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index f883a90e8af..65b585692e4 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -114,8 +114,6 @@ impl Client { (transport, behaviour) } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index 5f19a47db78..4d1eebb3075 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -214,8 +214,6 @@ impl Relay { } } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index 20afd6f8019..00d14381204 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -560,8 +560,6 @@ where .and_then(|connections| connections.iter_mut().find(|c| c.id == connection)) } - /// Called on the [`FromSwarm::ConnectionEstablished`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, ConnectionEstablished { @@ -591,8 +589,6 @@ where } } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { @@ -641,8 +637,6 @@ where } } - /// Called on the [`FromSwarm::AddressChange`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_address_change( &mut self, AddressChange { @@ -668,8 +662,6 @@ where connection.address = new_address; } - /// Called on the [`FromSwarm::DialFailure`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_dial_failure( &mut self, DialFailure { peer_id, .. }: DialFailure<::ConnectionHandler>, diff --git a/swarm/src/test.rs b/swarm/src/test.rs index eea3d4cf551..fa6a3ed533b 100644 --- a/swarm/src/test.rs +++ b/swarm/src/test.rs @@ -221,8 +221,6 @@ where false } - /// Called on the [`FromSwarm::ConnectionEstablished`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_established( &mut self, ConnectionEstablished { @@ -277,8 +275,6 @@ where ); } - /// Called on the [`FromSwarm::ConnectionClosed`] - /// [event](`NetworkBehaviour::on_swarm_event`). fn on_connection_closed( &mut self, ConnectionClosed { From 1a2aaebe768de772a2e05953bfaeaf0400978c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 19 Oct 2022 18:43:53 +0100 Subject: [PATCH 36/60] review: address Thomas reviews --- protocols/autonat/Cargo.toml | 2 +- protocols/autonat/src/behaviour.rs | 44 ++++++++++-------------------- protocols/kad/src/behaviour.rs | 10 +++---- swarm/src/behaviour.rs | 10 +++++++ 4 files changed, 31 insertions(+), 35 deletions(-) diff --git a/protocols/autonat/Cargo.toml b/protocols/autonat/Cargo.toml index c3b88583839..13ad3a0a2c7 100644 --- a/protocols/autonat/Cargo.toml +++ b/protocols/autonat/Cargo.toml @@ -19,7 +19,7 @@ futures = "0.3" futures-timer = "3.0" instant = "0.1" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } libp2p-request-response = { version = "0.22.0", path = "../request-response" } log = "0.4" rand = "0.8" diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index 929bca5e610..b0d78852274 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -306,23 +306,13 @@ impl Behaviour { fn on_connection_established( &mut self, ConnectionEstablished { - peer_id, - connection_id, + peer_id: peer, + connection_id: conn, endpoint, - failed_addresses, - other_established, + .. }: ConnectionEstablished, ) { - self.inner - .on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { - peer_id, - connection_id, - endpoint, - failed_addresses, - other_established, - })); - - let connections = self.connected.entry(peer_id).or_default(); + let connections = self.connected.entry(peer).or_default(); let addr = endpoint.get_remote_address(); let observed_addr = if !endpoint.is_relayed() && (!self.config.only_global_ips || addr.is_global_ip()) { @@ -330,14 +320,14 @@ impl Behaviour { } else { None }; - connections.insert(connection_id, observed_addr); + connections.insert(conn, observed_addr); match endpoint { ConnectedPoint::Dialer { address, role_override: Endpoint::Dialer, } => { - if let Some(event) = self.as_server().on_outbound_connection(&peer_id, address) { + if let Some(event) = self.as_server().on_outbound_connection(&peer, address) { self.pending_out_events .push_back(Event::InboundProbe(event)); } @@ -407,26 +397,18 @@ impl Behaviour { fn on_address_change( &mut self, AddressChange { - peer_id, - connection_id, + peer_id: peer, + connection_id: conn, old, new, }: AddressChange, ) { - self.inner - .on_swarm_event(FromSwarm::AddressChange(AddressChange { - peer_id, - connection_id, - old, - new, - })); - if old.is_relayed() && new.is_relayed() { return; } let connections = self .connected - .get_mut(&peer_id) + .get_mut(&peer) .expect("Peer is connected."); let addr = new.get_remote_address(); let observed_addr = @@ -435,7 +417,7 @@ impl Behaviour { } else { None }; - connections.insert(connection_id, observed_addr); + connections.insert(conn, observed_addr); } } @@ -499,13 +481,17 @@ impl NetworkBehaviour for Behaviour { fn on_swarm_event(&mut self, event: FromSwarm) { match event { FromSwarm::ConnectionEstablished(connection_established) => { + self.inner.on_swarm_event(FromSwarm::ConnectionEstablished(connection_established)); self.on_connection_established(connection_established) } FromSwarm::ConnectionClosed(connection_closed) => { self.on_connection_closed(connection_closed) } FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), - FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), + FromSwarm::AddressChange(address_change) => { + self.inner.on_swarm_event(FromSwarm::AddressChange(address_change)); + self.on_address_change(address_change) + }, listen_addr @ FromSwarm::NewListenAddr(_) => { self.inner.on_swarm_event(listen_addr); self.as_client().on_new_address(); diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index de15c349ac3..8c55694cf76 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -1979,7 +1979,7 @@ where fn on_connection_handler_event( &mut self, source: PeerId, - connection_id: ConnectionId, + connection: ConnectionId, event: KademliaHandlerEvent, ) { match event { @@ -2011,7 +2011,7 @@ where self.queued_events .push_back(NetworkBehaviourAction::NotifyHandler { peer_id: source, - handler: NotifyHandler::One(connection_id), + handler: NotifyHandler::One(connection), event: KademliaHandlerIn::FindNodeRes { closer_peers, request_id, @@ -2043,7 +2043,7 @@ where self.queued_events .push_back(NetworkBehaviourAction::NotifyHandler { peer_id: source, - handler: NotifyHandler::One(connection_id), + handler: NotifyHandler::One(connection), event: KademliaHandlerIn::GetProvidersRes { closer_peers, provider_peers, @@ -2120,7 +2120,7 @@ where self.queued_events .push_back(NetworkBehaviourAction::NotifyHandler { peer_id: source, - handler: NotifyHandler::One(connection_id), + handler: NotifyHandler::One(connection), event: KademliaHandlerIn::GetRecordRes { record, closer_peers, @@ -2192,7 +2192,7 @@ where } KademliaHandlerEvent::PutRecord { record, request_id } => { - self.record_received(source, connection_id, request_id, record); + self.record_received(source, connection, request_id, record); } KademliaHandlerEvent::PutRecordRes { user_data, .. } => { diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index cc0b7f6abac..3d514b7424d 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -916,6 +916,7 @@ pub struct ConnectionClosed<'a, Handler: IntoConnectionHandler> { /// [`FromSwarm`] variant that informs the behaviour that the [`ConnectedPoint`] of an existing /// connection has changed. +#[derive(Clone, Copy)] pub struct AddressChange<'a> { pub peer_id: PeerId, pub connection_id: ConnectionId, @@ -925,6 +926,7 @@ pub struct AddressChange<'a> { /// [`FromSwarm`] variant that informs the behaviour that the dial to a known /// or unknown node failed. +#[derive(Clone, Copy)] pub struct DialFailure<'a, Handler> { pub peer_id: Option, pub handler: Handler, @@ -936,6 +938,7 @@ pub struct DialFailure<'a, Handler> { /// /// This can include, for example, an error during the handshake of the encryption layer, or the /// connection unexpectedly closed. +#[derive(Clone, Copy)] pub struct ListenFailure<'a, Handler> { pub local_addr: &'a Multiaddr, pub send_back_addr: &'a Multiaddr, @@ -943,12 +946,14 @@ pub struct ListenFailure<'a, Handler> { } /// [`FromSwarm`] variant that informs the behaviour that a new listener was created. +#[derive(Clone, Copy)] pub struct NewListener { pub listener_id: ListenerId, } /// [`FromSwarm`] variant that informs the behaviour /// that we have started listening on a new multiaddr. +#[derive(Clone, Copy)] pub struct NewListenAddr<'a> { pub listener_id: ListenerId, pub addr: &'a Multiaddr, @@ -957,18 +962,21 @@ pub struct NewListenAddr<'a> { /// [`FromSwarm`] variant that informs the behaviour that a multiaddr /// we were listening on has expired, /// which means that we are no longer listening on it. +#[derive(Clone, Copy)] pub struct ExpiredListenAddr<'a> { pub listener_id: ListenerId, pub addr: &'a Multiaddr, } /// [`FromSwarm`] variant that informs the behaviour that a listener experienced an error. +#[derive(Clone, Copy)] pub struct ListenerError<'a> { pub listener_id: ListenerId, pub err: &'a (dyn std::error::Error + 'static), } /// [`FromSwarm`] variant that informs the behaviour that a listener closed. +#[derive(Clone, Copy)] pub struct ListenerClosed<'a> { pub listener_id: ListenerId, pub reason: Result<(), &'a std::io::Error>, @@ -976,11 +984,13 @@ pub struct ListenerClosed<'a> { /// [`FromSwarm`] variant that informs the behaviour /// that we have discovered a new external address for us. +#[derive(Clone, Copy)] pub struct NewExternalAddr<'a> { pub addr: &'a Multiaddr, } /// [`FromSwarm`] variant that informs the behaviour that an external address was removed. +#[derive(Clone, Copy)] pub struct ExpiredExternalAddr<'a> { pub addr: &'a Multiaddr, } From 2e58d654caef2e550abf9d07568fff2cef83b959 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 19 Oct 2022 21:39:31 +0100 Subject: [PATCH 37/60] review: cargo fmt --- protocols/autonat/src/behaviour.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index b0d78852274..cc0adc51c02 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -406,10 +406,7 @@ impl Behaviour { if old.is_relayed() && new.is_relayed() { return; } - let connections = self - .connected - .get_mut(&peer) - .expect("Peer is connected."); + let connections = self.connected.get_mut(&peer).expect("Peer is connected."); let addr = new.get_remote_address(); let observed_addr = if !new.is_relayed() && (!self.config.only_global_ips || addr.is_global_ip()) { @@ -481,7 +478,8 @@ impl NetworkBehaviour for Behaviour { fn on_swarm_event(&mut self, event: FromSwarm) { match event { FromSwarm::ConnectionEstablished(connection_established) => { - self.inner.on_swarm_event(FromSwarm::ConnectionEstablished(connection_established)); + self.inner + .on_swarm_event(FromSwarm::ConnectionEstablished(connection_established)); self.on_connection_established(connection_established) } FromSwarm::ConnectionClosed(connection_closed) => { @@ -489,9 +487,10 @@ impl NetworkBehaviour for Behaviour { } FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), FromSwarm::AddressChange(address_change) => { - self.inner.on_swarm_event(FromSwarm::AddressChange(address_change)); + self.inner + .on_swarm_event(FromSwarm::AddressChange(address_change)); self.on_address_change(address_change) - }, + } listen_addr @ FromSwarm::NewListenAddr(_) => { self.inner.on_swarm_event(listen_addr); self.as_client().on_new_address(); From 9c527042045077d983809d23fde3d4b3488d04fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 20 Oct 2022 11:44:47 +0100 Subject: [PATCH 38/60] review: Update CHANGELOG links to proper ones. --- protocols/autonat/CHANGELOG.md | 4 +++- protocols/dcutr/CHANGELOG.md | 4 +++- protocols/floodsub/CHANGELOG.md | 4 +++- protocols/gossipsub/CHANGELOG.md | 4 +++- protocols/identify/CHANGELOG.md | 4 +++- protocols/kad/CHANGELOG.md | 4 +++- protocols/mdns/CHANGELOG.md | 4 +++- protocols/ping/CHANGELOG.md | 4 +++- protocols/relay/CHANGELOG.md | 4 +++- protocols/rendezvous/CHANGELOG.md | 4 +++- protocols/request-response/CHANGELOG.md | 4 +++- swarm/CHANGELOG.md | 6 ++++-- 12 files changed, 37 insertions(+), 13 deletions(-) diff --git a/protocols/autonat/CHANGELOG.md b/protocols/autonat/CHANGELOG.md index 7a62b01aa74..6d0dad33bf4 100644 --- a/protocols/autonat/CHANGELOG.md +++ b/protocols/autonat/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.8.1 - [unreleased] - Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.8.0 diff --git a/protocols/dcutr/CHANGELOG.md b/protocols/dcutr/CHANGELOG.md index 812a8eb0689..47ad734a026 100644 --- a/protocols/dcutr/CHANGELOG.md +++ b/protocols/dcutr/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.7.1 - [unreleased] - Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.7.0 diff --git a/protocols/floodsub/CHANGELOG.md b/protocols/floodsub/CHANGELOG.md index 38f642deac8..977d1934159 100644 --- a/protocols/floodsub/CHANGELOG.md +++ b/protocols/floodsub/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.40.1 - [unreleased] - Replace `Floodsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.40.0 diff --git a/protocols/gossipsub/CHANGELOG.md b/protocols/gossipsub/CHANGELOG.md index 453f9c5d720..30dd5e1dd9a 100644 --- a/protocols/gossipsub/CHANGELOG.md +++ b/protocols/gossipsub/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.42.1 - [unreleased] - Replace `Gossipsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.42.0 diff --git a/protocols/identify/CHANGELOG.md b/protocols/identify/CHANGELOG.md index 8f3dc1ca795..343b2a585d5 100644 --- a/protocols/identify/CHANGELOG.md +++ b/protocols/identify/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.40.1 - [unreleased] - Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.40.0 diff --git a/protocols/kad/CHANGELOG.md b/protocols/kad/CHANGELOG.md index 06cfe90afa5..9617085ff5f 100644 --- a/protocols/kad/CHANGELOG.md +++ b/protocols/kad/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.41.1 - [unreleased] - Replace `Kademlia`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.41.0 diff --git a/protocols/mdns/CHANGELOG.md b/protocols/mdns/CHANGELOG.md index 4c1f2f90224..37eb8178f19 100644 --- a/protocols/mdns/CHANGELOG.md +++ b/protocols/mdns/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.41.1 - [unreleased] - Replace `GenMdns`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.41.0 diff --git a/protocols/ping/CHANGELOG.md b/protocols/ping/CHANGELOG.md index e4ddb5fcc6e..e25e47b1deb 100644 --- a/protocols/ping/CHANGELOG.md +++ b/protocols/ping/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.40.1 - [unreleased] - Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.40.0 diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index db274592dd6..90b740237a8 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.13.1 - [unreleased] - Replace `Client` and `Relay`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.13.0 diff --git a/protocols/rendezvous/CHANGELOG.md b/protocols/rendezvous/CHANGELOG.md index ea5157a5856..99411035a57 100644 --- a/protocols/rendezvous/CHANGELOG.md +++ b/protocols/rendezvous/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.10.1 - [unreleased] - Replace `Client` and `Server`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.10.0 diff --git a/protocols/request-response/CHANGELOG.md b/protocols/request-response/CHANGELOG.md index f9c0cb47cb3..4ea95a668dc 100644 --- a/protocols/request-response/CHANGELOG.md +++ b/protocols/request-response/CHANGELOG.md @@ -1,7 +1,9 @@ # 0.22.1 - [unreleased] - Replace `RequestResponse`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.22.0 diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 797fbad81d6..c64bf2cda2a 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -2,11 +2,13 @@ - Add new `on_swarm_event` method to `NetworkBehaviour` that accepts a `FromSwarm` enum and update `inject_*` methods to call `on_swarm_event` with the respective `FromSwarm` variant and deprecate - them. See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + them. See [PR 3011]. - Add new `on_connection_handler_event` method with the same signature as `inject_event`, make the default implementation of `inject_event` call `on_connection_handler_event` and deprecate it. - See [PR 3011](https://github.com/libp2p/rust-libp2p/pull/3011). + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 # 0.40.0 From f9037a2fee4cfaeddd26fa47df8b0df3604b556e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 20 Oct 2022 12:42:18 +0100 Subject: [PATCH 39/60] review update swarm dependency on protocols --- protocols/dcutr/Cargo.toml | 2 +- protocols/floodsub/Cargo.toml | 2 +- protocols/gossipsub/Cargo.toml | 2 +- protocols/identify/Cargo.toml | 2 +- protocols/kad/Cargo.toml | 2 +- protocols/mdns/Cargo.toml | 2 +- protocols/ping/Cargo.toml | 2 +- protocols/relay/Cargo.toml | 2 +- protocols/rendezvous/Cargo.toml | 2 +- protocols/request-response/Cargo.toml | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/protocols/dcutr/Cargo.toml b/protocols/dcutr/Cargo.toml index d9cc5861bc5..c9546dfd99a 100644 --- a/protocols/dcutr/Cargo.toml +++ b/protocols/dcutr/Cargo.toml @@ -18,7 +18,7 @@ futures = "0.3.1" futures-timer = "3.0" instant = "0.1.11" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } log = "0.4" prost-codec = { version = "0.2", path = "../../misc/prost-codec" } prost = "0.11" diff --git a/protocols/floodsub/Cargo.toml b/protocols/floodsub/Cargo.toml index f030e7477d9..4eb6359b955 100644 --- a/protocols/floodsub/Cargo.toml +++ b/protocols/floodsub/Cargo.toml @@ -15,7 +15,7 @@ cuckoofilter = "0.5.0" fnv = "1.0" futures = "0.3.1" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } log = "0.4" prost = "0.11" rand = "0.8" diff --git a/protocols/gossipsub/Cargo.toml b/protocols/gossipsub/Cargo.toml index 00778ef0688..992b7791c62 100644 --- a/protocols/gossipsub/Cargo.toml +++ b/protocols/gossipsub/Cargo.toml @@ -11,7 +11,7 @@ keywords = ["peer-to-peer", "libp2p", "networking"] categories = ["network-programming", "asynchronous"] [dependencies] -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } libp2p-core = { version = "0.37.0", path = "../../core" } bytes = "1.0" byteorder = "1.3.4" diff --git a/protocols/identify/Cargo.toml b/protocols/identify/Cargo.toml index c24c2e8a9c6..bf0abb197ad 100644 --- a/protocols/identify/Cargo.toml +++ b/protocols/identify/Cargo.toml @@ -15,7 +15,7 @@ asynchronous-codec = "0.6" futures = "0.3.1" futures-timer = "3.0.2" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } log = "0.4.1" lru = "0.8.0" prost-codec = { version = "0.2", path = "../../misc/prost-codec" } diff --git a/protocols/kad/Cargo.toml b/protocols/kad/Cargo.toml index e97394b7071..81309d2d9c4 100644 --- a/protocols/kad/Cargo.toml +++ b/protocols/kad/Cargo.toml @@ -19,7 +19,7 @@ asynchronous-codec = "0.6" futures = "0.3.1" log = "0.4" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } prost = "0.11" rand = "0.8" sha2 = "0.10.0" diff --git a/protocols/mdns/Cargo.toml b/protocols/mdns/Cargo.toml index 2663c76f820..e980a33cb96 100644 --- a/protocols/mdns/Cargo.toml +++ b/protocols/mdns/Cargo.toml @@ -16,7 +16,7 @@ dns-parser = "0.8.0" futures = "0.3.13" if-watch = "2.0.0" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } log = "0.4.14" rand = "0.8.3" smallvec = "1.6.1" diff --git a/protocols/ping/Cargo.toml b/protocols/ping/Cargo.toml index 70e03164318..f4d48f0c7fd 100644 --- a/protocols/ping/Cargo.toml +++ b/protocols/ping/Cargo.toml @@ -15,7 +15,7 @@ futures = "0.3.1" futures-timer = "3.0.2" instant = "0.1.11" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } log = "0.4.1" rand = "0.8" void = "1.0" diff --git a/protocols/relay/Cargo.toml b/protocols/relay/Cargo.toml index 19837380355..d0b7f2f28dd 100644 --- a/protocols/relay/Cargo.toml +++ b/protocols/relay/Cargo.toml @@ -18,7 +18,7 @@ futures = "0.3.1" futures-timer = "3" instant = "0.1.11" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } log = "0.4" pin-project = "1" prost-codec = { version = "0.2", path = "../../misc/prost-codec" } diff --git a/protocols/rendezvous/Cargo.toml b/protocols/rendezvous/Cargo.toml index fc25965bccd..4c6bc304144 100644 --- a/protocols/rendezvous/Cargo.toml +++ b/protocols/rendezvous/Cargo.toml @@ -13,7 +13,7 @@ categories = ["network-programming", "asynchronous"] [dependencies] asynchronous-codec = "0.6" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } prost = "0.11" void = "1" log = "0.4" diff --git a/protocols/request-response/Cargo.toml b/protocols/request-response/Cargo.toml index 53e0b756392..198a62817e8 100644 --- a/protocols/request-response/Cargo.toml +++ b/protocols/request-response/Cargo.toml @@ -16,7 +16,7 @@ bytes = "1" futures = "0.3.1" instant = "0.1.11" libp2p-core = { version = "0.37.0", path = "../../core" } -libp2p-swarm = { version = "0.40.0", path = "../../swarm" } +libp2p-swarm = { version = "0.40.1", path = "../../swarm" } log = "0.4.11" rand = "0.8" smallvec = "1.6.1" From 0c27ea6b66f3488309283d7632595b903eb3420e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 20 Oct 2022 12:42:57 +0100 Subject: [PATCH 40/60] review: address Thomas review comments --- protocols/dcutr/src/behaviour.rs | 52 +++++++++++++-------------- protocols/identify/src/behaviour.rs | 4 +-- protocols/request-response/src/lib.rs | 50 +++++++++++++------------- 3 files changed, 51 insertions(+), 55 deletions(-) diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 78f005e64a4..5f72e964071 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -129,30 +129,6 @@ impl Behaviour { } } - fn on_connection_closed( - &mut self, - ConnectionClosed { - peer_id, - connection_id, - endpoint, - .. - }: ConnectionClosed<::ConnectionHandler>, - ) { - if !endpoint.is_relayed() { - let connections = self - .direct_connections - .get_mut(&peer_id) - .expect("Peer of direct connection to be tracked."); - connections - .remove(&connection_id) - .then(|| ()) - .expect("Direct connection to be tracked."); - if connections.is_empty() { - self.direct_connections.remove(&peer_id); - } - } - } - fn on_dial_failure( &mut self, DialFailure { @@ -190,6 +166,30 @@ impl Behaviour { } } } + + fn on_connection_closed( + &mut self, + ConnectionClosed { + peer_id, + connection_id, + endpoint, + .. + }: ConnectionClosed<::ConnectionHandler>, + ) { + if !endpoint.is_relayed() { + let connections = self + .direct_connections + .get_mut(&peer_id) + .expect("Peer of direct connection to be tracked."); + connections + .remove(&connection_id) + .then(|| ()) + .expect("Direct connection to be tracked."); + if connections.is_empty() { + self.direct_connections.remove(&peer_id); + } + } + } } impl NetworkBehaviour for Behaviour { @@ -200,10 +200,6 @@ impl NetworkBehaviour for Behaviour { handler::Prototype::UnknownConnection } - fn addresses_of_peer(&mut self, _peer_id: &PeerId) -> Vec { - vec![] - } - fn on_connection_handler_event( &mut self, event_source: PeerId, diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index ca3f4d93887..c1c2737e143 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -211,7 +211,7 @@ impl Behaviour { &mut self, ConnectionEstablished { peer_id, - connection_id, + connection_id: conn, endpoint, failed_addresses, .. @@ -225,7 +225,7 @@ impl Behaviour { self.connected .entry(peer_id) .or_default() - .insert(connection_id, addr); + .insert(conn, addr); if let Some(entry) = self.discovered_peers.get_mut(&peer_id) { for addr in failed_addresses { diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index 00d14381204..53c3e059370 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -560,6 +560,31 @@ where .and_then(|connections| connections.iter_mut().find(|c| c.id == connection)) } + fn on_address_change( + &mut self, + AddressChange { + peer_id, + connection_id, + new, + .. + }: AddressChange, + ) { + let new_address = match new { + ConnectedPoint::Dialer { address, .. } => Some(address.clone()), + ConnectedPoint::Listener { .. } => None, + }; + let connections = self + .connected + .get_mut(&peer_id) + .expect("Address change can only happen on an established connection."); + + let connection = connections + .iter_mut() + .find(|c| c.id == connection_id) + .expect("Address change can only happen on an established connection."); + connection.address = new_address; + } + fn on_connection_established( &mut self, ConnectionEstablished { @@ -637,31 +662,6 @@ where } } - fn on_address_change( - &mut self, - AddressChange { - peer_id, - connection_id, - new, - .. - }: AddressChange, - ) { - let new_address = match new { - ConnectedPoint::Dialer { address, .. } => Some(address.clone()), - ConnectedPoint::Listener { .. } => None, - }; - let connections = self - .connected - .get_mut(&peer_id) - .expect("Address change can only happen on an established connection."); - - let connection = connections - .iter_mut() - .find(|c| c.id == connection_id) - .expect("Address change can only happen on an established connection."); - connection.address = new_address; - } - fn on_dial_failure( &mut self, DialFailure { peer_id, .. }: DialFailure<::ConnectionHandler>, From 632bad4e8dfdf7029f00b53a3d6d1cedec83c083 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 20 Oct 2022 13:44:51 +0100 Subject: [PATCH 41/60] review: minimize diff changes, by maintaining the same var names --- protocols/request-response/src/lib.rs | 55 +++++++++------------------ 1 file changed, 19 insertions(+), 36 deletions(-) diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index 53c3e059370..64d50a37927 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -717,10 +717,7 @@ where addresses } - fn on_swarm_event( - &mut self, - event: libp2p_swarm::behaviour::FromSwarm, - ) { + fn on_swarm_event(&mut self, event: FromSwarm) { match event { FromSwarm::ConnectionEstablished(connection_established) => { self.on_connection_established(connection_established) @@ -736,8 +733,8 @@ where fn on_connection_handler_event( &mut self, - peer_id: PeerId, - connection_id: ConnectionId, + peer: PeerId, + connection: ConnectionId, event: <::Handler as libp2p_swarm::ConnectionHandler>::OutEvent, ) { @@ -746,8 +743,7 @@ where request_id, response, } => { - let removed = - self.remove_pending_inbound_response(&peer_id, connection_id, &request_id); + let removed = self.remove_pending_inbound_response(&peer, connection, &request_id); debug_assert!( removed, "Expect request_id to be pending before receiving response.", @@ -759,10 +755,7 @@ where }; self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( - RequestResponseEvent::Message { - peer: peer_id, - message, - }, + RequestResponseEvent::Message { peer, message }, )); } RequestResponseHandlerEvent::Request { @@ -778,13 +771,10 @@ where }; self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( - RequestResponseEvent::Message { - peer: peer_id, - message, - }, + RequestResponseEvent::Message { peer, message }, )); - match self.get_connection_mut(&peer_id, connection_id) { + match self.get_connection_mut(&peer, connection) { Some(connection) => { let inserted = connection.pending_outbound_responses.insert(request_id); debug_assert!(inserted, "Expect id of new request to be unknown."); @@ -794,7 +784,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer: peer_id, + peer, request_id, error: InboundFailure::ConnectionClosed, }, @@ -803,8 +793,7 @@ where } } RequestResponseHandlerEvent::ResponseSent(request_id) => { - let removed = - self.remove_pending_outbound_response(&peer_id, connection_id, request_id); + let removed = self.remove_pending_outbound_response(&peer, connection, request_id); debug_assert!( removed, "Expect request_id to be pending before response is sent." @@ -812,15 +801,11 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( - RequestResponseEvent::ResponseSent { - peer: peer_id, - request_id, - }, + RequestResponseEvent::ResponseSent { peer, request_id }, )); } RequestResponseHandlerEvent::ResponseOmission(request_id) => { - let removed = - self.remove_pending_outbound_response(&peer_id, connection_id, request_id); + let removed = self.remove_pending_outbound_response(&peer, connection, request_id); debug_assert!( removed, "Expect request_id to be pending before response is omitted.", @@ -829,15 +814,14 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer: peer_id, + peer, request_id, error: InboundFailure::ResponseOmission, }, )); } RequestResponseHandlerEvent::OutboundTimeout(request_id) => { - let removed = - self.remove_pending_inbound_response(&peer_id, connection_id, &request_id); + let removed = self.remove_pending_inbound_response(&peer, connection, &request_id); debug_assert!( removed, "Expect request_id to be pending before request times out." @@ -846,7 +830,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::OutboundFailure { - peer: peer_id, + peer, request_id, error: OutboundFailure::Timeout, }, @@ -857,20 +841,19 @@ where // out to receive the request and for timing out sending the response. In the former // case the request is never added to `pending_outbound_responses` and thus one can // not assert the request_id to be present before removing it. - self.remove_pending_outbound_response(&peer_id, connection_id, request_id); + self.remove_pending_outbound_response(&peer, connection, request_id); self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer: peer_id, + peer, request_id, error: InboundFailure::Timeout, }, )); } RequestResponseHandlerEvent::OutboundUnsupportedProtocols(request_id) => { - let removed = - self.remove_pending_inbound_response(&peer_id, connection_id, &request_id); + let removed = self.remove_pending_inbound_response(&peer, connection, &request_id); debug_assert!( removed, "Expect request_id to be pending before failing to connect.", @@ -879,7 +862,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::OutboundFailure { - peer: peer_id, + peer, request_id, error: OutboundFailure::UnsupportedProtocols, }, @@ -892,7 +875,7 @@ where self.pending_events .push_back(NetworkBehaviourAction::GenerateEvent( RequestResponseEvent::InboundFailure { - peer: peer_id, + peer, request_id, error: InboundFailure::UnsupportedProtocols, }, From 59f9c5696127912115b4b385c80f1577bc84e4c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 20 Oct 2022 21:01:18 +0100 Subject: [PATCH 42/60] review: update protocol crates versions, to match latest CHANGELOG version entry. --- protocols/autonat/Cargo.toml | 2 +- protocols/dcutr/Cargo.toml | 2 +- protocols/identify/Cargo.toml | 2 +- protocols/kad/Cargo.toml | 2 +- protocols/mdns/Cargo.toml | 2 +- protocols/relay/Cargo.toml | 2 +- protocols/rendezvous/Cargo.toml | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/protocols/autonat/Cargo.toml b/protocols/autonat/Cargo.toml index 13ad3a0a2c7..aa6bc05e978 100644 --- a/protocols/autonat/Cargo.toml +++ b/protocols/autonat/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-autonat" edition = "2021" rust-version = "1.56.1" description = "NAT and firewall detection for libp2p" -version = "0.8.0" +version = "0.8.1" authors = ["David Craven ", "Elena Frank "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/protocols/dcutr/Cargo.toml b/protocols/dcutr/Cargo.toml index c9546dfd99a..1bcffe0523f 100644 --- a/protocols/dcutr/Cargo.toml +++ b/protocols/dcutr/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-dcutr" edition = "2021" rust-version = "1.56.1" description = "Direct connection upgrade through relay" -version = "0.7.0" +version = "0.7.1" authors = ["Max Inden "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/protocols/identify/Cargo.toml b/protocols/identify/Cargo.toml index bf0abb197ad..2c3d99368bd 100644 --- a/protocols/identify/Cargo.toml +++ b/protocols/identify/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-identify" edition = "2021" rust-version = "1.56.1" description = "Nodes identifcation protocol for libp2p" -version = "0.40.0" +version = "0.40.1" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/protocols/kad/Cargo.toml b/protocols/kad/Cargo.toml index 81309d2d9c4..9b34a84e70f 100644 --- a/protocols/kad/Cargo.toml +++ b/protocols/kad/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-kad" edition = "2021" rust-version = "1.56.1" description = "Kademlia protocol for libp2p" -version = "0.41.0" +version = "0.41.1" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/protocols/mdns/Cargo.toml b/protocols/mdns/Cargo.toml index e980a33cb96..5b15c635a0b 100644 --- a/protocols/mdns/Cargo.toml +++ b/protocols/mdns/Cargo.toml @@ -2,7 +2,7 @@ name = "libp2p-mdns" edition = "2021" rust-version = "1.56.1" -version = "0.41.0" +version = "0.41.1" description = "Implementation of the libp2p mDNS discovery method" authors = ["Parity Technologies "] license = "MIT" diff --git a/protocols/relay/Cargo.toml b/protocols/relay/Cargo.toml index d0b7f2f28dd..b6969d69aba 100644 --- a/protocols/relay/Cargo.toml +++ b/protocols/relay/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-relay" edition = "2021" rust-version = "1.56.1" description = "Communications relaying for libp2p" -version = "0.13.0" +version = "0.13.1" authors = ["Parity Technologies ", "Max Inden "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/protocols/rendezvous/Cargo.toml b/protocols/rendezvous/Cargo.toml index 4c6bc304144..ad3832d6c34 100644 --- a/protocols/rendezvous/Cargo.toml +++ b/protocols/rendezvous/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-rendezvous" edition = "2021" rust-version = "1.56.1" description = "Rendezvous protocol for libp2p" -version = "0.10.0" +version = "0.10.1" authors = ["The COMIT guys "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" From d095dc4648dee8ab54d34296d4b3c88f73d7556f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 20 Oct 2022 21:02:14 +0100 Subject: [PATCH 43/60] review: address Max's review comments --- swarm/CHANGELOG.md | 6 +++++- swarm/tests/public_api.rs | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index c64bf2cda2a..4c066de2236 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -2,7 +2,11 @@ - Add new `on_swarm_event` method to `NetworkBehaviour` that accepts a `FromSwarm` enum and update `inject_*` methods to call `on_swarm_event` with the respective `FromSwarm` variant and deprecate - them. See [PR 3011]. + them. + To migrate, users should replace the `NetworkBehaviour::inject_*` calls with a single + implementation of `NetworkBehaviour::on_swarm_event` treating each `FromSwarm` variant in + the same way its corresponding `inject_*` call was treated. + See [PR 3011]. - Add new `on_connection_handler_event` method with the same signature as `inject_event`, make the default implementation of `inject_event` call `on_connection_handler_event` and deprecate it. diff --git a/swarm/tests/public_api.rs b/swarm/tests/public_api.rs index 5ebaffeb5cf..ab4298bcccb 100644 --- a/swarm/tests/public_api.rs +++ b/swarm/tests/public_api.rs @@ -7,9 +7,9 @@ use libp2p_swarm::behaviour::{ NewListenAddr, NewListener, }; +// Test to break compilation everytime a variant changes, +// forcing us to revisit each implementation. #[test] -// test to break compilation everytime a variant changes, -// forcing us to revisit each implementation fn swarm_event_variants() { let event: FromSwarm<'_, dummy::ConnectionHandler> = FromSwarm::ListenerClosed(libp2p_swarm::behaviour::ListenerClosed { From e9bf9c50f85151221fc2bfd4d5913032d5005a53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 21 Oct 2022 16:18:58 +0100 Subject: [PATCH 44/60] review: update FromSwarm matching cases, to be exhaustive. --- protocols/dcutr/src/behaviour.rs | 10 +++++++++- protocols/floodsub/src/layer.rs | 11 ++++++++++- protocols/gossipsub/src/behaviour.rs | 10 +++++++++- protocols/identify/src/behaviour.rs | 8 +++++++- protocols/kad/src/behaviour.rs | 6 +++++- protocols/mdns/src/behaviour.rs | 11 ++++++++++- protocols/relay/src/v2/client.rs | 11 ++++++++++- protocols/relay/src/v2/relay.rs | 17 +++++++++++++++-- protocols/request-response/src/lib.rs | 9 ++++++++- 9 files changed, 83 insertions(+), 10 deletions(-) diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 5f72e964071..91fba987348 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -326,7 +326,15 @@ impl NetworkBehaviour for Behaviour { self.on_connection_closed(connection_closed) } FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), - _ => {} + FromSwarm::AddressChange(_) => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::NewListenAddr(_) => {} + FromSwarm::ExpiredListenAddr(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index de0a0711f0a..0ee12ce166a 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -488,7 +488,16 @@ impl NetworkBehaviour for Floodsub { FromSwarm::ConnectionClosed(connection_closed) => { self.on_connection_closed(connection_closed) } - _ => {} + FromSwarm::AddressChange(_) => {} + FromSwarm::DialFailure(_) => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::NewListenAddr(_) => {} + FromSwarm::ExpiredListenAddr(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index e8d126ac9ae..88606037dd2 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -3475,7 +3475,15 @@ where self.on_connection_closed(connection_closed) } FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), - _ => {} + FromSwarm::DialFailure(_) => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::NewListenAddr(_) => {} + FromSwarm::ExpiredListenAddr(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index c1c2737e143..c9ffa693ecc 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -447,7 +447,13 @@ impl NetworkBehaviour for Behaviour { self.pending_push.extend(self.connected.keys()); } } - _ => {} + FromSwarm::AddressChange(_) => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index 8c55694cf76..b6eed03db22 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -2370,7 +2370,11 @@ where FromSwarm::NewListenAddr(NewListenAddr { addr, .. }) => { self.local_addrs.insert(addr.clone()); } - _ => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index 2c28b27a0e4..4443458d917 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -159,7 +159,16 @@ where iface.fire_timer(); } } - _ => {} + FromSwarm::ConnectionEstablished(_) => {} + FromSwarm::DialFailure(_) => {} + FromSwarm::AddressChange(_) => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListenAddr(_) => {} + FromSwarm::ExpiredListenAddr(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index 65b585692e4..bc339ee9e68 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -171,7 +171,16 @@ impl NetworkBehaviour for Client { FromSwarm::ConnectionClosed(connection_closed) => { self.on_connection_closed(connection_closed) } - _ => {} + FromSwarm::AddressChange(_) => {} + FromSwarm::DialFailure(_) => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::NewListenAddr(_) => {} + FromSwarm::ExpiredListenAddr(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index 4d1eebb3075..02dc0cd9972 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -263,8 +263,21 @@ impl NetworkBehaviour for Relay { } fn on_swarm_event(&mut self, event: FromSwarm) { - if let FromSwarm::ConnectionClosed(connection_closed) = event { - self.on_connection_closed(connection_closed) + match event { + FromSwarm::ConnectionClosed(connection_closed) => { + self.on_connection_closed(connection_closed) + } + FromSwarm::ConnectionEstablished(_) => {} + FromSwarm::DialFailure(_) => {} + FromSwarm::AddressChange(_) => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::NewListenAddr(_) => {} + FromSwarm::ExpiredListenAddr(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index 64d50a37927..7c3cf42c4c0 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -727,7 +727,14 @@ where } FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), - _ => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::NewListenAddr(_) => {} + FromSwarm::ExpiredListenAddr(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} } } From 52c6df1b1154b1b6a284025f70737869ac2d4283 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sun, 23 Oct 2022 11:52:06 +0100 Subject: [PATCH 45/60] review: remove no longer required swarm public_api test --- swarm/tests/public_api.rs | 70 --------------------------------------- 1 file changed, 70 deletions(-) delete mode 100644 swarm/tests/public_api.rs diff --git a/swarm/tests/public_api.rs b/swarm/tests/public_api.rs deleted file mode 100644 index ab4298bcccb..00000000000 --- a/swarm/tests/public_api.rs +++ /dev/null @@ -1,70 +0,0 @@ -use libp2p::core::transport::ListenerId; -use libp2p::swarm::behaviour::FromSwarm; -use libp2p::swarm::dummy; -use libp2p_swarm::behaviour::{ - AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr, - ExpiredListenAddr, ListenFailure, ListenerClosed, ListenerError, NewExternalAddr, - NewListenAddr, NewListener, -}; - -// Test to break compilation everytime a variant changes, -// forcing us to revisit each implementation. -#[test] -fn swarm_event_variants() { - let event: FromSwarm<'_, dummy::ConnectionHandler> = - FromSwarm::ListenerClosed(libp2p_swarm::behaviour::ListenerClosed { - listener_id: ListenerId::new(), - reason: Ok(()), - }); - match event { - FromSwarm::ConnectionEstablished(ConnectionEstablished { - peer_id: _, - connection_id: _, - endpoint: _, - failed_addresses: _, - other_established: _, - }) => {} - FromSwarm::ConnectionClosed(ConnectionClosed { - peer_id: _, - connection_id: _, - endpoint: _, - handler: _, - remaining_established: _, - }) => {} - FromSwarm::AddressChange(AddressChange { - peer_id: _, - connection_id: _, - old: _, - new: _, - }) => {} - FromSwarm::DialFailure(DialFailure { - peer_id: _, - handler: _, - error: _, - }) => {} - FromSwarm::ListenFailure(ListenFailure { - local_addr: _, - send_back_addr: _, - handler: _, - }) => {} - FromSwarm::NewListener(NewListener { listener_id: _ }) => {} - FromSwarm::NewListenAddr(NewListenAddr { - listener_id: _, - addr: _, - }) => {} - FromSwarm::ExpiredListenAddr(ExpiredListenAddr { - listener_id: _, - addr: _, - }) => {} - FromSwarm::ListenerError(ListenerError { - listener_id: _, - err: _, - }) => {} - FromSwarm::ListenerClosed(ListenerClosed { - listener_id: _, - reason: _, - }) => {} - FromSwarm::NewExternalAddr(NewExternalAddr { addr: _ }) => {} - FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr: _ }) => {} - } -} From 3300d7f5b348c04abaa5290fa04855d71c9779b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 26 Oct 2022 16:42:15 +0100 Subject: [PATCH 46/60] review: Address Max's review. --- swarm/CHANGELOG.md | 4 ++-- swarm/Cargo.toml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 4c066de2236..9a3c40ea482 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -1,8 +1,8 @@ -# 0.40.1 - [unreleased] +# 0.40.2 - [unreleased] - Add new `on_swarm_event` method to `NetworkBehaviour` that accepts a `FromSwarm` enum and update `inject_*` methods to call `on_swarm_event` with the respective `FromSwarm` variant and deprecate - them. + `inject_*`. To migrate, users should replace the `NetworkBehaviour::inject_*` calls with a single implementation of `NetworkBehaviour::on_swarm_event` treating each `FromSwarm` variant in the same way its corresponding `inject_*` call was treated. diff --git a/swarm/Cargo.toml b/swarm/Cargo.toml index adbb81cd70e..5ee726ada9c 100644 --- a/swarm/Cargo.toml +++ b/swarm/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-swarm" edition = "2021" rust-version = "1.56.1" description = "The libp2p swarm" -version = "0.40.1" +version = "0.40.2" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" From c259abc844623c90beffda4f2bb8937e084285c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 27 Oct 2022 16:26:36 +0100 Subject: [PATCH 47/60] swarm: update deprcated warnings since version --- swarm/src/behaviour.rs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 3d514b7424d..ade81298ef9 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -171,7 +171,7 @@ pub trait NetworkBehaviour: 'static { /// Informs the behaviour about a newly established connection to a peer. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::ConnectionEstablished` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_connection_established( @@ -198,7 +198,7 @@ pub trait NetworkBehaviour: 'static { /// A call to this method is always paired with an earlier call to /// [`NetworkBehaviour::inject_connection_established`] with the same peer ID, connection ID and endpoint. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::ConnectionClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_connection_closed( @@ -220,7 +220,7 @@ pub trait NetworkBehaviour: 'static { /// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::AddressChange` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_address_change( @@ -244,7 +244,7 @@ pub trait NetworkBehaviour: 'static { /// The `peer_id` is guaranteed to be in a connected state. In other words, /// [`NetworkBehaviour::inject_connection_established`] has previously been called with this `PeerId`. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Implement `NetworkBehaviour::on_connection_handler_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_event( @@ -258,7 +258,7 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that the dial to a known or unknown node failed. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `InEvent::DialFailure` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_dial_failure( @@ -280,7 +280,7 @@ pub trait NetworkBehaviour: 'static { /// This can include, for example, an error during the handshake of the encryption layer, or the /// connection unexpectedly closed. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::ListenFailure` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listen_failure( @@ -298,7 +298,7 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that a new listener was created. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::NewListener` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_listener(&mut self, id: ListenerId) { @@ -307,7 +307,7 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that we have started listening on a new multiaddr. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::NewListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { @@ -320,7 +320,7 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that a multiaddr we were listening on has expired, /// which means that we are no longer listening on it. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::ExpiredListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) { @@ -332,7 +332,7 @@ pub trait NetworkBehaviour: 'static { /// A listener experienced an error. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::ListenerError` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) { @@ -344,7 +344,7 @@ pub trait NetworkBehaviour: 'static { /// A listener closed. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::ListenerClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) { @@ -356,7 +356,7 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that we have discovered a new external address for us. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::NewExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_new_external_addr(&mut self, addr: &Multiaddr) { @@ -365,7 +365,7 @@ pub trait NetworkBehaviour: 'static { /// Indicates to the behaviour that an external address was removed. #[deprecated( - since = "0.39.0", + since = "0.40.2", note = "Handle `FromSwarm::ExpiredExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it." )] fn inject_expired_external_addr(&mut self, addr: &Multiaddr) { From 6695976ee924ede5a2bb614e97d3a6bde042ebe4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 2 Nov 2022 11:26:17 +0000 Subject: [PATCH 48/60] review: Address Thomas suggestions --- protocols/dcutr/src/behaviour.rs | 24 +++--- protocols/gossipsub/src/behaviour.rs | 13 +-- protocols/kad/src/behaviour.rs | 121 ++++++++++++++------------- protocols/ping/src/lib.rs | 24 +++++- 4 files changed, 105 insertions(+), 77 deletions(-) diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index 91fba987348..deeb3a9ac10 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -88,12 +88,12 @@ impl Behaviour { ConnectionEstablished { peer_id, connection_id, - endpoint, + endpoint: connected_point, .. }: ConnectionEstablished, ) { - if endpoint.is_relayed() { - if endpoint.is_listener() && !self.direct_connections.contains_key(&peer_id) { + if connected_point.is_relayed() { + if connected_point.is_listener() && !self.direct_connections.contains_key(&peer_id) { // TODO: Try dialing the remote peer directly. Specification: // // > The protocol starts with the completion of a relay connection from A to B. Upon @@ -112,7 +112,7 @@ impl Behaviour { NetworkBehaviourAction::GenerateEvent( Event::InitiatedDirectConnectionUpgrade { remote_peer_id: peer_id, - local_relayed_addr: match endpoint { + local_relayed_addr: match connected_point { ConnectedPoint::Listener { local_addr, .. } => local_addr.clone(), ConnectedPoint::Dialer { .. } => unreachable!("Due to outer if."), }, @@ -172,11 +172,11 @@ impl Behaviour { ConnectionClosed { peer_id, connection_id, - endpoint, + endpoint: connected_point, .. }: ConnectionClosed<::ConnectionHandler>, ) { - if !endpoint.is_relayed() { + if !connected_point.is_relayed() { let connections = self .direct_connections .get_mut(&peer_id) @@ -203,11 +203,11 @@ impl NetworkBehaviour for Behaviour { fn on_connection_handler_event( &mut self, event_source: PeerId, - connection_id: ConnectionId, - event: <::Handler as + connection: ConnectionId, + handler_event: <::Handler as ConnectionHandler>::OutEvent, ) { - match event { + match handler_event { Either::Left(handler::relayed::Event::InboundConnectRequest { inbound_connect, remote_addr, @@ -215,7 +215,7 @@ impl NetworkBehaviour for Behaviour { self.queued_actions.extend([ ActionBuilder::AcceptInboundConnect { peer_id: event_source, - handler: NotifyHandler::One(connection_id), + handler: NotifyHandler::One(connection), inbound_connect, }, NetworkBehaviourAction::GenerateEvent( @@ -244,7 +244,7 @@ impl NetworkBehaviour for Behaviour { .condition(dial_opts::PeerCondition::Always) .build(), handler: handler::Prototype::DirectConnection { - relayed_connection_id: connection_id, + relayed_connection_id: connection, role: handler::Role::Listener, }, } @@ -272,7 +272,7 @@ impl NetworkBehaviour for Behaviour { .override_role() .build(), handler: handler::Prototype::DirectConnection { - relayed_connection_id: connection_id, + relayed_connection_id: connection, role: handler::Role::Initiator { attempt }, }, } diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index 88606037dd2..bb29fa42e39 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -3257,27 +3257,30 @@ where fn on_address_change( &mut self, AddressChange { - peer_id, old, new, .. + peer_id, + old: endpoint_old, + new: endpoint_new, + .. }: AddressChange, ) { // Exchange IP in peer scoring system if let Some((peer_score, ..)) = &mut self.peer_score { - if let Some(ip) = get_ip_addr(old.get_remote_address()) { + if let Some(ip) = get_ip_addr(endpoint_old.get_remote_address()) { peer_score.remove_ip(&peer_id, &ip); } else { trace!( "Couldn't extract ip from endpoint of peer {} with endpoint {:?}", &peer_id, - old + endpoint_old ) } - if let Some(ip) = get_ip_addr(new.get_remote_address()) { + if let Some(ip) = get_ip_addr(endpoint_new.get_remote_address()) { peer_score.add_ip(&peer_id, ip); } else { trace!( "Couldn't extract ip from endpoint of peer {} with endpoint {:?}", peer_id, - new + endpoint_new ) } } diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index b6eed03db22..8bc7b10821a 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -1815,20 +1815,61 @@ where } } - fn on_connection_closed( + fn on_address_change( &mut self, - ConnectionClosed { - peer_id, - remaining_established, + AddressChange { + peer_id: peer, + old, + new, .. - }: ConnectionClosed<::ConnectionHandler>, + }: AddressChange, ) { - if remaining_established == 0 { - for query in self.queries.iter_mut() { - query.on_failure(&peer_id); + let (old, new) = (old.get_remote_address(), new.get_remote_address()); + + // Update routing table. + if let Some(addrs) = self.kbuckets.entry(&kbucket::Key::from(peer)).value() { + if addrs.replace(old, new) { + debug!( + "Address '{}' replaced with '{}' for peer '{}'.", + old, new, peer + ); + } else { + debug!( + "Address '{}' not replaced with '{}' for peer '{}' as old address wasn't \ + present.", + old, new, peer + ); + } + } else { + debug!( + "Address '{}' not replaced with '{}' for peer '{}' as peer is not present in the \ + routing table.", + old, new, peer + ); + } + + // Update query address cache. + // + // Given two connected nodes: local node A and remote node B. Say node B + // is not in node A's routing table. Additionally node B is part of the + // `QueryInner::addresses` list of an ongoing query on node A. Say Node + // B triggers an address change and then disconnects. Later on the + // earlier mentioned query on node A would like to connect to node B. + // Without replacing the address in the `QueryInner::addresses` set node + // A would attempt to dial the old and not the new address. + // + // While upholding correctness, iterating through all discovered + // addresses of a peer in all currently ongoing queries might have a + // large performance impact. If so, the code below might be worth + // revisiting. + for query in self.queries.iter_mut() { + if let Some(addrs) = query.inner.addresses.get_mut(&peer) { + for addr in addrs.iter_mut() { + if addr == old { + *addr = new.clone(); + } + } } - self.connection_updated(peer_id, None, NodeStatus::Disconnected); - self.connected_peers.remove(&peer_id); } } @@ -1876,58 +1917,20 @@ where } } - fn on_address_change( + fn on_connection_closed( &mut self, - AddressChange { - peer_id, old, new, .. - }: AddressChange, + ConnectionClosed { + peer_id, + remaining_established, + .. + }: ConnectionClosed<::ConnectionHandler>, ) { - let (old, new) = (old.get_remote_address(), new.get_remote_address()); - - // Update routing table. - if let Some(addrs) = self.kbuckets.entry(&kbucket::Key::from(peer_id)).value() { - if addrs.replace(old, new) { - debug!( - "Address '{}' replaced with '{}' for peer '{}'.", - old, new, peer_id - ); - } else { - debug!( - "Address '{}' not replaced with '{}' for peer '{}' as old address wasn't \ - present.", - old, new, peer_id, - ); - } - } else { - debug!( - "Address '{}' not replaced with '{}' for peer '{}' as peer is not present in the \ - routing table.", - old, new, peer_id, - ); - } - - // Update query address cache. - // - // Given two connected nodes: local node A and remote node B. Say node B - // is not in node A's routing table. Additionally node B is part of the - // `QueryInner::addresses` list of an ongoing query on node A. Say Node - // B triggers an address change and then disconnects. Later on the - // earlier mentioned query on node A would like to connect to node B. - // Without replacing the address in the `QueryInner::addresses` set node - // A would attempt to dial the old and not the new address. - // - // While upholding correctness, iterating through all discovered - // addresses of a peer in all currently ongoing queries might have a - // large performance impact. If so, the code below might be worth - // revisiting. - for query in self.queries.iter_mut() { - if let Some(addrs) = query.inner.addresses.get_mut(&peer_id) { - for addr in addrs.iter_mut() { - if addr == old { - *addr = new.clone(); - } - } + if remaining_established == 0 { + for query in self.queries.iter_mut() { + query.on_failure(&peer_id); } + self.connection_updated(peer_id, None, NodeStatus::Disconnected); + self.connected_peers.remove(&peer_id); } } } diff --git a/protocols/ping/src/lib.rs b/protocols/ping/src/lib.rs index 22a2b0418c5..6e3314c5489 100644 --- a/protocols/ping/src/lib.rs +++ b/protocols/ping/src/lib.rs @@ -46,7 +46,9 @@ mod protocol; use handler::Handler; pub use handler::{Config, Failure, Success}; use libp2p_core::{connection::ConnectionId, PeerId}; -use libp2p_swarm::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use libp2p_swarm::{ + behaviour::FromSwarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters, +}; use std::{ collections::VecDeque, task::{Context, Poll}, @@ -142,4 +144,24 @@ impl NetworkBehaviour for Behaviour { Poll::Pending } } + + fn on_swarm_event( + &mut self, + event: libp2p_swarm::behaviour::FromSwarm, + ) { + match event { + FromSwarm::ConnectionEstablished(_) => {} + FromSwarm::ConnectionClosed(_) => {} + FromSwarm::AddressChange(_) => {} + FromSwarm::DialFailure(_) => {} + FromSwarm::ListenFailure(_) => {} + FromSwarm::NewListener(_) => {} + FromSwarm::NewListenAddr(_) => {} + FromSwarm::ExpiredListenAddr(_) => {} + FromSwarm::ListenerError(_) => {} + FromSwarm::ListenerClosed(_) => {} + FromSwarm::NewExternalAddr(_) => {} + FromSwarm::ExpiredExternalAddr(_) => {} + } + } } From 70906445ef5b1251aa65f716990690f8b2624aa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 2 Nov 2022 18:07:28 +0000 Subject: [PATCH 49/60] swarm-derive: update proc macro to use on_swarm_event, and on_connection_handler_events --- swarm-derive/src/lib.rs | 289 ++++++++++++++++++++----------------- swarm-derive/tests/test.rs | 2 +- 2 files changed, 155 insertions(+), 136 deletions(-) diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index 426e4faec1f..847cf7479fc 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -55,10 +55,19 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { let into_proto_select_ident = quote! {::libp2p::swarm::IntoConnectionHandlerSelect}; let peer_id = quote! {::libp2p::core::PeerId}; let connection_id = quote! {::libp2p::core::connection::ConnectionId}; - let dial_errors = quote! {Option<&Vec<::libp2p::core::Multiaddr>>}; - let connected_point = quote! {::libp2p::core::ConnectedPoint}; - let listener_id = quote! {::libp2p::core::transport::ListenerId}; - let dial_error = quote! {::libp2p::swarm::DialError}; + let from_swarm = quote! {::libp2p::swarm::behaviour::FromSwarm}; + let connection_established = quote! {::libp2p::swarm::behaviour::ConnectionEstablished}; + let address_change = quote! {::libp2p::swarm::behaviour::AddressChange}; + let connection_closed = quote! {::libp2p::swarm::behaviour::ConnectionClosed}; + let dial_failure = quote! {::libp2p::swarm::behaviour::DialFailure}; + let listen_failure = quote! {::libp2p::swarm::behaviour::ListenFailure}; + let new_listener = quote! {::libp2p::swarm::behaviour::NewListener}; + let new_listen_addr = quote! {::libp2p::swarm::behaviour::NewListenAddr}; + let expired_listen_addr = quote! {::libp2p::swarm::behaviour::ExpiredListenAddr}; + let new_external_addr = quote! {::libp2p::swarm::behaviour::NewExternalAddr}; + let expired_external_addr = quote! {::libp2p::swarm::behaviour::ExpiredExternalAddr}; + let listener_error = quote! {::libp2p::swarm::behaviour::ListenerError}; + let listener_closed = quote! {::libp2p::swarm::behaviour::ListenerClosed}; let poll_parameters = quote! {::libp2p::swarm::PollParameters}; @@ -180,35 +189,44 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }) }; - // Build the list of statements to put in the body of `inject_connection_established()`. - let inject_connection_established_stmts = { - data_struct.fields.iter().enumerate().map(move |(field_n, field)| { - match field.ident { - Some(ref i) => quote!{ self.#i.inject_connection_established(peer_id, connection_id, endpoint, errors, other_established); }, - None => quote!{ self.#field_n.inject_connection_established(peer_id, connection_id, endpoint, errors, other_established); }, - } - }) + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::ConnectionEstablished variant. + let on_connection_established_stmts = { + data_struct + .fields + .iter() + .enumerate() + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event( + #from_swarm::ConnectionEstablished(#connection_established { peer_id, connection_id, endpoint, failed_addresses, other_established}));}, + None => quote! { self.#field_n.on_swarm_event( + #from_swarm::ConnectionEstablished(#connection_established { peer_id, connection_id, endpoint, failed_addresses, other_established}));}, + }) }; - // Build the list of statements to put in the body of `inject_address_change()`. - let inject_address_change_stmts = { - data_struct.fields.iter().enumerate().map(move |(field_n, field)| { - match field.ident { - Some(ref i) => quote!{ self.#i.inject_address_change(peer_id, connection_id, old, new); }, - None => quote!{ self.#field_n.inject_address_change(peer_id, connection_id, old, new); }, - } - }) + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::AddressChange variant. + let on_address_change_stmts = { + data_struct + .fields + .iter() + .enumerate() + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::AddressChange(#address_change { peer_id, connection_id, old, new }));}, + None => quote! { self.#field_n.on_swarm_event(#from_swarm::AddressChange(#address_change { peer_id, connection_id, old, new }));}, + }) }; - // Build the list of statements to put in the body of `inject_connection_closed()`. - let inject_connection_closed_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::ConnectionClosed variant. + let on_connection_closed_stmts = { data_struct.fields .iter() .enumerate() // The outmost handler belongs to the last behaviour. .rev() .enumerate() - .map(move |(enum_n, (field_n, field))| { + .map(|(enum_n, (field_n, field))| { let handler = if field_n == 0 { // Given that the iterator is reversed, this is the innermost handler only. quote! { let handler = handlers } @@ -217,20 +235,23 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { let (handlers, handler) = handlers.into_inner() } }; - let inject = match field.ident { - Some(ref i) => quote!{ self.#i.inject_connection_closed(peer_id, connection_id, endpoint, handler, remaining_established) }, - None => quote!{ self.#enum_n.inject_connection_closed(peer_id, connection_id, endpoint, handler, remaining_established) }, + let on = match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event( + #from_swarm::ConnectionClosed(#connection_closed { peer_id, connection_id, endpoint, handler, remaining_established }));}, + None => quote! { self.#enum_n.on_swarm_event( + #from_swarm::ConnectionClosed(#connection_closed { peer_id, connection_id, endpoint, handler, remaining_established }));}, }; quote! { #handler; - #inject; + #on; } }) }; - // Build the list of statements to put in the body of `inject_dial_failure()`. - let inject_dial_failure_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::DialFailure variant. + let on_dial_failure_stmts = { data_struct .fields .iter() @@ -238,7 +259,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { // The outmost handler belongs to the last behaviour. .rev() .enumerate() - .map(move |(enum_n, (field_n, field))| { + .map(|(enum_n, (field_n, field))| { let handler = if field_n == 0 { // Given that the iterator is reversed, this is the innermost handler only. quote! { let handler = handlers } @@ -248,30 +269,27 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { } }; - let inject = match field.ident { - Some(ref i) => { - quote! { self.#i.inject_dial_failure(peer_id, handler, error) } - } - None => { - quote! { self.#enum_n.inject_dial_failure(peer_id, handler, error) } - } + let on = match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::DialFailure(#dial_failure { peer_id, handler, error }));}, + None => quote! { self.#enum_n.on_swarm_event(#from_swarm::DialFailure(#dial_failure { peer_id, handler, error }));} }; quote! { #handler; - #inject; + #on; } }) }; - // Build the list of statements to put in the body of `inject_listen_failure()`. - let inject_listen_failure_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::ListenFailure variant. + let on_listen_failure_stmts = { data_struct.fields .iter() .enumerate() .rev() .enumerate() - .map(move |(enum_n, (field_n, field))| { + .map(|(enum_n, (field_n, field))| { let handler = if field_n == 0 { quote! { let handler = handlers } } else { @@ -280,107 +298,114 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { } }; - let inject = match field.ident { - Some(ref i) => quote! { self.#i.inject_listen_failure(local_addr, send_back_addr, handler) }, - None => quote! { self.#enum_n.inject_listen_failure(local_addr, send_back_addr, handler) }, + let on = match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ListenFailure(#listen_failure { local_addr, send_back_addr, handler }));}, + None => quote! { self.#enum_n.on_swarm_event(#from_swarm::ListenFailure(#listen_failure { local_addr, send_back_addr, handler }));}, }; quote! { #handler; - #inject; + #on; } }) }; - // Build the list of statements to put in the body of `inject_new_listener()`. - let inject_new_listener_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::NewListener variant. + let on_new_listener_stmts = { data_struct .fields .iter() .enumerate() - .map(move |(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.inject_new_listener(id); }, - None => quote! { self.#field_n.inject_new_listener(id); }, + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::NewListener(#new_listener { listener_id }));}, + None => quote! { self.#field_n.on_swarm_event(#from_swarm::NewListener(#new_listener { listener_id }));}, }) }; - // Build the list of statements to put in the body of `inject_new_listen_addr()`. - let inject_new_listen_addr_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::NewListenAddr variant. + let on_new_listen_addr_stmts = { data_struct .fields .iter() .enumerate() - .map(move |(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.inject_new_listen_addr(id, addr); }, - None => quote! { self.#field_n.inject_new_listen_addr(id, addr); }, + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::NewListenAddr(#new_listen_addr { listener_id, addr }));}, + None => quote! { self.#field_n.on_swarm_event(#from_swarm::NewListenAddr(#new_listen_addr { listener_id, addr }));}, }) }; - // Build the list of statements to put in the body of `inject_expired_listen_addr()`. - let inject_expired_listen_addr_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::ExpiredListenAddr variant. + let on_expired_listen_addr_stmts = { data_struct .fields .iter() .enumerate() - .map(move |(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.inject_expired_listen_addr(id, addr); }, - None => quote! { self.#field_n.inject_expired_listen_addr(id, addr); }, + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ExpiredListenAddr(#expired_listen_addr { listener_id, addr }));}, + None => quote! { self.#field_n.on_swarm_event(#from_swarm::ExpiredListenAddr(#expired_listen_addr { listener_id, addr }));}, }) }; - // Build the list of statements to put in the body of `inject_new_external_addr()`. - let inject_new_external_addr_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::NewExternalAddr variant. + let on_new_external_addr_stmts = { data_struct .fields .iter() .enumerate() - .map(move |(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.inject_new_external_addr(addr); }, - None => quote! { self.#field_n.inject_new_external_addr(addr); }, + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::NewExternalAddr(#new_external_addr { addr }));}, + None => quote! { self.#field_n.on_swarm_event(#from_swarm::NewExternalAddr(#new_external_addr { addr }));}, }) }; - // Build the list of statements to put in the body of `inject_expired_external_addr()`. - let inject_expired_external_addr_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::ExpiredExternalAddr variant. + let on_expired_external_addr_stmts = { data_struct .fields .iter() .enumerate() - .map(move |(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.inject_expired_external_addr(addr); }, - None => quote! { self.#field_n.inject_expired_external_addr(addr); }, + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ExpiredExternalAddr(#expired_external_addr { addr }));}, + None => quote! { self.#field_n.on_swarm_event(#from_swarm::ExpiredExternalAddr(#expired_external_addr { addr }));}, }) }; - // Build the list of statements to put in the body of `inject_listener_error()`. - let inject_listener_error_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::ListenerError variant. + let on_listener_error_stmts = { data_struct .fields .iter() .enumerate() - .map(move |(field_n, field)| match field.ident { - Some(ref i) => quote!(self.#i.inject_listener_error(id, err);), - None => quote!(self.#field_n.inject_listener_error(id, err);), + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ListenerError(#listener_error { listener_id, err }));}, + None => quote!{self.#field_n.on_swarm_event(#from_swarm::ListenerError(#listener_error { listener_id, err }));}, }) }; - // Build the list of statements to put in the body of `inject_listener_closed()`. - let inject_listener_closed_stmts = { + // Build the list of statements to put in the body of `on_swarm_event()` + // for the FromSwarm::ListenerClosed variant. + let on_listener_closed_stmts = { data_struct .fields .iter() .enumerate() - .map(move |(field_n, field)| match field.ident { - Some(ref i) => quote!(self.#i.inject_listener_closed(id, reason);), - None => quote!(self.#field_n.inject_listener_closed(id, reason);), + .map(|(field_n, field)| match field.ident { + Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ListenerClosed(#listener_closed { listener_id, reason }));}, + None => quote!{self.#field_n.on_swarm_event(#from_swarm::ListenerClosed(#listener_closed { listener_id, reason }));}, }) }; - // Build the list of variants to put in the body of `inject_event()`. + // Build the list of variants to put in the body of `on_connection_handler_event()`. // // The event type is a construction of nested `#either_ident`s of the events of the children. - // We call `inject_event` on the corresponding child. - let inject_node_event_stmts = data_struct.fields.iter().enumerate().enumerate().map(|(enum_n, (field_n, field))| { + // We call `on_connection_handler_event` on the corresponding child. + let on_node_event_stmts = data_struct.fields.iter().enumerate().enumerate().map(|(enum_n, (field_n, field))| { let mut elem = if enum_n != 0 { quote!{ #either_ident::Second(ev) } } else { @@ -392,8 +417,8 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { } Some(match field.ident { - Some(ref i) => quote!{ #elem => #trait_to_impl::inject_event(&mut self.#i, peer_id, connection_id, ev) }, - None => quote!{ #elem => #trait_to_impl::inject_event(&mut self.#field_n, peer_id, connection_id, ev) }, + Some(ref i) => quote!{ #elem => #trait_to_impl::on_connection_handler_event(&mut self.#i, peer_id, connection_id, ev) }, + None => quote!{ #elem => #trait_to_impl::on_connection_handler_event(&mut self.#field_n, peer_id, connection_id, ev) }, }) }); @@ -564,62 +589,14 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { out } - fn inject_connection_established(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, endpoint: &#connected_point, errors: #dial_errors, other_established: usize) { - #(#inject_connection_established_stmts);* - } - - fn inject_address_change(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, old: &#connected_point, new: &#connected_point) { - #(#inject_address_change_stmts);* - } - - fn inject_connection_closed(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, endpoint: &#connected_point, handlers: ::Handler, remaining_established: usize) { - #(#inject_connection_closed_stmts);* - } - - fn inject_dial_failure(&mut self, peer_id: Option<#peer_id>, handlers: Self::ConnectionHandler, error: &#dial_error) { - #(#inject_dial_failure_stmts);* - } - - fn inject_listen_failure(&mut self, local_addr: &#multiaddr, send_back_addr: &#multiaddr, handlers: Self::ConnectionHandler) { - #(#inject_listen_failure_stmts);* - } - - fn inject_new_listener(&mut self, id: #listener_id) { - #(#inject_new_listener_stmts);* - } - - fn inject_new_listen_addr(&mut self, id: #listener_id, addr: &#multiaddr) { - #(#inject_new_listen_addr_stmts);* - } - - fn inject_expired_listen_addr(&mut self, id: #listener_id, addr: &#multiaddr) { - #(#inject_expired_listen_addr_stmts);* - } - - fn inject_new_external_addr(&mut self, addr: &#multiaddr) { - #(#inject_new_external_addr_stmts);* - } - - fn inject_expired_external_addr(&mut self, addr: &#multiaddr) { - #(#inject_expired_external_addr_stmts);* - } - - fn inject_listener_error(&mut self, id: #listener_id, err: &(dyn std::error::Error + 'static)) { - #(#inject_listener_error_stmts);* - } - - fn inject_listener_closed(&mut self, id: #listener_id, reason: std::result::Result<(), &std::io::Error>) { - #(#inject_listener_closed_stmts);* - } - - fn inject_event( + fn on_connection_handler_event( &mut self, peer_id: #peer_id, connection_id: #connection_id, event: <::Handler as #connection_handler>::OutEvent ) { match event { - #(#inject_node_event_stmts),* + #(#on_node_event_stmts),* } } @@ -628,6 +605,48 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { #(#poll_stmts)* std::task::Poll::Pending } + + fn on_swarm_event(&mut self, event: #from_swarm) { + match event { + #from_swarm::ConnectionEstablished( + #connection_established { peer_id, connection_id, endpoint, failed_addresses, other_established }) + => { #(#on_connection_established_stmts)* } + #from_swarm::AddressChange( + #address_change { peer_id, connection_id, old, new }) + => { #(#on_address_change_stmts)* } + #from_swarm::ConnectionClosed( + #connection_closed { peer_id, connection_id, endpoint, handler: handlers, remaining_established }) + => { #(#on_connection_closed_stmts)* } + #from_swarm::DialFailure( + #dial_failure { peer_id, handler: handlers, error }) + => { #(#on_dial_failure_stmts)* } + #from_swarm::ListenFailure( + #listen_failure { local_addr, send_back_addr, handler: handlers }) + => { #(#on_listen_failure_stmts)* } + #from_swarm::NewListener( + #new_listener { listener_id }) + => { #(#on_new_listener_stmts)* } + #from_swarm::NewListenAddr( + #new_listen_addr { listener_id, addr }) + => { #(#on_new_listen_addr_stmts)* } + #from_swarm::ExpiredListenAddr( + #expired_listen_addr { listener_id, addr }) + => { #(#on_expired_listen_addr_stmts)* } + #from_swarm::NewExternalAddr( + #new_external_addr { addr }) + => { #(#on_new_external_addr_stmts)* } + #from_swarm::ExpiredExternalAddr( + #expired_external_addr { addr }) + => { #(#on_expired_external_addr_stmts)* } + #from_swarm::ListenerError( + #listener_error { listener_id, err }) + => { #(#on_listener_error_stmts)* } + #from_swarm::ListenerClosed( + #listener_closed { listener_id, reason }) + => { #(#on_listener_closed_stmts)* } + _ => {} + } + } } }; diff --git a/swarm-derive/tests/test.rs b/swarm-derive/tests/test.rs index 2404ef699ca..a03ca8f82e9 100644 --- a/swarm-derive/tests/test.rs +++ b/swarm-derive/tests/test.rs @@ -373,7 +373,7 @@ fn custom_out_event_no_type_parameters() { dummy::ConnectionHandler } - fn inject_event( + fn on_connection_handler_event( &mut self, _peer: PeerId, _connection: ConnectionId, From ae3e68a4a7f16159284974b5885323d44825dccd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 3 Nov 2022 10:09:02 +0000 Subject: [PATCH 50/60] review: Address Max suggestions --- CHANGELOG.md | 20 +++++++++++++++++++- Cargo.toml | 2 +- protocols/autonat/CHANGELOG.md | 2 +- protocols/dcutr/CHANGELOG.md | 2 +- protocols/floodsub/CHANGELOG.md | 2 +- protocols/gossipsub/CHANGELOG.md | 2 +- protocols/gossipsub/src/behaviour/tests.rs | 7 ------- protocols/identify/CHANGELOG.md | 2 +- protocols/kad/CHANGELOG.md | 2 +- protocols/mdns/CHANGELOG.md | 2 +- protocols/ping/CHANGELOG.md | 2 +- protocols/relay/CHANGELOG.md | 2 +- protocols/rendezvous/CHANGELOG.md | 2 +- protocols/request-response/CHANGELOG.md | 2 +- swarm-derive/CHANGELOG.md | 8 ++++++++ swarm-derive/Cargo.toml | 2 +- swarm/CHANGELOG.md | 2 ++ 17 files changed, 42 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 65999fbb193..7eae97a15ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,24 @@ # `libp2p` facade crate +# 0.49.1 - [unreleased] + +- Add new `on_swarm_event` method to `NetworkBehaviour` that accepts a `FromSwarm` enum and update + `inject_*` methods to call `on_swarm_event` with the respective `FromSwarm` variant and deprecate + `inject_*`. + To migrate, users should replace the `NetworkBehaviour::inject_*` calls with a single + implementation of `NetworkBehaviour::on_swarm_event` treating each `FromSwarm` variant in + the same way its corresponding `inject_*` call was treated. + See [PR 3011]. + +- Add new `on_connection_handler_event` method with the same signature as `inject_event`, make the + default implementation of `inject_event` call `on_connection_handler_event` and deprecate it. + To migrate, users should replace the `NetworkBehaviour::inject_event` calls + with `NetworkBehaviour::on_connection_handler_event`. + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 + # 0.49.0 - Remove default features. You need to enable required features explicitly now. As a quick workaround, you may want to use the @@ -55,7 +73,7 @@ - `tcp-async-io` in favor of `tcp` + `async-std` - `mdns-async-io` in favor of `mdns` + `async-std` - `dns-async-std` in favor of `dns` + `async-std` - + See [PR 2962]. - Update individual crates. diff --git a/Cargo.toml b/Cargo.toml index d369bb9a0c6..f68e8ce1315 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p" edition = "2021" rust-version = "1.60.0" description = "Peer-to-peer networking library" -version = "0.49.0" +version = "0.49.1" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/protocols/autonat/CHANGELOG.md b/protocols/autonat/CHANGELOG.md index 6d0dad33bf4..97a107e9ecb 100644 --- a/protocols/autonat/CHANGELOG.md +++ b/protocols/autonat/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.8.1 - [unreleased] -- Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Behaviour`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/dcutr/CHANGELOG.md b/protocols/dcutr/CHANGELOG.md index 47ad734a026..e8a10fe9d3e 100644 --- a/protocols/dcutr/CHANGELOG.md +++ b/protocols/dcutr/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.7.1 - [unreleased] -- Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Behaviour`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/floodsub/CHANGELOG.md b/protocols/floodsub/CHANGELOG.md index 977d1934159..eb856c19a5d 100644 --- a/protocols/floodsub/CHANGELOG.md +++ b/protocols/floodsub/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.40.1 - [unreleased] -- Replace `Floodsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Floodsub`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/gossipsub/CHANGELOG.md b/protocols/gossipsub/CHANGELOG.md index 30dd5e1dd9a..c5065d86331 100644 --- a/protocols/gossipsub/CHANGELOG.md +++ b/protocols/gossipsub/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.42.1 - [unreleased] -- Replace `Gossipsub`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Gossipsub`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/gossipsub/src/behaviour/tests.rs b/protocols/gossipsub/src/behaviour/tests.rs index a1e8acca8da..9bf32d8ff43 100644 --- a/protocols/gossipsub/src/behaviour/tests.rs +++ b/protocols/gossipsub/src/behaviour/tests.rs @@ -2351,13 +2351,6 @@ fn test_add_outbound_peers_if_min_is_not_satisfied() { ); } -//TODO add a test that ensures that new outbound connections are recognized as such. -// This is at the moment done in behaviour with relying on the fact that the call to -// `NetworkBehaviour::on_swarm_event` with `FromSwarm::ConnectionEstablished` -// for the first connection is done before `inject_connected` -// gets called. For all further connections `NetworkBehaviour::on_swarm_event` -// should get called wit `FromSwarm::ConnectionEstablished` after `inject_connected`. - #[test] fn test_prune_negative_scored_peers() { let config = GossipsubConfig::default(); diff --git a/protocols/identify/CHANGELOG.md b/protocols/identify/CHANGELOG.md index 343b2a585d5..69c0dc31de0 100644 --- a/protocols/identify/CHANGELOG.md +++ b/protocols/identify/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.40.1 - [unreleased] -- Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Behaviour`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/kad/CHANGELOG.md b/protocols/kad/CHANGELOG.md index 9617085ff5f..eee59cc5cd1 100644 --- a/protocols/kad/CHANGELOG.md +++ b/protocols/kad/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.41.1 - [unreleased] -- Replace `Kademlia`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Kademlia`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/mdns/CHANGELOG.md b/protocols/mdns/CHANGELOG.md index 37eb8178f19..89755eb6db3 100644 --- a/protocols/mdns/CHANGELOG.md +++ b/protocols/mdns/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.41.1 - [unreleased] -- Replace `GenMdns`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `GenMdns`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/ping/CHANGELOG.md b/protocols/ping/CHANGELOG.md index e25e47b1deb..c138c28730e 100644 --- a/protocols/ping/CHANGELOG.md +++ b/protocols/ping/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.40.1 - [unreleased] -- Replace `Behaviour`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Behaviour`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/relay/CHANGELOG.md b/protocols/relay/CHANGELOG.md index 90b740237a8..ffacd59d6f2 100644 --- a/protocols/relay/CHANGELOG.md +++ b/protocols/relay/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.13.1 - [unreleased] -- Replace `Client` and `Relay`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Client` and `Relay`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/rendezvous/CHANGELOG.md b/protocols/rendezvous/CHANGELOG.md index 99411035a57..c985f78d64b 100644 --- a/protocols/rendezvous/CHANGELOG.md +++ b/protocols/rendezvous/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.10.1 - [unreleased] -- Replace `Client` and `Server`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `Client` and `Server`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/protocols/request-response/CHANGELOG.md b/protocols/request-response/CHANGELOG.md index 4ea95a668dc..419abed0322 100644 --- a/protocols/request-response/CHANGELOG.md +++ b/protocols/request-response/CHANGELOG.md @@ -1,6 +1,6 @@ # 0.22.1 - [unreleased] -- Replace `RequestResponse`'s NetworkBehaviour implemention `inject_*` methods with the new `on_*` methods. +- Replace `RequestResponse`'s `NetworkBehaviour` implemention `inject_*` methods with the new `on_*` methods. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 diff --git a/swarm-derive/CHANGELOG.md b/swarm-derive/CHANGELOG.md index 722537e6b59..7d5e3251cc1 100644 --- a/swarm-derive/CHANGELOG.md +++ b/swarm-derive/CHANGELOG.md @@ -1,3 +1,11 @@ +# 0.30.2 - [unreleased] + +- Replace `NetworkBehaviour` Derive macro deprecated `inject_*` method implementations + with the new `on_swarm_event` and `on_connection_handler_event`. + See [PR 3011]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 + # 0.30.1 - Fix an issue where the derive would generate bad code if the type parameters between the behaviour and a custom diff --git a/swarm-derive/Cargo.toml b/swarm-derive/Cargo.toml index baab666b0eb..3e69363d05a 100644 --- a/swarm-derive/Cargo.toml +++ b/swarm-derive/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-swarm-derive" edition = "2021" rust-version = "1.56.1" description = "Procedural macros of libp2p-core" -version = "0.30.1" +version = "0.30.2" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 9a3c40ea482..7504c55be2e 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -10,6 +10,8 @@ - Add new `on_connection_handler_event` method with the same signature as `inject_event`, make the default implementation of `inject_event` call `on_connection_handler_event` and deprecate it. + To migrate, users should replace the `NetworkBehaviour::inject_event` call + with `NetworkBehaviour::on_connection_handler_event`. See [PR 3011]. [PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 From c1d053a79230be6c346a0f4298cb82b57aff3e46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 3 Nov 2022 10:47:59 +0000 Subject: [PATCH 51/60] review: remove non need newline --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9b4266be703..744ca92ef4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -110,7 +110,6 @@ - `tcp-async-io` in favor of `tcp` + `async-std` - `mdns-async-io` in favor of `mdns` + `async-std` - `dns-async-std` in favor of `dns` + `async-std` - See [PR 2962]. - Update individual crates. From a369ee73cd7c38fbc12fc1ef62385fad64b4e071 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 3 Nov 2022 10:54:22 +0000 Subject: [PATCH 52/60] review: re-introduce trailing whitespace for less review diff --- Cargo.toml | 2 +- protocols/autonat/Cargo.toml | 2 +- protocols/dcutr/Cargo.toml | 2 +- protocols/floodsub/Cargo.toml | 2 +- protocols/gossipsub/Cargo.toml | 2 +- protocols/identify/Cargo.toml | 2 +- protocols/kad/Cargo.toml | 2 +- protocols/mdns/Cargo.toml | 2 +- protocols/ping/Cargo.toml | 2 +- protocols/relay/Cargo.toml | 2 +- protocols/rendezvous/Cargo.toml | 2 +- swarm/Cargo.toml | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e0086fe5e01..6bc3f5e4e2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -202,7 +202,7 @@ required-features = ["full"] name = "distributed-key-value-store" required-features = ["full"] -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/autonat/Cargo.toml b/protocols/autonat/Cargo.toml index d25a7343182..10fd0e71ff5 100644 --- a/protocols/autonat/Cargo.toml +++ b/protocols/autonat/Cargo.toml @@ -31,7 +31,7 @@ env_logger = "0.9" clap = { version = "4.0.13", features = ["derive"] } libp2p = { path = "../..", features = ["full"] } -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/dcutr/Cargo.toml b/protocols/dcutr/Cargo.toml index 8b57214536a..33486f494a2 100644 --- a/protocols/dcutr/Cargo.toml +++ b/protocols/dcutr/Cargo.toml @@ -34,7 +34,7 @@ libp2p = { path = "../..", features = ["full"] } rand = "0.8" clap = { version = "4.0.13", features = ["derive"] } -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/floodsub/Cargo.toml b/protocols/floodsub/Cargo.toml index 6a914fd4909..1225d1cd99d 100644 --- a/protocols/floodsub/Cargo.toml +++ b/protocols/floodsub/Cargo.toml @@ -25,7 +25,7 @@ thiserror = "1.0.37" [build-dependencies] prost-build = "0.11" -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/gossipsub/Cargo.toml b/protocols/gossipsub/Cargo.toml index 29085a0e331..4f34aada5ea 100644 --- a/protocols/gossipsub/Cargo.toml +++ b/protocols/gossipsub/Cargo.toml @@ -44,7 +44,7 @@ derive_builder = "0.11.1" [build-dependencies] prost-build = "0.11" -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/identify/Cargo.toml b/protocols/identify/Cargo.toml index 181ac718740..c0d05b7039d 100644 --- a/protocols/identify/Cargo.toml +++ b/protocols/identify/Cargo.toml @@ -32,7 +32,7 @@ libp2p = { path = "../..", features = ["full"] } [build-dependencies] prost-build = "0.11" -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/kad/Cargo.toml b/protocols/kad/Cargo.toml index 5d5d8538271..8f91f34180c 100644 --- a/protocols/kad/Cargo.toml +++ b/protocols/kad/Cargo.toml @@ -44,7 +44,7 @@ prost-build = "0.11" [features] serde = ["dep:serde", "bytes/serde"] -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/mdns/Cargo.toml b/protocols/mdns/Cargo.toml index 2612c453293..5729043514e 100644 --- a/protocols/mdns/Cargo.toml +++ b/protocols/mdns/Cargo.toml @@ -46,7 +46,7 @@ name = "use-tokio" required-features = ["tokio"] -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/ping/Cargo.toml b/protocols/ping/Cargo.toml index 06a7e6a6b21..c26dbb225b9 100644 --- a/protocols/ping/Cargo.toml +++ b/protocols/ping/Cargo.toml @@ -25,7 +25,7 @@ async-std = "1.6.2" libp2p = { path = "../..", features = ["full"] } quickcheck = { package = "quickcheck-ext", path = "../../misc/quickcheck-ext" } -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/relay/Cargo.toml b/protocols/relay/Cargo.toml index 1d63c8a9985..9c6e3528096 100644 --- a/protocols/relay/Cargo.toml +++ b/protocols/relay/Cargo.toml @@ -38,7 +38,7 @@ libp2p = { path = "../..", features = ["full"] } quickcheck = { package = "quickcheck-ext", path = "../../misc/quickcheck-ext" } clap = { version = "4.0.13", features = ["derive"] } -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/protocols/rendezvous/Cargo.toml b/protocols/rendezvous/Cargo.toml index 6d9076d6e6a..4f53d3cf23b 100644 --- a/protocols/rendezvous/Cargo.toml +++ b/protocols/rendezvous/Cargo.toml @@ -37,7 +37,7 @@ tokio = { version = "1.15", features = [ "rt-multi-thread", "time", "macros", "s [build-dependencies] prost-build = "0.11" -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true diff --git a/swarm/Cargo.toml b/swarm/Cargo.toml index c841445680a..75dd0968b16 100644 --- a/swarm/Cargo.toml +++ b/swarm/Cargo.toml @@ -30,7 +30,7 @@ env_logger = "0.9" libp2p = { path = "..", features = ["full"] } quickcheck = { package = "quickcheck-ext", path = "../misc/quickcheck-ext" } -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true From fe61298bee5f58c93a848d1584eb8c42484812e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 3 Nov 2022 10:55:25 +0000 Subject: [PATCH 53/60] review: re-introduce trailing whitespace for less review --- protocols/request-response/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/protocols/request-response/Cargo.toml b/protocols/request-response/Cargo.toml index dd9e373082b..63df7cd502a 100644 --- a/protocols/request-response/Cargo.toml +++ b/protocols/request-response/Cargo.toml @@ -28,7 +28,7 @@ env_logger = "0.9.0" libp2p = { path = "../..", features = ["full"] } rand = "0.8" -# Passing arguments to the docsrs builder in order to properly document cfg's. +# Passing arguments to the docsrs builder in order to properly document cfg's. # More information: https://docs.rs/about/builds#cross-compiling [package.metadata.docs.rs] all-features = true From 7c996365228ef4269c76298d6387a9e2a7995f4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 4 Nov 2022 13:33:58 +0000 Subject: [PATCH 54/60] review: address max suggestion, and insert backticks in the FromSwarm references. --- swarm-derive/src/lib.rs | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index 6e4fa535344..53817104c0a 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -191,7 +191,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::ConnectionEstablished variant. + // for the `FromSwarm::ConnectionEstablished` variant. let on_connection_established_stmts = { data_struct .fields @@ -206,7 +206,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::AddressChange variant. + // for the `FromSwarm::AddressChange variant`. let on_address_change_stmts = { data_struct .fields @@ -219,7 +219,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::ConnectionClosed variant. + // for the `FromSwarm::ConnectionClosed` variant. let on_connection_closed_stmts = { data_struct.fields .iter() @@ -251,7 +251,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::DialFailure variant. + // for the `FromSwarm::DialFailure` variant. let on_dial_failure_stmts = { data_struct .fields @@ -283,7 +283,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::ListenFailure variant. + // for the `FromSwarm::ListenFailure` variant. let on_listen_failure_stmts = { data_struct.fields .iter() @@ -312,7 +312,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::NewListener variant. + // for the `FromSwarm::NewListener` variant. let on_new_listener_stmts = { data_struct .fields @@ -325,7 +325,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::NewListenAddr variant. + // for the `FromSwarm::NewListenAddr` variant. let on_new_listen_addr_stmts = { data_struct .fields @@ -338,7 +338,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::ExpiredListenAddr variant. + // for the `FromSwarm::ExpiredListenAddr` variant. let on_expired_listen_addr_stmts = { data_struct .fields @@ -351,7 +351,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::NewExternalAddr variant. + // for the `FromSwarm::NewExternalAddr` variant. let on_new_external_addr_stmts = { data_struct .fields @@ -364,7 +364,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::ExpiredExternalAddr variant. + // for the `FromSwarm::ExpiredExternalAddr` variant. let on_expired_external_addr_stmts = { data_struct .fields @@ -377,7 +377,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::ListenerError variant. + // for the `FromSwarm::ListenerError` variant. let on_listener_error_stmts = { data_struct .fields @@ -390,7 +390,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; // Build the list of statements to put in the body of `on_swarm_event()` - // for the FromSwarm::ListenerClosed variant. + // for the `FromSwarm::ListenerClosed` variant. let on_listener_closed_stmts = { data_struct .fields From ba56bfd86514879764ce33582702da47d118d434 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 4 Nov 2022 14:56:11 +0000 Subject: [PATCH 55/60] review: nit, improve all variants matchingstyle --- protocols/dcutr/src/behaviour.rs | 18 +++++++++--------- protocols/floodsub/src/layer.rs | 20 ++++++++++---------- protocols/gossipsub/src/behaviour.rs | 18 +++++++++--------- protocols/identify/src/behaviour.rs | 14 +++++++------- protocols/kad/src/behaviour.rs | 10 +++++----- protocols/mdns/src/behaviour.rs | 20 ++++++++++---------- protocols/ping/src/lib.rs | 24 ++++++++++++------------ protocols/relay/src/v2/client.rs | 20 ++++++++++---------- protocols/relay/src/v2/relay.rs | 22 +++++++++++----------- 9 files changed, 83 insertions(+), 83 deletions(-) diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index deeb3a9ac10..df4aabfb4e8 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -326,15 +326,15 @@ impl NetworkBehaviour for Behaviour { self.on_connection_closed(connection_closed) } FromSwarm::DialFailure(dial_failure) => self.on_dial_failure(dial_failure), - FromSwarm::AddressChange(_) => {} - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListener(_) => {} - FromSwarm::NewListenAddr(_) => {} - FromSwarm::ExpiredListenAddr(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::NewExternalAddr(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::AddressChange(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index 0ee12ce166a..776c0e8551b 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -488,16 +488,16 @@ impl NetworkBehaviour for Floodsub { FromSwarm::ConnectionClosed(connection_closed) => { self.on_connection_closed(connection_closed) } - FromSwarm::AddressChange(_) => {} - FromSwarm::DialFailure(_) => {} - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListener(_) => {} - FromSwarm::NewListenAddr(_) => {} - FromSwarm::ExpiredListenAddr(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::NewExternalAddr(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index bb29fa42e39..b84aaab5908 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -3478,15 +3478,15 @@ where self.on_connection_closed(connection_closed) } FromSwarm::AddressChange(address_change) => self.on_address_change(address_change), - FromSwarm::DialFailure(_) => {} - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListener(_) => {} - FromSwarm::NewListenAddr(_) => {} - FromSwarm::ExpiredListenAddr(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::NewExternalAddr(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/identify/src/behaviour.rs b/protocols/identify/src/behaviour.rs index c825ad23404..04b9fef3b7e 100644 --- a/protocols/identify/src/behaviour.rs +++ b/protocols/identify/src/behaviour.rs @@ -447,13 +447,13 @@ impl NetworkBehaviour for Behaviour { self.pending_push.extend(self.connected.keys()); } } - FromSwarm::AddressChange(_) => {} - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListener(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::NewExternalAddr(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::AddressChange(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index 127efc4497b..b113deb64d5 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -2373,11 +2373,11 @@ where FromSwarm::NewListenAddr(NewListenAddr { addr, .. }) => { self.local_addrs.insert(addr.clone()); } - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListener(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index 4443458d917..9c635886b6b 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -159,16 +159,16 @@ where iface.fire_timer(); } } - FromSwarm::ConnectionEstablished(_) => {} - FromSwarm::DialFailure(_) => {} - FromSwarm::AddressChange(_) => {} - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListenAddr(_) => {} - FromSwarm::ExpiredListenAddr(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::NewExternalAddr(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::ConnectionEstablished(_) + | FromSwarm::DialFailure(_) + | FromSwarm::AddressChange(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } diff --git a/protocols/ping/src/lib.rs b/protocols/ping/src/lib.rs index 68a4ca6a7da..6e481500df9 100644 --- a/protocols/ping/src/lib.rs +++ b/protocols/ping/src/lib.rs @@ -152,18 +152,18 @@ impl NetworkBehaviour for Behaviour { event: libp2p_swarm::behaviour::FromSwarm, ) { match event { - FromSwarm::ConnectionEstablished(_) => {} - FromSwarm::ConnectionClosed(_) => {} - FromSwarm::AddressChange(_) => {} - FromSwarm::DialFailure(_) => {} - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListener(_) => {} - FromSwarm::NewListenAddr(_) => {} - FromSwarm::ExpiredListenAddr(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::NewExternalAddr(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::ConnectionEstablished(_) + | FromSwarm::ConnectionClosed(_) + | FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } } diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index bc339ee9e68..d9a2d977588 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -171,16 +171,16 @@ impl NetworkBehaviour for Client { FromSwarm::ConnectionClosed(connection_closed) => { self.on_connection_closed(connection_closed) } - FromSwarm::AddressChange(_) => {} - FromSwarm::DialFailure(_) => {} - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListener(_) => {} - FromSwarm::NewListenAddr(_) => {} - FromSwarm::ExpiredListenAddr(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::NewExternalAddr(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index 02dc0cd9972..788e45be97c 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -267,17 +267,17 @@ impl NetworkBehaviour for Relay { FromSwarm::ConnectionClosed(connection_closed) => { self.on_connection_closed(connection_closed) } - FromSwarm::ConnectionEstablished(_) => {} - FromSwarm::DialFailure(_) => {} - FromSwarm::AddressChange(_) => {} - FromSwarm::ListenFailure(_) => {} - FromSwarm::NewListener(_) => {} - FromSwarm::NewListenAddr(_) => {} - FromSwarm::ExpiredListenAddr(_) => {} - FromSwarm::ListenerError(_) => {} - FromSwarm::ListenerClosed(_) => {} - FromSwarm::NewExternalAddr(_) => {} - FromSwarm::ExpiredExternalAddr(_) => {} + FromSwarm::ConnectionEstablished(_) + | FromSwarm::DialFailure(_) + | FromSwarm::AddressChange(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} } } From 7d8a2b72c9c57af97565c974c6d6459be76d1883 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sun, 6 Nov 2022 13:11:20 +0000 Subject: [PATCH 56/60] review: replace inject_event on missing parts, and implement on_swarm_event for required types. --- protocols/rendezvous/src/client.rs | 18 ++++++++++++++++++ protocols/rendezvous/src/server.rs | 18 ++++++++++++++++++ swarm-derive/tests/test.rs | 18 ++++++++++++++++++ swarm/src/dummy.rs | 21 +++++++++++++++++++-- swarm/src/keep_alive.rs | 21 +++++++++++++++++++-- swarm/src/test.rs | 26 ++++++++++++++++++++++++++ 6 files changed, 118 insertions(+), 4 deletions(-) diff --git a/protocols/rendezvous/src/client.rs b/protocols/rendezvous/src/client.rs index 93115b5386b..80ff29add06 100644 --- a/protocols/rendezvous/src/client.rs +++ b/protocols/rendezvous/src/client.rs @@ -32,6 +32,7 @@ use libp2p_core::connection::ConnectionId; use libp2p_core::identity::error::SigningError; use libp2p_core::identity::Keypair; use libp2p_core::{Multiaddr, PeerId, PeerRecord}; +use libp2p_swarm::behaviour::FromSwarm; use libp2p_swarm::{ CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; @@ -265,6 +266,23 @@ impl NetworkBehaviour for Behaviour { Poll::Pending } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(_) + | FromSwarm::ConnectionClosed(_) + | FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} + } + } } fn handle_outbound_event( diff --git a/protocols/rendezvous/src/server.rs b/protocols/rendezvous/src/server.rs index e88de1d056c..560397943ce 100644 --- a/protocols/rendezvous/src/server.rs +++ b/protocols/rendezvous/src/server.rs @@ -29,6 +29,7 @@ use futures::stream::FuturesUnordered; use futures::{FutureExt, StreamExt}; use libp2p_core::connection::ConnectionId; use libp2p_core::PeerId; +use libp2p_swarm::behaviour::FromSwarm; use libp2p_swarm::{ CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; @@ -160,6 +161,23 @@ impl NetworkBehaviour for Behaviour { Poll::Pending } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(_) + | FromSwarm::ConnectionClosed(_) + | FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} + } + } } fn handle_inbound_event( diff --git a/swarm-derive/tests/test.rs b/swarm-derive/tests/test.rs index 439fe3ef030..90826240ddf 100644 --- a/swarm-derive/tests/test.rs +++ b/swarm-derive/tests/test.rs @@ -19,6 +19,7 @@ // DEALINGS IN THE SOFTWARE. use futures::prelude::*; +use libp2p::swarm::behaviour::FromSwarm; use libp2p::swarm::{dummy, NetworkBehaviour, SwarmEvent}; use libp2p::{identify, ping}; use libp2p_swarm_derive::*; @@ -390,6 +391,23 @@ fn custom_out_event_no_type_parameters() { ) -> Poll> { Poll::Pending } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(_) + | FromSwarm::ConnectionClosed(_) + | FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} + } + } } #[derive(NetworkBehaviour)] diff --git a/swarm/src/dummy.rs b/swarm/src/dummy.rs index 61f055915b3..6c51065a9e1 100644 --- a/swarm/src/dummy.rs +++ b/swarm/src/dummy.rs @@ -1,4 +1,4 @@ -use crate::behaviour::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use crate::behaviour::{FromSwarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters}; use crate::handler::{InboundUpgradeSend, OutboundUpgradeSend}; use crate::{ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol}; use libp2p_core::connection::ConnectionId; @@ -19,7 +19,7 @@ impl NetworkBehaviour for Behaviour { ConnectionHandler } - fn inject_event(&mut self, _: PeerId, _: ConnectionId, event: Void) { + fn on_connection_handler_event(&mut self, _: PeerId, _: ConnectionId, event: Void) { void::unreachable(event) } @@ -30,6 +30,23 @@ impl NetworkBehaviour for Behaviour { ) -> Poll> { Poll::Pending } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(_) + | FromSwarm::ConnectionClosed(_) + | FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} + } + } } /// An implementation of [`ConnectionHandler`] that neither handles any protocols nor does it keep the connection alive. diff --git a/swarm/src/keep_alive.rs b/swarm/src/keep_alive.rs index ea5d5ee6399..29a0eca1e21 100644 --- a/swarm/src/keep_alive.rs +++ b/swarm/src/keep_alive.rs @@ -1,4 +1,4 @@ -use crate::behaviour::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use crate::behaviour::{FromSwarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters}; use crate::handler::{ ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol, }; @@ -29,7 +29,7 @@ impl NetworkBehaviour for Behaviour { ConnectionHandler } - fn inject_event(&mut self, _: PeerId, _: ConnectionId, event: Void) { + fn on_connection_handler_event(&mut self, _: PeerId, _: ConnectionId, event: Void) { void::unreachable(event) } @@ -40,6 +40,23 @@ impl NetworkBehaviour for Behaviour { ) -> Poll> { Poll::Pending } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(_) + | FromSwarm::ConnectionClosed(_) + | FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} + } + } } /// Implementation of [`ConnectionHandler`] that doesn't handle anything but keeps the connection alive. diff --git a/swarm/src/test.rs b/swarm/src/test.rs index fa6a3ed533b..94a5fbfef54 100644 --- a/swarm/src/test.rs +++ b/swarm/src/test.rs @@ -87,6 +87,32 @@ where ) -> Poll> { self.next_action.take().map_or(Poll::Pending, Poll::Ready) } + + fn on_swarm_event(&mut self, event: FromSwarm) { + match event { + FromSwarm::ConnectionEstablished(_) + | FromSwarm::ConnectionClosed(_) + | FromSwarm::AddressChange(_) + | FromSwarm::DialFailure(_) + | FromSwarm::ListenFailure(_) + | FromSwarm::NewListener(_) + | FromSwarm::NewListenAddr(_) + | FromSwarm::ExpiredListenAddr(_) + | FromSwarm::ListenerError(_) + | FromSwarm::ListenerClosed(_) + | FromSwarm::NewExternalAddr(_) + | FromSwarm::ExpiredExternalAddr(_) => {} + } + } + + fn on_connection_handler_event( + &mut self, + _peer_id: PeerId, + _connection_id: ConnectionId, + _event: <::Handler as + ConnectionHandler>::OutEvent, + ) { + } } /// A `CallTraceBehaviour` is a `NetworkBehaviour` that tracks From b9baeb3f2167a86d5186224ad2b738d2f03e7f36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 7 Nov 2022 23:26:34 +0000 Subject: [PATCH 57/60] review: address Thomas suggestion --- CHANGELOG.md | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 744ca92ef4f..28bc6874eef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,12 +47,9 @@ # 0.50.0 - [unreleased] - Introduce [`libp2p-tls` `v0.1.0-alpha`](transports/tls/CHANGELOG.md#010-alpha). See [PR 2945]. - - Remove deprecated features: `tcp-tokio`, `mdns-tokio`, `dns-tokio`, `tcp-async-io`, `mdns-async-io`, `dns-async-std`. See [PR 3001]. - - Introduce [`libp2p-tls` `v0.1.0`](transports/tls/CHANGELOG.md#010). See [PR 2945]. - - Update individual crates. - Update to [`libp2p-autonat` `v0.89.0`](protocols/autonat/CHANGELOG.md#090). - Update to [`libp2p-core` `v0.38.0`](core/CHANGELOG.md#0380). @@ -79,21 +76,6 @@ - Update to [`libp2p-websocket` `v0.40.0`](transports/websocket/CHANGELOG.md#0400). - Update to [`libp2p-yamux` `v0.42.0`](muxers/yamux/CHANGELOG.md#0420). -- Add new `on_swarm_event` method to `NetworkBehaviour` that accepts a `FromSwarm` enum and update - `inject_*` methods to call `on_swarm_event` with the respective `FromSwarm` variant and deprecate - `inject_*`. - To migrate, users should replace the `NetworkBehaviour::inject_*` calls with a single - implementation of `NetworkBehaviour::on_swarm_event` treating each `FromSwarm` variant in - the same way its corresponding `inject_*` call was treated. - See [PR 3011]. - -- Add new `on_connection_handler_event` method with the same signature as `inject_event`, make the - default implementation of `inject_event` call `on_connection_handler_event` and deprecate it. - To migrate, users should replace the `NetworkBehaviour::inject_event` calls - with `NetworkBehaviour::on_connection_handler_event`. - See [PR 3011]. - -[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 [PR 2945]: https://github.com/libp2p/rust-libp2p/pull/2945 [PR 3001]: https://github.com/libp2p/rust-libp2p/pull/3001 [PR 2945]: https://github.com/libp2p/rust-libp2p/pull/2945 @@ -110,6 +92,7 @@ - `tcp-async-io` in favor of `tcp` + `async-std` - `mdns-async-io` in favor of `mdns` + `async-std` - `dns-async-std` in favor of `dns` + `async-std` + See [PR 2962]. - Update individual crates. From 73e0dcfcbda7555696f1bb51913527b3cae1acff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 14 Nov 2022 11:49:26 +0000 Subject: [PATCH 58/60] review: revert to call inject on inner types. --- swarm/src/behaviour.rs | 100 ++++++++++++++++++++++++++++++++++ swarm/src/behaviour/either.rs | 44 +++++++++------ swarm/src/behaviour/toggle.rs | 8 ++- 3 files changed, 132 insertions(+), 20 deletions(-) diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 438be1dc305..6240e570888 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -1111,3 +1111,103 @@ impl<'a, Handler: IntoConnectionHandler> FromSwarm<'a, Handler> { } } } + +/// Helper function to call [`NetworkBehaviour`]'s `inject_*` methods given a `FromSwarm. +/// TODO: Remove this function when we remove the remaining `inject_*` calls +/// from [`Either`] and [`Toggle`]. +pub(crate) fn inject_from_swarm( + behaviour: &mut T, + event: FromSwarm, +) { + match event { + FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + }) => { + #[allow(deprecated)] + behaviour.inject_connection_established( + &peer_id, + &connection_id, + endpoint, + Some(&failed_addresses.into()), + other_established, + ); + } + FromSwarm::ConnectionClosed(ConnectionClosed { + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + }) => { + #[allow(deprecated)] + behaviour.inject_connection_closed( + &peer_id, + &connection_id, + endpoint, + handler, + remaining_established, + ); + } + FromSwarm::AddressChange(AddressChange { + peer_id, + connection_id, + old, + new, + }) => { + #[allow(deprecated)] + behaviour.inject_address_change(&peer_id, &connection_id, old, new); + } + FromSwarm::DialFailure(DialFailure { + peer_id, + handler, + error, + }) => { + #[allow(deprecated)] + behaviour.inject_dial_failure(peer_id, handler, error); + } + FromSwarm::ListenFailure(ListenFailure { + local_addr, + send_back_addr, + handler, + }) => { + #[allow(deprecated)] + behaviour.inject_listen_failure(local_addr, send_back_addr, handler); + } + FromSwarm::NewListener(NewListener { listener_id }) => { + #[allow(deprecated)] + behaviour.inject_new_listener(listener_id); + } + FromSwarm::NewListenAddr(NewListenAddr { listener_id, addr }) => { + #[allow(deprecated)] + behaviour.inject_new_listen_addr(listener_id, addr); + } + FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id, addr }) => { + #[allow(deprecated)] + behaviour.inject_expired_listen_addr(listener_id, addr); + } + FromSwarm::ListenerError(ListenerError { listener_id, err }) => { + #[allow(deprecated)] + behaviour.inject_listener_error(listener_id, err); + } + FromSwarm::ListenerClosed(ListenerClosed { + listener_id, + reason, + }) => { + #[allow(deprecated)] + behaviour.inject_listener_closed(listener_id, reason); + } + FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => { + #[allow(deprecated)] + behaviour.inject_new_external_addr(addr); + } + FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }) => + { + #[allow(deprecated)] + behaviour.inject_expired_external_addr(addr) + } + } +} diff --git a/swarm/src/behaviour/either.rs b/swarm/src/behaviour/either.rs index 7c8171e5a9c..4154db1a0de 100644 --- a/swarm/src/behaviour/either.rs +++ b/swarm/src/behaviour/either.rs @@ -18,7 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::behaviour::{self, NetworkBehaviour, NetworkBehaviourAction, PollParameters}; +use crate::behaviour::{ + self, inject_from_swarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters, +}; use crate::handler::either::IntoEitherHandler; use either::Either; use libp2p_core::{Multiaddr, PeerId}; @@ -49,20 +51,26 @@ where fn on_swarm_event(&mut self, event: behaviour::FromSwarm) { match self { - Either::Left(b) => b.on_swarm_event(event.map_handler( - |h| h.unwrap_left(), - |h| match h { - Either::Left(h) => h, - Either::Right(_) => unreachable!(), - }, - )), - Either::Right(b) => b.on_swarm_event(event.map_handler( - |h| h.unwrap_right(), - |h| match h { - Either::Right(h) => h, - Either::Left(_) => unreachable!(), - }, - )), + Either::Left(b) => inject_from_swarm( + b, + event.map_handler( + |h| h.unwrap_left(), + |h| match h { + Either::Left(h) => h, + Either::Right(_) => unreachable!(), + }, + ), + ), + Either::Right(b) => inject_from_swarm( + b, + event.map_handler( + |h| h.unwrap_right(), + |h| match h { + Either::Right(h) => h, + Either::Left(_) => unreachable!(), + }, + ), + ), } } @@ -74,10 +82,12 @@ where ) { match (self, event) { (Either::Left(left), Either::Left(event)) => { - left.on_connection_handler_event(peer_id, connection_id, event) + #[allow(deprecated)] + left.inject_event(peer_id, connection_id, event); } (Either::Right(right), Either::Right(event)) => { - right.on_connection_handler_event(peer_id, connection_id, event) + #[allow(deprecated)] + right.inject_event(peer_id, connection_id, event); } _ => unreachable!(), } diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index c4e1b2bf560..4b01138a596 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -18,6 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. +use crate::behaviour::{inject_from_swarm, FromSwarm}; use crate::handler::{ ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, KeepAlive, SubstreamProtocol, @@ -82,10 +83,10 @@ where .unwrap_or_else(Vec::new) } - fn on_swarm_event(&mut self, event: super::FromSwarm) { + fn on_swarm_event(&mut self, event: FromSwarm) { if let Some(behaviour) = &mut self.inner { if let Some(event) = event.maybe_map_handler(|h| h.inner, |h| h.inner) { - behaviour.on_swarm_event(event); + inject_from_swarm(behaviour, event); } } } @@ -97,7 +98,8 @@ where event: crate::THandlerOutEvent, ) { if let Some(behaviour) = &mut self.inner { - behaviour.on_connection_handler_event(peer_id, connection_id, event) + #[allow(deprecated)] + behaviour.inject_event(peer_id, connection_id, event) } } From f0fd82a574bbf7f71fc6f3d3f419811aab50b5f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 15 Nov 2022 12:35:55 +0000 Subject: [PATCH 59/60] review: revert swarm-derive to call inject on inner types. --- swarm-derive/src/lib.rs | 180 ++++++++++++++++++++++++++-------------- 1 file changed, 116 insertions(+), 64 deletions(-) diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index 7a75a4e69e0..625cc7b499f 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -187,10 +187,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event( - #from_swarm::ConnectionEstablished(#connection_established { peer_id, connection_id, endpoint, failed_addresses, other_established}));}, - None => quote! { self.#field_n.on_swarm_event( - #from_swarm::ConnectionEstablished(#connection_established { peer_id, connection_id, endpoint, failed_addresses, other_established}));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_connection_established(&peer_id, &connection_id, endpoint, Some(&failed_addresses.into()), other_established);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_connection_established(&peer_id, &connection_id, endpoint, Some(&failed_addresses.into()), other_established);}, }) }; @@ -202,8 +204,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::AddressChange(#address_change { peer_id, connection_id, old, new }));}, - None => quote! { self.#field_n.on_swarm_event(#from_swarm::AddressChange(#address_change { peer_id, connection_id, old, new }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_address_change(&peer_id, &connection_id, old, new);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_address_change(&peer_id, &connection_id, old, new);}, }) }; @@ -226,10 +232,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { } }; let on = match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event( - #from_swarm::ConnectionClosed(#connection_closed { peer_id, connection_id, endpoint, handler, remaining_established }));}, - None => quote! { self.#enum_n.on_swarm_event( - #from_swarm::ConnectionClosed(#connection_closed { peer_id, connection_id, endpoint, handler, remaining_established }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_connection_closed(&peer_id, &connection_id, endpoint, handler, remaining_established);}, + None => quote! { + #[allow(deprecated)] + self.#enum_n.inject_connection_closed(&peer_id, &connection_id, endpoint, handler, remaining_established);}, }; quote! { @@ -260,8 +268,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; let on = match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::DialFailure(#dial_failure { peer_id, handler, error }));}, - None => quote! { self.#enum_n.on_swarm_event(#from_swarm::DialFailure(#dial_failure { peer_id, handler, error }));} + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_dial_failure(peer_id, handler, error);}, + None => quote! { + #[allow(deprecated)] + self.#enum_n.inject_dial_failure(peer_id, handler, error);}, }; quote! { @@ -273,32 +285,34 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { // Build the list of statements to put in the body of `on_swarm_event()` // for the `FromSwarm::ListenFailure` variant. - let on_listen_failure_stmts = { - data_struct.fields - .iter() - .enumerate() - .rev() - .enumerate() - .map(|(enum_n, (field_n, field))| { - let handler = if field_n == 0 { - quote! { let handler = handlers } - } else { - quote! { - let (handlers, handler) = handlers.into_inner() - } - }; + let on_listen_failure_stmts = + { + data_struct.fields.iter().enumerate().rev().enumerate().map( + |(enum_n, (field_n, field))| { + let handler = if field_n == 0 { + quote! { let handler = handlers } + } else { + quote! { + let (handlers, handler) = handlers.into_inner() + } + }; - let on = match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ListenFailure(#listen_failure { local_addr, send_back_addr, handler }));}, - None => quote! { self.#enum_n.on_swarm_event(#from_swarm::ListenFailure(#listen_failure { local_addr, send_back_addr, handler }));}, - }; + let on = match field.ident { + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_listen_failure(local_addr, send_back_addr, handler);}, + None => quote! { + #[allow(deprecated)] + self.#enum_n.inject_listen_failure(local_addr, send_back_addr, handler);}, + }; - quote! { - #handler; - #on; - } - }) - }; + quote! { + #handler; + #on; + } + }, + ) + }; // Build the list of statements to put in the body of `on_swarm_event()` // for the `FromSwarm::NewListener` variant. @@ -308,8 +322,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::NewListener(#new_listener { listener_id }));}, - None => quote! { self.#field_n.on_swarm_event(#from_swarm::NewListener(#new_listener { listener_id }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_new_listener(listener_id);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_new_listener(listener_id);}, }) }; @@ -321,8 +339,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::NewListenAddr(#new_listen_addr { listener_id, addr }));}, - None => quote! { self.#field_n.on_swarm_event(#from_swarm::NewListenAddr(#new_listen_addr { listener_id, addr }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_new_listen_addr(listener_id, addr);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_new_listen_addr(listener_id, addr);}, }) }; @@ -334,8 +356,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ExpiredListenAddr(#expired_listen_addr { listener_id, addr }));}, - None => quote! { self.#field_n.on_swarm_event(#from_swarm::ExpiredListenAddr(#expired_listen_addr { listener_id, addr }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_expired_listen_addr(listener_id, addr);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_expired_listen_addr(listener_id, addr);}, }) }; @@ -347,8 +373,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::NewExternalAddr(#new_external_addr { addr }));}, - None => quote! { self.#field_n.on_swarm_event(#from_swarm::NewExternalAddr(#new_external_addr { addr }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_new_external_addr(addr);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_new_external_addr(addr);}, }) }; @@ -360,8 +390,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ExpiredExternalAddr(#expired_external_addr { addr }));}, - None => quote! { self.#field_n.on_swarm_event(#from_swarm::ExpiredExternalAddr(#expired_external_addr { addr }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_expired_external_addr(addr);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_expired_external_addr(addr);}, }) }; @@ -373,8 +407,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ListenerError(#listener_error { listener_id, err }));}, - None => quote!{self.#field_n.on_swarm_event(#from_swarm::ListenerError(#listener_error { listener_id, err }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_listener_error(listener_id, err);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_listener_error(listener_id, err);}, }) }; @@ -386,8 +424,12 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .iter() .enumerate() .map(|(field_n, field)| match field.ident { - Some(ref i) => quote! { self.#i.on_swarm_event(#from_swarm::ListenerClosed(#listener_closed { listener_id, reason }));}, - None => quote!{self.#field_n.on_swarm_event(#from_swarm::ListenerClosed(#listener_closed { listener_id, reason }));}, + Some(ref i) => quote! { + #[allow(deprecated)] + self.#i.inject_listener_closed(listener_id, reason);}, + None => quote! { + #[allow(deprecated)] + self.#field_n.inject_listener_closed(listener_id, reason);}, }) }; @@ -395,22 +437,32 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { // // The event type is a construction of nested `#either_ident`s of the events of the children. // We call `on_connection_handler_event` on the corresponding child. - let on_node_event_stmts = data_struct.fields.iter().enumerate().enumerate().map(|(enum_n, (field_n, field))| { - let mut elem = if enum_n != 0 { - quote!{ #either_ident::Second(ev) } - } else { - quote!{ ev } - }; + let on_node_event_stmts = + data_struct + .fields + .iter() + .enumerate() + .enumerate() + .map(|(enum_n, (field_n, field))| { + let mut elem = if enum_n != 0 { + quote! { #either_ident::Second(ev) } + } else { + quote! { ev } + }; - for _ in 0 .. data_struct.fields.len() - 1 - enum_n { - elem = quote!{ #either_ident::First(#elem) }; - } + for _ in 0..data_struct.fields.len() - 1 - enum_n { + elem = quote! { #either_ident::First(#elem) }; + } - Some(match field.ident { - Some(ref i) => quote!{ #elem => #trait_to_impl::on_connection_handler_event(&mut self.#i, peer_id, connection_id, ev) }, - None => quote!{ #elem => #trait_to_impl::on_connection_handler_event(&mut self.#field_n, peer_id, connection_id, ev) }, - }) - }); + Some(match field.ident { + Some(ref i) => quote! { #elem => { + #[allow(deprecated)] + #trait_to_impl::inject_event(&mut self.#i, peer_id, connection_id, ev) }}, + None => quote! { #elem => { + #[allow(deprecated)] + #trait_to_impl::inject_event(&mut self.#field_n, peer_id, connection_id, ev) }}, + }) + }); // The [`ConnectionHandler`] associated type. let connection_handler_ty = { From dcf82356d0361d3581e0e98cddb71a60f6f27bc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 15 Nov 2022 12:54:28 +0000 Subject: [PATCH 60/60] review: revert missing var names on swarm-derive. --- swarm-derive/src/lib.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index 625cc7b499f..4af70e6a84a 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -231,7 +231,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { let (handlers, handler) = handlers.into_inner() } }; - let on = match field.ident { + let inject = match field.ident { Some(ref i) => quote! { #[allow(deprecated)] self.#i.inject_connection_closed(&peer_id, &connection_id, endpoint, handler, remaining_established);}, @@ -242,7 +242,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { quote! { #handler; - #on; + #inject; } }) }; @@ -267,7 +267,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { } }; - let on = match field.ident { + let inject = match field.ident { Some(ref i) => quote! { #[allow(deprecated)] self.#i.inject_dial_failure(peer_id, handler, error);}, @@ -278,7 +278,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { quote! { #handler; - #on; + #inject; } }) }; @@ -297,7 +297,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { } }; - let on = match field.ident { + let inject = match field.ident { Some(ref i) => quote! { #[allow(deprecated)] self.#i.inject_listen_failure(local_addr, send_back_addr, handler);}, @@ -308,7 +308,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { quote! { #handler; - #on; + #inject; } }, )