From c0bf8848e7f580e0a9d3324f4340b5e936e160ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 17 Dec 2022 20:47:15 +0000 Subject: [PATCH 01/11] rendezvous: rename SubstreamHandler::inject_event to on_event --- protocols/rendezvous/src/handler/inbound.rs | 2 +- protocols/rendezvous/src/handler/outbound.rs | 2 +- protocols/rendezvous/src/substream_handler.rs | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/protocols/rendezvous/src/handler/inbound.rs b/protocols/rendezvous/src/handler/inbound.rs index aba68bd1bea..5ed2e4052ab 100644 --- a/protocols/rendezvous/src/handler/inbound.rs +++ b/protocols/rendezvous/src/handler/inbound.rs @@ -97,7 +97,7 @@ impl SubstreamHandler for Stream { Stream::PendingRead(Framed::new(substream, RendezvousCodec::default())) } - fn inject_event(self, event: Self::InEvent) -> Self { + fn on_event(self, event: Self::InEvent) -> Self { match (event, self) { (InEvent::RegisterResponse { ttl }, Stream::PendingBehaviour(substream)) => { Stream::PendingSend(substream, Message::RegisterResponse(Ok(ttl))) diff --git a/protocols/rendezvous/src/handler/outbound.rs b/protocols/rendezvous/src/handler/outbound.rs index d461e7c7294..d80bcdeb82a 100644 --- a/protocols/rendezvous/src/handler/outbound.rs +++ b/protocols/rendezvous/src/handler/outbound.rs @@ -94,7 +94,7 @@ impl SubstreamHandler for Stream { })) } - fn inject_event(self, event: Self::InEvent) -> Self { + fn on_event(self, event: Self::InEvent) -> Self { void::unreachable(event) } diff --git a/protocols/rendezvous/src/substream_handler.rs b/protocols/rendezvous/src/substream_handler.rs index f57dfded6c9..5ccf5243e16 100644 --- a/protocols/rendezvous/src/substream_handler.rs +++ b/protocols/rendezvous/src/substream_handler.rs @@ -52,7 +52,7 @@ pub trait SubstreamHandler: Sized { fn upgrade(open_info: Self::OpenInfo) -> SubstreamProtocol; fn new(substream: NegotiatedSubstream, info: Self::OpenInfo) -> Self; - fn inject_event(self, event: Self::InEvent) -> Self; + fn on_event(self, event: Self::InEvent) -> Self; fn advance(self, cx: &mut Context<'_>) -> Result, Self::Error>; } @@ -395,7 +395,7 @@ where InEvent::NotifyInboundSubstream { id, message } => { match self.inbound_substreams.remove(&id) { Some(handler) => { - let new_handler = handler.inject_event(message); + let new_handler = handler.on_event(message); self.inbound_substreams.insert(id, new_handler); } @@ -407,7 +407,7 @@ where InEvent::NotifyOutboundSubstream { id, message } => { match self.outbound_substreams.remove(&id) { Some(handler) => { - let new_handler = handler.inject_event(message); + let new_handler = handler.on_event(message); self.outbound_substreams.insert(id, new_handler); } @@ -537,7 +537,7 @@ impl SubstreamHandler for void::Void { unreachable!("we should never yield a substream") } - fn inject_event(self, event: Self::InEvent) -> Self { + fn on_event(self, event: Self::InEvent) -> Self { void::unreachable(event) } From 29f488289c706d60f912c7f35e4bb68da887773f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 17 Dec 2022 21:37:58 +0000 Subject: [PATCH 02/11] rendezvous: replace inject_* methods with on_* on SubstreamHandler. --- protocols/rendezvous/src/substream_handler.rs | 63 ++++++++++--------- 1 file changed, 33 insertions(+), 30 deletions(-) diff --git a/protocols/rendezvous/src/substream_handler.rs b/protocols/rendezvous/src/substream_handler.rs index 5ccf5243e16..16a493ccc3a 100644 --- a/protocols/rendezvous/src/substream_handler.rs +++ b/protocols/rendezvous/src/substream_handler.rs @@ -29,10 +29,9 @@ use futures::future::{self, BoxFuture, Fuse, FusedFuture}; use futures::FutureExt; use instant::Instant; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; -use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend}; +use libp2p_swarm::handler::{ConnectionEvent, FullyNegotiatedInbound, FullyNegotiatedOutbound}; use libp2p_swarm::{ - ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, - NegotiatedSubstream, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, KeepAlive, NegotiatedSubstream, SubstreamProtocol, }; use std::collections::{HashMap, VecDeque}; use std::fmt; @@ -367,29 +366,41 @@ where TInboundSubstreamHandler::upgrade(()) } - fn inject_fully_negotiated_inbound( + fn on_connection_event( &mut self, - protocol: ::Output, - _: Self::InboundOpenInfo, - ) { - self.inbound_substreams.insert( - self.next_inbound_substream_id.fetch_and_increment(), - TInboundSubstreamHandler::new(protocol, ()), - ); - } - - fn inject_fully_negotiated_outbound( - &mut self, - protocol: ::Output, - info: Self::OutboundOpenInfo, + event: ConnectionEvent< + Self::InboundProtocol, + Self::OutboundProtocol, + Self::InboundOpenInfo, + Self::OutboundOpenInfo, + >, ) { - self.outbound_substreams.insert( - self.next_outbound_substream_id.fetch_and_increment(), - TOutboundSubstreamHandler::new(protocol, info), - ); + match event { + ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { + protocol, .. + }) => { + self.inbound_substreams.insert( + self.next_inbound_substream_id.fetch_and_increment(), + TInboundSubstreamHandler::new(protocol, ()), + ); + } + ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { + protocol, + info, + }) => { + self.outbound_substreams.insert( + self.next_outbound_substream_id.fetch_and_increment(), + TOutboundSubstreamHandler::new(protocol, info), + ); + } + // TODO: Handle upgrade errors properly + ConnectionEvent::AddressChange(_) + | ConnectionEvent::ListenUpgradeError(_) + | ConnectionEvent::DialUpgradeError(_) => {} + } } - fn inject_event(&mut self, event: Self::InEvent) { + fn on_behaviour_event(&mut self, event: Self::InEvent) { match event { InEvent::NewSubstream { open_info } => self.new_substreams.push_back(open_info), InEvent::NotifyInboundSubstream { id, message } => { @@ -419,14 +430,6 @@ where } } - fn inject_dial_upgrade_error( - &mut self, - _: Self::OutboundOpenInfo, - _: ConnectionHandlerUpgrErr, - ) { - // TODO: Handle upgrade errors properly - } - fn connection_keep_alive(&self) -> KeepAlive { // Rudimentary keep-alive handling, to be extended as needed as this abstraction is used more by other protocols. From 61d3535782ba85fffc554233823b51d78fa53b14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Sat, 17 Dec 2022 21:48:56 +0000 Subject: [PATCH 03/11] dcutr: remove dangling inject_ methods for Handler --- protocols/dcutr/src/handler/direct.rs | 27 ++------------------------- 1 file changed, 2 insertions(+), 25 deletions(-) diff --git a/protocols/dcutr/src/handler/direct.rs b/protocols/dcutr/src/handler/direct.rs index f0fdf5930ac..9e6759977ad 100644 --- a/protocols/dcutr/src/handler/direct.rs +++ b/protocols/dcutr/src/handler/direct.rs @@ -21,11 +21,11 @@ //! [`ConnectionHandler`] handling direct connection upgraded through a relayed connection. use libp2p_core::connection::ConnectionId; -use libp2p_core::upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade}; +use libp2p_core::upgrade::DeniedUpgrade; use libp2p_swarm::handler::ConnectionEvent; use libp2p_swarm::{ ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, - NegotiatedSubstream, SubstreamProtocol, + SubstreamProtocol, }; use std::task::{Context, Poll}; use void::Void; @@ -62,31 +62,8 @@ impl ConnectionHandler for Handler { SubstreamProtocol::new(DeniedUpgrade, ()) } - fn inject_fully_negotiated_inbound( - &mut self, - _: >::Output, - _: Self::InboundOpenInfo, - ) { - } - - fn inject_fully_negotiated_outbound( - &mut self, - _: >::Output, - _: Self::OutboundOpenInfo, - ) { - } - fn on_behaviour_event(&mut self, _: Self::InEvent) {} - fn inject_dial_upgrade_error( - &mut self, - _: Self::OutboundOpenInfo, - _: ConnectionHandlerUpgrErr< - >::Error, - >, - ) { - } - fn connection_keep_alive(&self) -> KeepAlive { KeepAlive::No } From 500283a083d402b1cb40564cecddd586032e3901 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Mon, 19 Dec 2022 19:16:53 +0000 Subject: [PATCH 04/11] swarm: remove inject_ methods from ConnectionHandler. --- protocols/request-response/src/handler.rs | 2 +- swarm/src/behaviour.rs | 31 +-- swarm/src/behaviour/toggle.rs | 71 ++--- swarm/src/connection.rs | 94 ++++--- swarm/src/handler.rs | 103 +------ swarm/src/handler/either.rs | 244 ++++++++++------- swarm/src/handler/map_in.rs | 38 +-- swarm/src/handler/map_out.rs | 38 +-- swarm/src/handler/multi.rs | 320 ++++++++++++---------- swarm/src/handler/select.rs | 230 +++++++++------- 10 files changed, 575 insertions(+), 596 deletions(-) diff --git a/protocols/request-response/src/handler.rs b/protocols/request-response/src/handler.rs index 3eba5b10c77..50cd6adb055 100644 --- a/protocols/request-response/src/handler.rs +++ b/protocols/request-response/src/handler.rs @@ -366,7 +366,7 @@ where Err(oneshot::Canceled) => { // The inbound upgrade has errored or timed out reading // or waiting for the request. The handler is informed - // via `inject_listen_upgrade_error`. + // via `on_connection_event` call with `ConnectionEvent::ListenUpgradeError`. } } } diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 141d6c3efbd..a0496cefc92 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -586,28 +586,17 @@ pub enum NetworkBehaviourAction< /// # SubstreamProtocol::new(DeniedUpgrade, ()) /// # } /// # - /// # fn inject_fully_negotiated_inbound( - /// # &mut self, - /// # _: >::Output, - /// # _: Self::InboundOpenInfo, - /// # ) { - /// # } - /// # - /// # fn inject_fully_negotiated_outbound( - /// # &mut self, - /// # _: >::Output, - /// # _: Self::OutboundOpenInfo, - /// # ) { - /// # } - /// # - /// # fn inject_event(&mut self, _event: Self::InEvent) {} + /// # fn on_behaviour_event(&mut self, _event: Self::InEvent) {} /// # - /// # fn inject_dial_upgrade_error( - /// # &mut self, - /// # _: Self::OutboundOpenInfo, - /// # _: ConnectionHandlerUpgrErr, - /// # ) { - /// # } + /// # fn on_connection_event( + /// # &mut self, + /// # event: ConnectionEvent< + /// # Self::InboundProtocol, + /// # Self::OutboundProtocol, + /// # Self::InboundOpenInfo, + /// # Self::OutboundOpenInfo, + /// # >, + /// # ) {} /// # /// # fn connection_keep_alive(&self) -> KeepAlive { /// # KeepAlive::Yes diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index 81255a40274..f36969bebe8 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -20,9 +20,9 @@ use crate::behaviour::{inject_from_swarm, FromSwarm}; use crate::handler::{ - ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, - DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, IntoConnectionHandler, - KeepAlive, ListenUpgradeError, SubstreamProtocol, + AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, + ConnectionHandlerUpgrErr, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, + IntoConnectionHandler, KeepAlive, ListenUpgradeError, SubstreamProtocol, }; use crate::upgrade::SendWrapper; use crate::{NetworkBehaviour, NetworkBehaviourAction, PollParameters}; @@ -99,8 +99,7 @@ where event: crate::THandlerOutEvent, ) { if let Some(behaviour) = &mut self.inner { - #[allow(deprecated)] - behaviour.inject_event(peer_id, connection_id, event) + behaviour.on_connection_handler_event(peer_id, connection_id, event) } } @@ -176,13 +175,17 @@ where }; if let Either::Left(info) = info { - #[allow(deprecated)] self.inner .as_mut() .expect("Can't receive an inbound substream if disabled; QED") - .inject_fully_negotiated_inbound(out, info) + .on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { + protocol: out, + info, + }, + )); } else { - panic!("Unexpected Either::Right in enabled `inject_fully_negotiated_inbound`.") + panic!("Unexpected Either::Right in enabled `on_fully_negotiated_inbound`.") } } @@ -199,11 +202,11 @@ where (None, Either::Right(())) => return, (Some(_), Either::Right(())) => panic!( "Unexpected `Either::Right` inbound info through \ - `inject_listen_upgrade_error` in enabled state.", + `on_listen_upgrade_error` in enabled state.", ), (None, Either::Left(_)) => panic!( "Unexpected `Either::Left` inbound info through \ - `inject_listen_upgrade_error` in disabled state.", + `on_listen_upgrade_error` in disabled state.", ), }; @@ -218,8 +221,10 @@ where } }; - #[allow(deprecated)] - inner.inject_listen_upgrade_error(info, err) + inner.on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info, + error: err, + })); } } @@ -251,11 +256,10 @@ where } fn on_behaviour_event(&mut self, event: Self::InEvent) { - #[allow(deprecated)] self.inner .as_mut() .expect("Can't receive events if disabled; QED") - .inject_event(event) + .on_behaviour_event(event) } fn connection_keep_alive(&self) -> KeepAlive { @@ -299,28 +303,31 @@ where ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { protocol: out, info, - }) => - { - #[allow(deprecated)] - self.inner - .as_mut() - .expect("Can't receive an outbound substream if disabled; QED") - .inject_fully_negotiated_outbound(out, info) - } + }) => self + .inner + .as_mut() + .expect("Can't receive an outbound substream if disabled; QED") + .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { + protocol: out, + info, + }, + )), ConnectionEvent::AddressChange(address_change) => { if let Some(inner) = self.inner.as_mut() { - #[allow(deprecated)] - inner.inject_address_change(address_change.new_address) + inner.on_connection_event(ConnectionEvent::AddressChange(AddressChange { + new_address: address_change.new_address, + })); } } - ConnectionEvent::DialUpgradeError(DialUpgradeError { info, error: err }) => - { - #[allow(deprecated)] - self.inner - .as_mut() - .expect("Can't receive an outbound substream if disabled; QED") - .inject_dial_upgrade_error(info, err) - } + ConnectionEvent::DialUpgradeError(DialUpgradeError { info, error: err }) => self + .inner + .as_mut() + .expect("Can't receive an outbound substream if disabled; QED") + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: err, + })), ConnectionEvent::ListenUpgradeError(listen_upgrade_error) => { self.on_listen_upgrade_error(listen_upgrade_error) } diff --git a/swarm/src/connection.rs b/swarm/src/connection.rs index 272f78f3a6b..15a414c01e4 100644 --- a/swarm/src/connection.rs +++ b/swarm/src/connection.rs @@ -27,7 +27,10 @@ pub use error::{ PendingOutboundConnectionError, }; -use crate::handler::ConnectionHandler; +use crate::handler::{ + AddressChange, ConnectionEvent, ConnectionHandler, DialUpgradeError, FullyNegotiatedInbound, + FullyNegotiatedOutbound, ListenUpgradeError, +}; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; use crate::{ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol}; use futures::stream::FuturesUnordered; @@ -150,8 +153,7 @@ where /// Notifies the connection handler of an event. pub fn on_behaviour_event(&mut self, event: THandler::InEvent) { - #[allow(deprecated)] - self.handler.inject_event(event); + self.handler.on_behaviour_event(event); } /// Begins an orderly shutdown of the connection, returning the connection @@ -180,9 +182,13 @@ where loop { match requested_substreams.poll_next_unpin(cx) { Poll::Ready(Some(Ok(()))) => continue, - Poll::Ready(Some(Err(user_data))) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error(user_data, ConnectionHandlerUpgrErr::Timeout); + Poll::Ready(Some(Err(info))) => { + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + }, + )); continue; } Poll::Ready(None) | Poll::Pending => {} @@ -209,14 +215,16 @@ where // In case the [`ConnectionHandler`] can not make any more progress, poll the negotiating outbound streams. match negotiating_out.poll_next_unpin(cx) { Poll::Pending | Poll::Ready(None) => {} - Poll::Ready(Some((user_data, Ok(upgrade)))) => { - #[allow(deprecated)] - handler.inject_fully_negotiated_outbound(upgrade, user_data); + Poll::Ready(Some((info, Ok(protocol)))) => { + handler.on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { protocol, info }, + )); continue; } - Poll::Ready(Some((user_data, Err(err)))) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error(user_data, err); + Poll::Ready(Some((info, Err(error)))) => { + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { info, error }, + )); continue; } } @@ -225,14 +233,16 @@ where // make any more progress, poll the negotiating inbound streams. match negotiating_in.poll_next_unpin(cx) { Poll::Pending | Poll::Ready(None) => {} - Poll::Ready(Some((user_data, Ok(upgrade)))) => { - #[allow(deprecated)] - handler.inject_fully_negotiated_inbound(upgrade, user_data); + Poll::Ready(Some((info, Ok(protocol)))) => { + handler.on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { protocol, info }, + )); continue; } - Poll::Ready(Some((user_data, Err(err)))) => { - #[allow(deprecated)] - handler.inject_listen_upgrade_error(user_data, err); + Poll::Ready(Some((info, Err(error)))) => { + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { info, error }, + )); continue; } } @@ -279,8 +289,9 @@ where match muxing.poll_unpin(cx)? { Poll::Pending => {} Poll::Ready(StreamMuxerEvent::AddressChange(address)) => { - #[allow(deprecated)] - handler.inject_address_change(&address); + handler.on_connection_event(ConnectionEvent::AddressChange(AddressChange { + new_address: &address, + })); return Poll::Ready(Ok(Event::AddressChange(address))); } } @@ -757,34 +768,35 @@ mod tests { SubstreamProtocol::new(DeniedUpgrade, ()).with_timeout(self.upgrade_timeout) } - fn inject_fully_negotiated_inbound( + fn on_connection_event( &mut self, - protocol: ::Output, - _: Self::InboundOpenInfo, - ) { - void::unreachable(protocol) - } - - fn inject_fully_negotiated_outbound( - &mut self, - protocol: ::Output, - _: Self::OutboundOpenInfo, + event: ConnectionEvent< + Self::InboundProtocol, + Self::OutboundProtocol, + Self::InboundOpenInfo, + Self::OutboundOpenInfo, + >, ) { - void::unreachable(protocol) + match event { + ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { + protocol, + .. + }) => void::unreachable(protocol), + ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { + protocol, + .. + }) => void::unreachable(protocol), + ConnectionEvent::DialUpgradeError(DialUpgradeError { error, .. }) => { + self.error = Some(error) + } + ConnectionEvent::AddressChange(_) | ConnectionEvent::ListenUpgradeError(_) => {} + } } - fn inject_event(&mut self, event: Self::InEvent) { + fn on_behaviour_event(&mut self, event: Self::InEvent) { void::unreachable(event) } - fn inject_dial_upgrade_error( - &mut self, - _: Self::OutboundOpenInfo, - error: ConnectionHandlerUpgrErr<::Error>, - ) { - self.error = Some(error) - } - fn connection_keep_alive(&self) -> KeepAlive { KeepAlive::Yes } diff --git a/swarm/src/handler.rs b/swarm/src/handler.rs index 2a4e1d44483..f60e94e2465 100644 --- a/swarm/src/handler.rs +++ b/swarm/src/handler.rs @@ -116,102 +116,6 @@ pub trait ConnectionHandler: Send + 'static { /// > This allows a remote to put the list of supported protocols in a cache. fn listen_protocol(&self) -> SubstreamProtocol; - /// Injects the output of a successful upgrade on a new inbound substream. - /// - /// Note that it is up to the [`ConnectionHandler`] implementation to manage the lifetime of the - /// negotiated inbound substreams. E.g. the implementation has to enforce a limit on the number - /// of simultaneously open negotiated inbound substreams. In other words it is up to the - /// [`ConnectionHandler`] implementation to stop a malicious remote node to open and keep alive - /// an excessive amount of inbound substreams. - #[deprecated( - since = "0.41.0", - note = "Handle `ConnectionEvent::FullyNegotiatedInbound` on `ConnectionHandler::on_connection_event` instead. - The default implemention of this `inject_*` method delegates to it." - )] - fn inject_fully_negotiated_inbound( - &mut self, - protocol: ::Output, - info: Self::InboundOpenInfo, - ) { - self.on_connection_event(ConnectionEvent::FullyNegotiatedInbound( - FullyNegotiatedInbound { protocol, info }, - )) - } - - /// Injects the output of a successful upgrade on a new outbound substream. - /// - /// The second argument is the information that was previously passed to - /// [`ConnectionHandlerEvent::OutboundSubstreamRequest`]. - #[deprecated( - since = "0.41.0", - note = "Handle `ConnectionEvent::FullyNegotiatedOutbound` on `ConnectionHandler::on_connection_event` instead. - The default implemention of this `inject_*` method delegates to it." - )] - fn inject_fully_negotiated_outbound( - &mut self, - protocol: ::Output, - info: Self::OutboundOpenInfo, - ) { - self.on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( - FullyNegotiatedOutbound { protocol, info }, - )) - } - - /// Injects an event coming from the outside in the handler. - #[deprecated( - since = "0.41.0", - note = "Implement `ConnectionHandler::on_behaviour_event` instead. The default implementation of `inject_event` delegates to it." - )] - fn inject_event(&mut self, event: Self::InEvent) { - self.on_behaviour_event(event); - } - - /// Notifies the handler of a change in the address of the remote. - #[deprecated( - since = "0.41.0", - note = "Handle `ConnectionEvent::AddressChange` on `ConnectionHandler::on_connection_event` instead. - The default implemention of this `inject_*` method delegates to it." - )] - fn inject_address_change(&mut self, new_address: &Multiaddr) { - self.on_connection_event(ConnectionEvent::AddressChange(AddressChange { - new_address, - })) - } - - /// Indicates to the handler that upgrading an outbound substream to the given protocol has failed. - #[deprecated( - since = "0.41.0", - note = "Handle `ConnectionEvent::DialUpgradeError` on `ConnectionHandler::on_connection_event` instead. - The default implemention of this `inject_*` method delegates to it." - )] - fn inject_dial_upgrade_error( - &mut self, - info: Self::OutboundOpenInfo, - error: ConnectionHandlerUpgrErr<::Error>, - ) { - self.on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error, - })) - } - - /// Indicates to the handler that upgrading an inbound substream to the given protocol has failed. - #[deprecated( - since = "0.41.0", - note = "Handle `ConnectionEvent::ListenUpgradeError` on `ConnectionHandler::on_connection_event` instead. - The default implemention of this `inject_*` method delegates to it." - )] - fn inject_listen_upgrade_error( - &mut self, - info: Self::InboundOpenInfo, - error: ConnectionHandlerUpgrErr<::Error>, - ) { - self.on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - info, - error, - })) - } - /// Returns until when the connection should be kept alive. /// /// This method is called by the `Swarm` after each invocation of @@ -279,18 +183,17 @@ pub trait ConnectionHandler: Send + 'static { } /// Informs the handler about an event from the [`NetworkBehaviour`](super::NetworkBehaviour). - fn on_behaviour_event(&mut self, _event: Self::InEvent) {} + fn on_behaviour_event(&mut self, _event: Self::InEvent); fn on_connection_event( &mut self, - _event: ConnectionEvent< + event: ConnectionEvent< Self::InboundProtocol, Self::OutboundProtocol, Self::InboundOpenInfo, Self::OutboundOpenInfo, >, - ) { - } + ); } /// Enumeration with the list of the possible stream events diff --git a/swarm/src/handler/either.rs b/swarm/src/handler/either.rs index e6d16ed1133..c718f5432a6 100644 --- a/swarm/src/handler/either.rs +++ b/swarm/src/handler/either.rs @@ -19,9 +19,9 @@ // DEALINGS IN THE SOFTWARE. use crate::handler::{ - AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, - ConnectionHandlerUpgrErr, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, - IntoConnectionHandler, KeepAlive, ListenUpgradeError, SubstreamProtocol, + ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, + DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, IntoConnectionHandler, + KeepAlive, ListenUpgradeError, SubstreamProtocol, }; use crate::upgrade::SendWrapper; use either::Either; @@ -122,10 +122,8 @@ where fn on_behaviour_event(&mut self, event: Self::InEvent) { match (self, event) { - #[allow(deprecated)] - (Either::Left(handler), Either::Left(event)) => handler.inject_event(event), - #[allow(deprecated)] - (Either::Right(handler), Either::Right(event)) => handler.inject_event(event), + (Either::Left(handler), Either::Left(event)) => handler.on_behaviour_event(event), + (Either::Right(handler), Either::Right(event)) => handler.on_behaviour_event(event), _ => unreachable!(), } } @@ -178,15 +176,21 @@ where protocol: output, info, }) => match (self, output, info) { - (Either::Left(handler), EitherOutput::First(output), Either::Left(info)) => - { - #[allow(deprecated)] - handler.inject_fully_negotiated_outbound(output, info) + (Either::Left(handler), EitherOutput::First(output), Either::Left(info)) => { + handler.on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { + protocol: output, + info, + }, + )); } - (Either::Right(handler), EitherOutput::Second(output), Either::Right(info)) => - { - #[allow(deprecated)] - handler.inject_fully_negotiated_outbound(output, info) + (Either::Right(handler), EitherOutput::Second(output), Either::Right(info)) => { + handler.on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { + protocol: output, + info, + }, + )); } _ => unreachable!(), }, @@ -194,62 +198,92 @@ where protocol: output, info, }) => match (self, output, info) { - (Either::Left(handler), EitherOutput::First(output), Either::Left(info)) => - { - #[allow(deprecated)] - handler.inject_fully_negotiated_inbound(output, info) + (Either::Left(handler), EitherOutput::First(output), Either::Left(info)) => { + handler.on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { + protocol: output, + info, + }, + )); } - (Either::Right(handler), EitherOutput::Second(output), Either::Right(info)) => - { - #[allow(deprecated)] - handler.inject_fully_negotiated_inbound(output, info) + (Either::Right(handler), EitherOutput::Second(output), Either::Right(info)) => { + handler.on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { + protocol: output, + info, + }, + )); } _ => unreachable!(), }, - ConnectionEvent::AddressChange(AddressChange { new_address: addr }) => match self { - #[allow(deprecated)] - Either::Left(handler) => handler.inject_address_change(addr), - #[allow(deprecated)] - Either::Right(handler) => handler.inject_address_change(addr), + ConnectionEvent::AddressChange(address_change) => match self { + Either::Left(handler) => { + handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) + } + Either::Right(handler) => { + handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) + } }, ConnectionEvent::DialUpgradeError(DialUpgradeError { info, error }) => match error { ConnectionHandlerUpgrErr::Timer => match (self, info) { (Either::Left(handler), Either::Left(info)) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer); + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timer, + }, + )); } (Either::Right(handler), Either::Right(info)) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer); + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timer, + }, + )); } _ => unreachable!(), }, ConnectionHandlerUpgrErr::Timeout => match (self, info) { (Either::Left(handler), Either::Left(info)) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout); + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + }, + )); } (Either::Right(handler), Either::Right(info)) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout); + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + }, + )); } _ => unreachable!(), }, ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => { match (self, info) { (Either::Left(handler), Either::Left(info)) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - ); + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + error, + )), + }, + )); } (Either::Right(handler), Either::Right(info)) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - ); + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + error, + )), + }, + )); } _ => unreachable!(), } @@ -257,11 +291,14 @@ where ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { match (self, info) { (Either::Left(handler), Either::Left(info)) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), - ); + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply( + e, + )), + }, + )); } _ => unreachable!(), } @@ -269,11 +306,14 @@ where ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { match (self, info) { (Either::Right(handler), Either::Right(info)) => { - #[allow(deprecated)] - handler.inject_dial_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), - ); + handler.on_connection_event(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply( + e, + )), + }, + )); } _ => unreachable!(), } @@ -283,49 +323,63 @@ where match error { ConnectionHandlerUpgrErr::Timer => match (self, info) { (Either::Left(handler), Either::Left(info)) => { - #[allow(deprecated)] - handler - .inject_listen_upgrade_error(info, ConnectionHandlerUpgrErr::Timer); + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timer, + }, + )); } (Either::Right(handler), Either::Right(info)) => { - #[allow(deprecated)] - handler - .inject_listen_upgrade_error(info, ConnectionHandlerUpgrErr::Timer); + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timer, + }, + )); } _ => unreachable!(), }, ConnectionHandlerUpgrErr::Timeout => match (self, info) { (Either::Left(handler), Either::Left(info)) => { - #[allow(deprecated)] - handler.inject_listen_upgrade_error( - info, - ConnectionHandlerUpgrErr::Timeout, - ); + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + }, + )); } (Either::Right(handler), Either::Right(info)) => { - #[allow(deprecated)] - handler.inject_listen_upgrade_error( - info, - ConnectionHandlerUpgrErr::Timeout, - ); + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + }, + )); } _ => unreachable!(), }, ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => { match (self, info) { (Either::Left(handler), Either::Left(info)) => { - #[allow(deprecated)] - handler.inject_listen_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - ); + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade( + UpgradeError::Select(error), + ), + }, + )); } (Either::Right(handler), Either::Right(info)) => { - #[allow(deprecated)] - handler.inject_listen_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - ); + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade( + UpgradeError::Select(error), + ), + }, + )); } _ => unreachable!(), } @@ -333,11 +387,14 @@ where ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { match (self, info) { (Either::Left(handler), Either::Left(info)) => { - #[allow(deprecated)] - handler.inject_listen_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), - ); + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade( + UpgradeError::Apply(e), + ), + }, + )); } _ => unreachable!(), } @@ -345,11 +402,14 @@ where ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { match (self, info) { (Either::Right(handler), Either::Right(info)) => { - #[allow(deprecated)] - handler.inject_listen_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), - ); + handler.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade( + UpgradeError::Apply(e), + ), + }, + )); } _ => unreachable!(), } diff --git a/swarm/src/handler/map_in.rs b/swarm/src/handler/map_in.rs index 326a6f8f4f9..3564de919bb 100644 --- a/swarm/src/handler/map_in.rs +++ b/swarm/src/handler/map_in.rs @@ -19,9 +19,7 @@ // DEALINGS IN THE SOFTWARE. use crate::handler::{ - AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError, - FullyNegotiatedInbound, FullyNegotiatedOutbound, KeepAlive, ListenUpgradeError, - SubstreamProtocol, + ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, KeepAlive, SubstreamProtocol, }; use std::{fmt::Debug, marker::PhantomData, task::Context, task::Poll}; @@ -65,8 +63,7 @@ where fn on_behaviour_event(&mut self, event: TNewIn) { if let Some(event) = (self.map)(event) { - #[allow(deprecated)] - self.inner.inject_event(event); + self.inner.on_behaviour_event(event); } } @@ -97,35 +94,6 @@ where Self::OutboundOpenInfo, >, ) { - match event { - ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { protocol, info }) => - { - #[allow(deprecated)] - self.inner.inject_fully_negotiated_inbound(protocol, info) - } - ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { - protocol, - info, - }) => - { - #[allow(deprecated)] - self.inner.inject_fully_negotiated_outbound(protocol, info) - } - ConnectionEvent::AddressChange(AddressChange { new_address }) => - { - #[allow(deprecated)] - self.inner.inject_address_change(new_address) - } - ConnectionEvent::DialUpgradeError(DialUpgradeError { info, error }) => - { - #[allow(deprecated)] - self.inner.inject_dial_upgrade_error(info, error) - } - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { info, error }) => - { - #[allow(deprecated)] - self.inner.inject_listen_upgrade_error(info, error) - } - } + self.inner.on_connection_event(event); } } diff --git a/swarm/src/handler/map_out.rs b/swarm/src/handler/map_out.rs index 87306dc48c6..773df2b6681 100644 --- a/swarm/src/handler/map_out.rs +++ b/swarm/src/handler/map_out.rs @@ -19,9 +19,7 @@ // DEALINGS IN THE SOFTWARE. use crate::handler::{ - AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, DialUpgradeError, - FullyNegotiatedInbound, FullyNegotiatedOutbound, KeepAlive, ListenUpgradeError, - SubstreamProtocol, + ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, KeepAlive, SubstreamProtocol, }; use std::fmt::Debug; use std::task::{Context, Poll}; @@ -59,8 +57,7 @@ where } fn on_behaviour_event(&mut self, event: Self::InEvent) { - #[allow(deprecated)] - self.inner.inject_event(event) + self.inner.on_behaviour_event(event) } fn connection_keep_alive(&self) -> KeepAlive { @@ -96,35 +93,6 @@ where Self::OutboundOpenInfo, >, ) { - match event { - ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { protocol, info }) => - { - #[allow(deprecated)] - self.inner.inject_fully_negotiated_inbound(protocol, info) - } - ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { - protocol, - info, - }) => - { - #[allow(deprecated)] - self.inner.inject_fully_negotiated_outbound(protocol, info) - } - ConnectionEvent::AddressChange(AddressChange { new_address }) => - { - #[allow(deprecated)] - self.inner.inject_address_change(new_address) - } - ConnectionEvent::DialUpgradeError(DialUpgradeError { info, error }) => - { - #[allow(deprecated)] - self.inner.inject_dial_upgrade_error(info, error) - } - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { info, error }) => - { - #[allow(deprecated)] - self.inner.inject_listen_upgrade_error(info, error) - } - } + self.inner.on_connection_event(event); } } diff --git a/swarm/src/handler/multi.rs b/swarm/src/handler/multi.rs index d80b51c52a8..35f0ebd7995 100644 --- a/swarm/src/handler/multi.rs +++ b/swarm/src/handler/multi.rs @@ -22,14 +22,15 @@ //! indexed by some key. use crate::handler::{ - ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, - KeepAlive, SubstreamProtocol, + AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, + ConnectionHandlerUpgrErr, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, + IntoConnectionHandler, KeepAlive, ListenUpgradeError, SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, UpgradeInfoSend}; use crate::NegotiatedSubstream; use futures::{future::BoxFuture, prelude::*}; use libp2p_core::upgrade::{NegotiationError, ProtocolError, ProtocolName, UpgradeError}; -use libp2p_core::{ConnectedPoint, Multiaddr, PeerId}; +use libp2p_core::{ConnectedPoint, PeerId}; use rand::Rng; use std::{ cmp, @@ -62,7 +63,7 @@ where impl MultiHandler where - K: Hash + Eq, + K: Clone + Debug + Hash + Eq + Send + 'static, H: ConnectionHandler, { /// Create and populate a `MultiHandler` from the given handler iterator. @@ -82,134 +83,50 @@ where )?; Ok(m) } -} - -impl ConnectionHandler for MultiHandler -where - K: Clone + Debug + Hash + Eq + Send + 'static, - H: ConnectionHandler, - H::InboundProtocol: InboundUpgradeSend, - H::OutboundProtocol: OutboundUpgradeSend, -{ - type InEvent = (K, ::InEvent); - type OutEvent = (K, ::OutEvent); - type Error = ::Error; - type InboundProtocol = Upgrade::InboundProtocol>; - type OutboundProtocol = ::OutboundProtocol; - type InboundOpenInfo = Info::InboundOpenInfo>; - type OutboundOpenInfo = (K, ::OutboundOpenInfo); - - fn listen_protocol(&self) -> SubstreamProtocol { - let (upgrade, info, timeout) = self - .handlers - .iter() - .map(|(key, handler)| { - let proto = handler.listen_protocol(); - let timeout = *proto.timeout(); - let (upgrade, info) = proto.into_upgrade(); - (key.clone(), (upgrade, info, timeout)) - }) - .fold( - (Upgrade::new(), Info::new(), Duration::from_secs(0)), - |(mut upg, mut inf, mut timeout), (k, (u, i, t))| { - upg.upgrades.push((k.clone(), u)); - inf.infos.push((k, i)); - timeout = cmp::max(timeout, t); - (upg, inf, timeout) - }, - ); - SubstreamProtocol::new(upgrade, info).with_timeout(timeout) - } - - fn inject_fully_negotiated_outbound( - &mut self, - protocol: ::Output, - (key, arg): Self::OutboundOpenInfo, - ) { - if let Some(h) = self.handlers.get_mut(&key) { - #[allow(deprecated)] - h.inject_fully_negotiated_outbound(protocol, arg) - } else { - log::error!("inject_fully_negotiated_outbound: no handler for key") - } - } - - fn inject_fully_negotiated_inbound( - &mut self, - (key, arg): ::Output, - mut info: Self::InboundOpenInfo, - ) { - if let Some(h) = self.handlers.get_mut(&key) { - if let Some(i) = info.take(&key) { - #[allow(deprecated)] - h.inject_fully_negotiated_inbound(arg, i) - } - } else { - log::error!("inject_fully_negotiated_inbound: no handler for key") - } - } - - fn on_behaviour_event(&mut self, (key, event): Self::InEvent) { - if let Some(h) = self.handlers.get_mut(&key) { - #[allow(deprecated)] - h.inject_event(event) - } else { - log::error!("inject_event: no handler for key") - } - } - - fn inject_address_change(&mut self, addr: &Multiaddr) { - for h in self.handlers.values_mut() { - #[allow(deprecated)] - h.inject_address_change(addr) - } - } - - fn inject_dial_upgrade_error( - &mut self, - (key, arg): Self::OutboundOpenInfo, - error: ConnectionHandlerUpgrErr<::Error>, - ) { - if let Some(h) = self.handlers.get_mut(&key) { - #[allow(deprecated)] - h.inject_dial_upgrade_error(arg, error) - } else { - log::error!("inject_dial_upgrade_error: no handler for protocol") - } - } - fn inject_listen_upgrade_error( + fn on_listen_upgrade_error( &mut self, - mut info: Self::InboundOpenInfo, - error: ConnectionHandlerUpgrErr<::Error>, + ListenUpgradeError { error, mut info }: ListenUpgradeError< + ::InboundOpenInfo, + ::InboundProtocol, + >, ) { match error { ConnectionHandlerUpgrErr::Timer => { for (k, h) in &mut self.handlers { if let Some(i) = info.take(k) { - #[allow(deprecated)] - h.inject_listen_upgrade_error(i, ConnectionHandlerUpgrErr::Timer) + h.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info: i, + error: ConnectionHandlerUpgrErr::Timer, + }, + )); } } } ConnectionHandlerUpgrErr::Timeout => { for (k, h) in &mut self.handlers { if let Some(i) = info.take(k) { - #[allow(deprecated)] - h.inject_listen_upgrade_error(i, ConnectionHandlerUpgrErr::Timeout) + h.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info: i, + error: ConnectionHandlerUpgrErr::Timeout, + }, + )); } } } ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { for (k, h) in &mut self.handlers { if let Some(i) = info.take(k) { - #[allow(deprecated)] - h.inject_listen_upgrade_error( - i, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( - NegotiationError::Failed, - )), - ) + h.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info: i, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + NegotiationError::Failed, + )), + }, + )); } } } @@ -222,11 +139,14 @@ where let e = NegotiationError::ProtocolError(ProtocolError::IoError( e.kind().into(), )); - #[allow(deprecated)] - h.inject_listen_upgrade_error( - i, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), - ) + h.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info: i, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + e, + )), + }, + )); } } } @@ -234,11 +154,14 @@ where for (k, h) in &mut self.handlers { if let Some(i) = info.take(k) { let e = NegotiationError::ProtocolError(ProtocolError::InvalidMessage); - #[allow(deprecated)] - h.inject_listen_upgrade_error( - i, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), - ) + h.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info: i, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + e, + )), + }, + )); } } } @@ -246,11 +169,14 @@ where for (k, h) in &mut self.handlers { if let Some(i) = info.take(k) { let e = NegotiationError::ProtocolError(ProtocolError::InvalidProtocol); - #[allow(deprecated)] - h.inject_listen_upgrade_error( - i, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), - ) + h.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info: i, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + e, + )), + }, + )); } } } @@ -259,11 +185,14 @@ where if let Some(i) = info.take(k) { let e = NegotiationError::ProtocolError(ProtocolError::TooManyProtocols); - #[allow(deprecated)] - h.inject_listen_upgrade_error( - i, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), - ) + h.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info: i, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + e, + )), + }, + )); } } } @@ -271,16 +200,131 @@ where ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply((k, e))) => { if let Some(h) = self.handlers.get_mut(&k) { if let Some(i) = info.take(&k) { - #[allow(deprecated)] - h.inject_listen_upgrade_error( - i, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), - ) + h.on_connection_event(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + info: i, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + }, + )); } } } } } +} + +impl ConnectionHandler for MultiHandler +where + K: Clone + Debug + Hash + Eq + Send + 'static, + H: ConnectionHandler, + H::InboundProtocol: InboundUpgradeSend, + H::OutboundProtocol: OutboundUpgradeSend, +{ + type InEvent = (K, ::InEvent); + type OutEvent = (K, ::OutEvent); + type Error = ::Error; + type InboundProtocol = Upgrade::InboundProtocol>; + type OutboundProtocol = ::OutboundProtocol; + type InboundOpenInfo = Info::InboundOpenInfo>; + type OutboundOpenInfo = (K, ::OutboundOpenInfo); + + fn listen_protocol(&self) -> SubstreamProtocol { + let (upgrade, info, timeout) = self + .handlers + .iter() + .map(|(key, handler)| { + let proto = handler.listen_protocol(); + let timeout = *proto.timeout(); + let (upgrade, info) = proto.into_upgrade(); + (key.clone(), (upgrade, info, timeout)) + }) + .fold( + (Upgrade::new(), Info::new(), Duration::from_secs(0)), + |(mut upg, mut inf, mut timeout), (k, (u, i, t))| { + upg.upgrades.push((k.clone(), u)); + inf.infos.push((k, i)); + timeout = cmp::max(timeout, t); + (upg, inf, timeout) + }, + ); + SubstreamProtocol::new(upgrade, info).with_timeout(timeout) + } + + fn on_connection_event( + &mut self, + event: ConnectionEvent< + Self::InboundProtocol, + Self::OutboundProtocol, + Self::InboundOpenInfo, + Self::OutboundOpenInfo, + >, + ) { + match event { + ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { + protocol, + info: (key, arg), + }) => { + if let Some(h) = self.handlers.get_mut(&key) { + h.on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { + protocol, + info: arg, + }, + )); + } else { + log::error!("FullyNegotiatedOutbound: no handler for key") + } + } + ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { + protocol: (key, arg), + mut info, + }) => { + if let Some(h) = self.handlers.get_mut(&key) { + if let Some(i) = info.take(&key) { + h.on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { + protocol: arg, + info: i, + }, + )); + } + } else { + log::error!("FullyNegotiatedInbound: no handler for key") + } + } + ConnectionEvent::AddressChange(AddressChange { new_address }) => { + for h in self.handlers.values_mut() { + h.on_connection_event(ConnectionEvent::AddressChange(AddressChange { + new_address, + })); + } + } + ConnectionEvent::DialUpgradeError(DialUpgradeError { + info: (key, arg), + error, + }) => { + if let Some(h) = self.handlers.get_mut(&key) { + h.on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info: arg, + error, + })); + } else { + log::error!("DialUpgradeError: no handler for protocol") + } + } + ConnectionEvent::ListenUpgradeError(listen_upgrade_error) => { + self.on_listen_upgrade_error(listen_upgrade_error) + } + } + } + + fn on_behaviour_event(&mut self, (key, event): Self::InEvent) { + if let Some(h) = self.handlers.get_mut(&key) { + h.on_behaviour_event(event) + } else { + log::error!("on_behaviour_event: no handler for key") + } + } fn connection_keep_alive(&self) -> KeepAlive { self.handlers diff --git a/swarm/src/handler/select.rs b/swarm/src/handler/select.rs index 65508c0b6a5..6a60e9099b9 100644 --- a/swarm/src/handler/select.rs +++ b/swarm/src/handler/select.rs @@ -19,9 +19,9 @@ // DEALINGS IN THE SOFTWARE. use crate::handler::{ - ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, - DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, IntoConnectionHandler, - KeepAlive, ListenUpgradeError, SubstreamProtocol, + AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, + ConnectionHandlerUpgrErr, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, + IntoConnectionHandler, KeepAlive, ListenUpgradeError, SubstreamProtocol, }; use crate::upgrade::SendWrapper; @@ -114,15 +114,17 @@ where >, ) { match (protocol, endpoint) { - (EitherOutput::First(protocol), EitherOutput::First(info)) => - { - #[allow(deprecated)] - self.proto1.inject_fully_negotiated_outbound(protocol, info) + (EitherOutput::First(protocol), EitherOutput::First(info)) => { + self.proto1 + .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { protocol, info }, + )); } - (EitherOutput::Second(protocol), EitherOutput::Second(info)) => - { - #[allow(deprecated)] - self.proto2.inject_fully_negotiated_outbound(protocol, info) + (EitherOutput::Second(protocol), EitherOutput::Second(info)) => { + self.proto2 + .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { protocol, info }, + )); } (EitherOutput::First(_), EitherOutput::Second(_)) => { panic!("wrong API usage: the protocol doesn't match the upgrade info") @@ -144,15 +146,17 @@ where >, ) { match protocol { - EitherOutput::First(protocol) => - { - #[allow(deprecated)] - self.proto1.inject_fully_negotiated_inbound(protocol, i1) + EitherOutput::First(protocol) => { + self.proto1 + .on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { protocol, info: i1 }, + )); } - EitherOutput::Second(protocol) => - { - #[allow(deprecated)] - self.proto2.inject_fully_negotiated_inbound(protocol, i2) + EitherOutput::Second(protocol) => { + self.proto2 + .on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { protocol, info: i2 }, + )); } } } @@ -165,60 +169,72 @@ where >, ) { match (info, error) { - #[allow(deprecated)] (EitherOutput::First(info), ConnectionHandlerUpgrErr::Timer) => self .proto1 - .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer), - #[allow(deprecated)] + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timer, + })), (EitherOutput::First(info), ConnectionHandlerUpgrErr::Timeout) => self .proto1 - .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout), - #[allow(deprecated)] + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + })), ( EitherOutput::First(info), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), - ) => self.proto1.inject_dial_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), - ), - #[allow(deprecated)] + ) => self + .proto1 + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + })), ( EitherOutput::First(info), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(err))), - ) => self.proto1.inject_dial_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), - ), + ) => self + .proto1 + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), + })), ( EitherOutput::First(_), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(_))), ) => { panic!("Wrong API usage; the upgrade error doesn't match the outbound open info"); } - #[allow(deprecated)] (EitherOutput::Second(info), ConnectionHandlerUpgrErr::Timeout) => self .proto2 - .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout), - #[allow(deprecated)] + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + })), (EitherOutput::Second(info), ConnectionHandlerUpgrErr::Timer) => self .proto2 - .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer), - #[allow(deprecated)] + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timer, + })), ( EitherOutput::Second(info), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), - ) => self.proto2.inject_dial_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), - ), - #[allow(deprecated)] + ) => self + .proto2 + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + })), ( EitherOutput::Second(info), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(err))), - ) => self.proto2.inject_dial_upgrade_error( - info, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), - ), + ) => self + .proto2 + .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), + })), ( EitherOutput::Second(_), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(_))), @@ -240,36 +256,47 @@ where ) { match error { ConnectionHandlerUpgrErr::Timer => { - #[allow(deprecated)] self.proto1 - .inject_listen_upgrade_error(i1, ConnectionHandlerUpgrErr::Timer); - #[allow(deprecated)] + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i1, + error: ConnectionHandlerUpgrErr::Timer, + })); + self.proto2 - .inject_listen_upgrade_error(i2, ConnectionHandlerUpgrErr::Timer) + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i2, + error: ConnectionHandlerUpgrErr::Timer, + })); } ConnectionHandlerUpgrErr::Timeout => { - #[allow(deprecated)] self.proto1 - .inject_listen_upgrade_error(i1, ConnectionHandlerUpgrErr::Timeout); - #[allow(deprecated)] + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i1, + error: ConnectionHandlerUpgrErr::Timeout, + })); + self.proto2 - .inject_listen_upgrade_error(i2, ConnectionHandlerUpgrErr::Timeout) + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i2, + error: ConnectionHandlerUpgrErr::Timeout, + })); } ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { - #[allow(deprecated)] - self.proto1.inject_listen_upgrade_error( - i1, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( - NegotiationError::Failed, - )), - ); - #[allow(deprecated)] - self.proto2.inject_listen_upgrade_error( - i2, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( - NegotiationError::Failed, - )), - ); + self.proto1 + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i1, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + NegotiationError::Failed, + )), + })); + + self.proto2 + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i2, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( + NegotiationError::Failed, + )), + })); } ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( NegotiationError::ProtocolError(e), @@ -295,32 +322,30 @@ where e2 = NegotiationError::ProtocolError(ProtocolError::TooManyProtocols) } } - #[allow(deprecated)] - self.proto1.inject_listen_upgrade_error( - i1, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e1)), - ); - #[allow(deprecated)] - self.proto2.inject_listen_upgrade_error( - i2, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e2)), - ) + self.proto1 + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i1, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e1)), + })); + self.proto2 + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i2, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e2)), + })); } - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => - { - #[allow(deprecated)] - self.proto1.inject_listen_upgrade_error( - i1, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), - ) + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { + self.proto1 + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i1, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + })); } - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => - { - #[allow(deprecated)] - self.proto2.inject_listen_upgrade_error( - i2, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), - ) + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { + self.proto2 + .on_connection_event(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + info: i2, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + })); } } } @@ -357,10 +382,8 @@ where fn on_behaviour_event(&mut self, event: Self::InEvent) { match event { - #[allow(deprecated)] - EitherOutput::First(event) => self.proto1.inject_event(event), - #[allow(deprecated)] - EitherOutput::Second(event) => self.proto2.inject_event(event), + EitherOutput::First(event) => self.proto1.on_behaviour_event(event), + EitherOutput::Second(event) => self.proto2.on_behaviour_event(event), } } @@ -436,10 +459,15 @@ where self.on_fully_negotiated_inbound(fully_negotiated_inbound) } ConnectionEvent::AddressChange(address) => { - #[allow(deprecated)] - self.proto1.inject_address_change(address.new_address); - #[allow(deprecated)] - self.proto2.inject_address_change(address.new_address) + self.proto1 + .on_connection_event(ConnectionEvent::AddressChange(AddressChange { + new_address: address.new_address, + })); + + self.proto2 + .on_connection_event(ConnectionEvent::AddressChange(AddressChange { + new_address: address.new_address, + })); } ConnectionEvent::DialUpgradeError(dial_upgrade_error) => { self.on_dial_upgrade_error(dial_upgrade_error) From d29a8c90090026a7274482d7ab8fb0f71a15febb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Tue, 20 Dec 2022 00:16:06 +0000 Subject: [PATCH 05/11] swarm: remove inject_ methods from NetworkBehaviour, swarm-derive: remove inject methods from derive macro. --- protocols/relay/src/v2/client.rs | 2 +- swarm-derive/src/lib.rs | 192 +++++++++++++----- swarm/CHANGELOG.md | 4 + swarm/src/behaviour.rs | 333 ++----------------------------- swarm/src/behaviour/either.rs | 44 ++-- swarm/src/behaviour/toggle.rs | 4 +- swarm/src/lib.rs | 207 +++++++++++-------- swarm/src/test.rs | 93 +++++---- 8 files changed, 353 insertions(+), 526 deletions(-) diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index d9a2d977588..75a5c22d2ca 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -138,7 +138,7 @@ impl Client { } } hash_map::Entry::Vacant(_) => { - unreachable!("`inject_connection_closed` for unconnected peer.") + unreachable!("`on_connection_closed` for unconnected peer.") } }; } diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index b142ea77c67..489ec8c7bc6 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -188,11 +188,23 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_connection_established(&peer_id, &connection_id, endpoint, Some(&failed_addresses.into()), other_established);}, + self.#i.on_swarm_event(#from_swarm::ConnectionEstablished(#connection_established { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_connection_established(&peer_id, &connection_id, endpoint, Some(&failed_addresses.into()), other_established);}, + self.#field_n.on_swarm_event(#from_swarm::ConnectionEstablished(#connection_established { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + })); + }, }) }; @@ -205,18 +217,29 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_address_change(&peer_id, &connection_id, old, new);}, + self.#i.on_swarm_event(#from_swarm::AddressChange(#address_change { + peer_id, + connection_id, + old, + new, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_address_change(&peer_id, &connection_id, old, new);}, + 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 `on_swarm_event()` // for the `FromSwarm::ConnectionClosed` variant. let on_connection_closed_stmts = { - data_struct.fields + data_struct + .fields .iter() .enumerate() // The outmost handler belongs to the last behaviour. @@ -233,11 +256,23 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }; let inject = match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_connection_closed(&peer_id, &connection_id, endpoint, handler, remaining_established);}, + self.#i.on_swarm_event(#from_swarm::ConnectionClosed(#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);}, + self.#enum_n.on_swarm_event(#from_swarm::ConnectionClosed(#connection_closed { + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + })); + }, }; quote! { @@ -269,13 +304,20 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { let inject = match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_dial_failure(peer_id, handler, error);}, + self.#i.on_swarm_event(#from_swarm::DialFailure(#dial_failure { + peer_id, + handler, + error, + })); + }, None => quote! { - #[allow(deprecated)] - self.#enum_n.inject_dial_failure(peer_id, handler, error);}, + self.#enum_n.on_swarm_event(#from_swarm::DialFailure(#dial_failure { + peer_id, + handler, + error, + })); + }, }; - quote! { #handler; #inject; @@ -299,11 +341,19 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { let inject = match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_listen_failure(local_addr, send_back_addr, handler);}, + self.#i.on_swarm_event(#from_swarm::ListenFailure(#listen_failure { + local_addr, + send_back_addr, + handler, + })); + }, None => quote! { - #[allow(deprecated)] - self.#enum_n.inject_listen_failure(local_addr, send_back_addr, handler);}, + self.#enum_n.on_swarm_event(#from_swarm::ListenFailure(#listen_failure { + local_addr, + send_back_addr, + handler, + })); + }, }; quote! { @@ -323,11 +373,15 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_new_listener(listener_id);}, + self.#i.on_swarm_event(#from_swarm::NewListener(#new_listener { + listener_id, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_new_listener(listener_id);}, + self.#field_n.on_swarm_event(#from_swarm::NewListener(#new_listener { + listener_id, + })); + }, }) }; @@ -340,11 +394,17 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_new_listen_addr(listener_id, addr);}, + self.#i.on_swarm_event(#from_swarm::NewListenAddr(#new_listen_addr { + listener_id, + addr, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_new_listen_addr(listener_id, addr);}, + self.#field_n.on_swarm_event(#from_swarm::NewListenAddr(#new_listen_addr { + listener_id, + addr, + })); + }, }) }; @@ -357,11 +417,17 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_expired_listen_addr(listener_id, addr);}, + self.#i.on_swarm_event(#from_swarm::ExpiredListenAddr(#expired_listen_addr { + listener_id, + addr, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_expired_listen_addr(listener_id, addr);}, + self.#field_n.on_swarm_event(#from_swarm::ExpiredListenAddr(#expired_listen_addr { + listener_id, + addr, + })); + }, }) }; @@ -374,11 +440,15 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_new_external_addr(addr);}, + self.#i.on_swarm_event(#from_swarm::NewExternalAddr(#new_external_addr { + addr, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_new_external_addr(addr);}, + self.#field_n.on_swarm_event(#from_swarm::NewExternalAddr(#new_external_addr { + addr, + })); + }, }) }; @@ -391,11 +461,15 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_expired_external_addr(addr);}, + self.#i.on_swarm_event(#from_swarm::ExpiredExternalAddr(#expired_external_addr { + addr, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_expired_external_addr(addr);}, + self.#field_n.on_swarm_event(#from_swarm::ExpiredExternalAddr(#expired_external_addr { + addr, + })); + }, }) }; @@ -408,11 +482,17 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_listener_error(listener_id, err);}, + self.#i.on_swarm_event(#from_swarm::ListenerError(#listener_error { + listener_id, + err, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_listener_error(listener_id, err);}, + self.#field_n.on_swarm_event(#from_swarm::ListenerError(#listener_error { + listener_id, + err, + })); + }, }) }; @@ -425,11 +505,17 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { .enumerate() .map(|(field_n, field)| match field.ident { Some(ref i) => quote! { - #[allow(deprecated)] - self.#i.inject_listener_closed(listener_id, reason);}, + self.#i.on_swarm_event(#from_swarm::ListenerClosed(#listener_closed { + listener_id, + reason, + })); + }, None => quote! { - #[allow(deprecated)] - self.#field_n.inject_listener_closed(listener_id, reason);}, + self.#field_n.on_swarm_event(#from_swarm::ListenerClosed(#listener_closed { + listener_id, + reason, + })); + }, }) }; @@ -456,11 +542,9 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { Some(match field.ident { Some(ref i) => quote! { #elem => { - #[allow(deprecated)] - #trait_to_impl::inject_event(&mut self.#i, peer_id, connection_id, ev) }}, + #trait_to_impl::on_connection_handler_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) }}, + #trait_to_impl::on_connection_handler_event(&mut self.#field_n, peer_id, connection_id, ev) }}, }) }); diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index e6f0a92c8ec..a46df49392e 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -5,9 +5,13 @@ - Add `estblished_in` to `SwarmEvent::ConnectionEstablished`. See [PR 3134]. +- Remove deprecated `inject_*` methods from `NetworkBehaviour` and `ConnectionHandler`. + see [PR 3260]. + [PR 3170]: https://github.com/libp2p/rust-libp2p/pull/3170 [PR 3134]: https://github.com/libp2p/rust-libp2p/pull/3134 [PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153 +[PR 3260]: https://github.com/libp2p/rust-libp2p/pull/3260 # 0.41.1 diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index a0496cefc92..6fc494b1578 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -140,7 +140,8 @@ pub trait NetworkBehaviour: 'static { /// /// The network behaviour (ie. the implementation of this trait) and the handlers it has spawned /// (ie. the objects returned by `new_handler`) can communicate by passing messages. Messages - /// sent from the handler to the behaviour are injected with [`NetworkBehaviour::inject_event`], + /// sent from the handler to the behaviour are invoked with + /// [`NetworkBehaviour::on_connection_handler_event`], /// and the behaviour can send a message to the handler by making [`NetworkBehaviour::poll`] /// return [`NetworkBehaviourAction::NotifyHandler`]. /// @@ -159,7 +160,7 @@ pub trait NetworkBehaviour: 'static { } /// Informs the behaviour about an event from the [`Swarm`](crate::Swarm). - fn on_swarm_event(&mut self, _event: FromSwarm) {} + 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. @@ -175,209 +176,6 @@ pub trait NetworkBehaviour: 'static { ) { } - /// Informs the behaviour about a newly established connection to a peer. - #[deprecated( - 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( - &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - endpoint: &ConnectedPoint, - failed_addresses: Option<&Vec>, - other_established: usize, - ) { - self.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { - peer_id: *peer_id, - connection_id: *connection_id, - endpoint, - failed_addresses: failed_addresses - .map(|v| v.as_slice()) - .unwrap_or_else(|| &[]), - other_established, - })); - } - - /// 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.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( - &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - endpoint: &ConnectedPoint, - handler: ::Handler, - remaining_established: usize, - ) { - 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. - #[deprecated( - 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( - &mut self, - peer_id: &PeerId, - connection_id: &ConnectionId, - old: &ConnectedPoint, - new: &ConnectedPoint, - ) { - 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`. - /// 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.40.2", - note = "Implement `NetworkBehaviour::on_connection_handler_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_connection_handler_event(peer_id, connection, event); - } - - /// Indicates to the behaviour that the dial to a known or unknown node failed. - #[deprecated( - 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( - &mut self, - peer_id: Option, - handler: Self::ConnectionHandler, - error: &DialError, - ) { - 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 - /// initial handshake. - /// - /// This can include, for example, an error during the handshake of the encryption layer, or the - /// connection unexpectedly closed. - #[deprecated( - 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( - &mut self, - local_addr: &Multiaddr, - send_back_addr: &Multiaddr, - handler: Self::ConnectionHandler, - ) { - self.on_swarm_event(FromSwarm::ListenFailure(ListenFailure { - local_addr, - send_back_addr, - handler, - })); - } - - /// Indicates to the behaviour that a new listener was created. - #[deprecated( - 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) { - self.on_swarm_event(FromSwarm::NewListener(NewListener { listener_id: id })); - } - - /// Indicates to the behaviour that we have started listening on a new multiaddr. - #[deprecated( - 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) { - self.on_swarm_event(FromSwarm::NewListenAddr(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.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) { - self.on_swarm_event(FromSwarm::ExpiredListenAddr(ExpiredListenAddr { - listener_id: id, - addr, - })); - } - - /// A listener experienced an error. - #[deprecated( - 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)) { - self.on_swarm_event(FromSwarm::ListenerError(ListenerError { - listener_id: id, - err, - })); - } - - /// A listener closed. - #[deprecated( - 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>) { - 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. - #[deprecated( - 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) { - self.on_swarm_event(FromSwarm::NewExternalAddr(NewExternalAddr { addr })); - } - - /// Indicates to the behaviour that an external address was removed. - #[deprecated( - 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) { - self.on_swarm_event(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr })); - } - /// Polls for things that swarm should do. /// /// This API mimics the API of the `Stream` trait. The method may register the current task in @@ -447,8 +245,8 @@ pub enum NetworkBehaviourAction< /// Instructs the swarm to start a dial. /// - /// On success, [`NetworkBehaviour::inject_connection_established`] is invoked. - /// On failure, [`NetworkBehaviour::inject_dial_failure`] is invoked. + /// On success, [`NetworkBehaviour::on_swarm_event`] with `ConnectionEstablished` is invoked. + /// On failure, [`NetworkBehaviour::on_swarm_event`] with `DialFailure` is invoked. /// /// Note that the provided handler is returned to the [`NetworkBehaviour`] on connection failure /// and connection closing. Thus it can be used to carry state, which otherwise would have to be @@ -468,10 +266,11 @@ pub enum NetworkBehaviourAction< /// # use libp2p_core::PeerId; /// # use libp2p_plaintext::PlainText2Config; /// # use libp2p_swarm::{ - /// # DialError, IntoConnectionHandler, KeepAlive, NegotiatedSubstream, + /// # FromSwarm, DialFailure, DialError, IntoConnectionHandler, KeepAlive, NegotiatedSubstream, /// # NetworkBehaviour, NetworkBehaviourAction, PollParameters, ConnectionHandler, /// # ConnectionHandlerEvent, ConnectionHandlerUpgrErr, SubstreamProtocol, Swarm, SwarmEvent, /// # }; + /// # use libp2p_swarm::handler::ConnectionEvent; /// # use libp2p_swarm::dial_opts::{DialOpts, PeerCondition}; /// # use libp2p_yamux as yamux; /// # use std::collections::VecDeque; @@ -533,7 +332,7 @@ pub enum NetworkBehaviourAction< /// # } /// # /// # - /// # fn inject_event( + /// # fn on_connection_handler_event( /// # &mut self, /// # _: PeerId, /// # _: ConnectionId, @@ -542,17 +341,17 @@ pub enum NetworkBehaviourAction< /// # unreachable!(); /// # } /// # - /// fn inject_dial_failure( + /// fn on_swarm_event( /// &mut self, - /// _: Option, - /// handler: Self::ConnectionHandler, - /// _: &DialError, + /// event: FromSwarm, /// ) { /// // As expected, sending the message failed. But lucky us, we got the handler back, thus /// // the precious message is not lost and we can return it back to the user. - /// let msg = handler.message.unwrap(); - /// self.outbox_to_swarm - /// .push_back(NetworkBehaviourAction::GenerateEvent(msg)) + /// if let FromSwarm::DialFailure(DialFailure { handler, .. }) = event { + /// let msg = handler.message.unwrap(); + /// self.outbox_to_swarm + /// .push_back(NetworkBehaviourAction::GenerateEvent(msg)) + /// } /// } /// # /// # fn poll( @@ -630,7 +429,7 @@ pub enum NetworkBehaviourAction< /// If the specified connection no longer exists, the event is silently dropped. /// /// Typically the connection ID given is the same as the one passed to - /// [`NetworkBehaviour::inject_event`], i.e. whenever the behaviour wishes to + /// [`NetworkBehaviour::on_connection_handler_event`], i.e. whenever the behaviour wishes to /// respond to a request on the same connection (and possibly the same /// substream, as per the implementation of [`ConnectionHandler`]). /// @@ -1117,103 +916,3 @@ 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 4154db1a0de..073a0275548 100644 --- a/swarm/src/behaviour/either.rs +++ b/swarm/src/behaviour/either.rs @@ -18,9 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::behaviour::{ - self, inject_from_swarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters, -}; +use crate::behaviour::{self, NetworkBehaviour, NetworkBehaviourAction, PollParameters}; use crate::handler::either::IntoEitherHandler; use either::Either; use libp2p_core::{Multiaddr, PeerId}; @@ -51,26 +49,20 @@ where fn on_swarm_event(&mut self, event: behaviour::FromSwarm) { match self { - 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!(), - }, - ), - ), + 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!(), + }, + )), } } @@ -82,12 +74,10 @@ where ) { match (self, event) { (Either::Left(left), Either::Left(event)) => { - #[allow(deprecated)] - left.inject_event(peer_id, connection_id, event); + left.on_connection_handler_event(peer_id, connection_id, event); } (Either::Right(right), Either::Right(event)) => { - #[allow(deprecated)] - right.inject_event(peer_id, connection_id, event); + right.on_connection_handler_event(peer_id, connection_id, event); } _ => unreachable!(), } diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index f36969bebe8..ae198dc2bd3 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -18,7 +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::behaviour::FromSwarm; use crate::handler::{ AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, @@ -87,7 +87,7 @@ where 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) { - inject_from_swarm(behaviour, event); + behaviour.on_swarm_event(event); } } } diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index cf6051e1e85..c350f5a58fb 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -101,8 +101,10 @@ pub mod derive_prelude { } pub use behaviour::{ - CloseConnection, ExternalAddresses, ListenAddresses, NetworkBehaviour, NetworkBehaviourAction, - NotifyHandler, PollParameters, + AddressChange, CloseConnection, ConnectionClosed, DialFailure, ExpiredExternalAddr, + ExpiredListenAddr, ExternalAddresses, FromSwarm, ListenAddresses, ListenFailure, + ListenerClosed, ListenerError, NetworkBehaviour, NetworkBehaviourAction, NewExternalAddr, + NewListenAddr, NotifyHandler, PollParameters, }; pub use connection::pool::{ConnectionCounters, ConnectionLimits}; pub use connection::{ @@ -464,8 +466,10 @@ 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)?; - #[allow(deprecated)] - self.behaviour.inject_new_listener(id); + self.behaviour + .on_swarm_event(FromSwarm::NewListener(behaviour::NewListener { + listener_id: id, + })); Ok(id) } @@ -489,9 +493,9 @@ where /// # use libp2p_swarm::dummy; /// # /// let mut swarm = Swarm::without_executor( - /// DummyTransport::new().boxed(), - /// dummy::Behaviour, - /// PeerId::random(), + /// DummyTransport::new().boxed(), + /// dummy::Behaviour, + /// PeerId::random(), /// ); /// /// // Dial a known peer. @@ -533,22 +537,24 @@ where PeerCondition::Always => true, }; if !condition_matched { - #[allow(deprecated)] - self.behaviour.inject_dial_failure( - Some(peer_id), - handler, - &DialError::DialPeerConditionFalse(condition), - ); - + self.behaviour + .on_swarm_event(FromSwarm::DialFailure(DialFailure { + peer_id: Some(peer_id), + handler, + error: &DialError::DialPeerConditionFalse(condition), + })); return Err(DialError::DialPeerConditionFalse(condition)); } // Check if peer is banned. if self.banned_peers.contains(&peer_id) { let error = DialError::Banned; - #[allow(deprecated)] self.behaviour - .inject_dial_failure(Some(peer_id), handler, &error); + .on_swarm_event(FromSwarm::DialFailure(DialFailure { + peer_id: Some(peer_id), + handler, + error: &error, + })); return Err(error); } @@ -584,9 +590,12 @@ where if addresses.is_empty() { let error = DialError::NoAddresses; - #[allow(deprecated)] self.behaviour - .inject_dial_failure(Some(peer_id), handler, &error); + .on_swarm_event(FromSwarm::DialFailure(DialFailure { + peer_id: Some(peer_id), + handler, + error: &error, + })); return Err(error); }; @@ -668,8 +677,13 @@ where Ok(_connection_id) => Ok(()), Err((connection_limit, handler)) => { let error = DialError::ConnectionLimit(connection_limit); - #[allow(deprecated)] - self.behaviour.inject_dial_failure(peer_id, handler, &error); + self.behaviour + .on_swarm_event(FromSwarm::DialFailure(DialFailure { + peer_id, + handler, + error: &error, + })); + Err(error) } } @@ -710,15 +724,17 @@ where let result = self.external_addrs.add(a.clone(), s); let expired = match &result { AddAddressResult::Inserted { expired } => { - #[allow(deprecated)] - self.behaviour.inject_new_external_addr(&a); + self.behaviour + .on_swarm_event(FromSwarm::NewExternalAddr(NewExternalAddr { addr: &a })); expired } AddAddressResult::Updated { expired } => expired, }; for a in expired { - #[allow(deprecated)] - self.behaviour.inject_expired_external_addr(&a.addr); + self.behaviour + .on_swarm_event(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { + addr: &a.addr, + })); } result } @@ -731,8 +747,8 @@ where /// otherwise. pub fn remove_external_address(&mut self, addr: &Multiaddr) -> bool { if self.external_addrs.remove(addr) { - #[allow(deprecated)] - self.behaviour.inject_expired_external_addr(addr); + self.behaviour + .on_swarm_event(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr })); true } else { false @@ -838,15 +854,23 @@ where ); let failed_addresses = concurrent_dial_errors .as_ref() - .map(|es| es.iter().map(|(a, _)| a).cloned().collect()); - #[allow(deprecated)] - self.behaviour.inject_connection_established( - &peer_id, - &id, - &endpoint, - failed_addresses.as_ref(), - non_banned_established, - ); + .map(|es| { + es.iter() + .map(|(a, _)| a) + .cloned() + .collect::>() + }) + .unwrap_or_default(); + self.behaviour + .on_swarm_event(FromSwarm::ConnectionEstablished( + behaviour::ConnectionEstablished { + peer_id, + connection_id: id, + endpoint: &endpoint, + failed_addresses: &failed_addresses, + other_established: non_banned_established, + }, + )); return Some(SwarmEvent::ConnectionEstablished { peer_id, num_established, @@ -864,8 +888,12 @@ where } => { let error = error.into(); - #[allow(deprecated)] - self.behaviour.inject_dial_failure(peer, handler, &error); + self.behaviour + .on_swarm_event(FromSwarm::DialFailure(DialFailure { + peer_id: peer, + handler, + error: &error, + })); if let Some(peer) = peer { log::debug!("Connection attempt to {:?} failed with {:?}.", peer, error,); @@ -886,9 +914,12 @@ where handler, } => { log::debug!("Incoming connection failed: {:?}", error); - #[allow(deprecated)] self.behaviour - .inject_listen_failure(&local_addr, &send_back_addr, handler); + .on_swarm_event(FromSwarm::ListenFailure(ListenFailure { + local_addr: &local_addr, + send_back_addr: &send_back_addr, + handler, + })); return Some(SwarmEvent::IncomingConnectionError { local_addr, send_back_addr, @@ -927,14 +958,14 @@ where .into_iter() .filter(|conn_id| !self.banned_peer_connections.contains(conn_id)) .count(); - #[allow(deprecated)] - self.behaviour.inject_connection_closed( - &peer_id, - &id, - &endpoint, - handler, - remaining_non_banned, - ); + self.behaviour + .on_swarm_event(FromSwarm::ConnectionClosed(ConnectionClosed { + peer_id, + connection_id: id, + endpoint: &endpoint, + handler, + remaining_established: remaining_non_banned, + })); } return Some(SwarmEvent::ConnectionClosed { peer_id, @@ -947,8 +978,8 @@ where if self.banned_peer_connections.contains(&id) { log::debug!("Ignoring event from banned peer: {} {:?}.", peer_id, id); } else { - #[allow(deprecated)] - self.behaviour.inject_event(peer_id, id, event); + self.behaviour + .on_connection_handler_event(peer_id, id, event); } } PoolEvent::AddressChange { @@ -958,13 +989,13 @@ where old_endpoint, } => { if !self.banned_peer_connections.contains(&id) { - #[allow(deprecated)] - self.behaviour.inject_address_change( - &peer_id, - &id, - &old_endpoint, - &new_endpoint, - ); + self.behaviour + .on_swarm_event(FromSwarm::AddressChange(AddressChange { + peer_id, + connection_id: id, + old: &old_endpoint, + new: &new_endpoint, + })); } } } @@ -1002,9 +1033,12 @@ where }); } Err((connection_limit, handler)) => { - #[allow(deprecated)] self.behaviour - .inject_listen_failure(&local_addr, &send_back_addr, handler); + .on_swarm_event(FromSwarm::ListenFailure(ListenFailure { + local_addr: &local_addr, + send_back_addr: &send_back_addr, + handler, + })); log::warn!("Incoming connection rejected: {:?}", connection_limit); } }; @@ -1018,9 +1052,11 @@ where if !addrs.contains(&listen_addr) { addrs.push(listen_addr.clone()) } - #[allow(deprecated)] self.behaviour - .inject_new_listen_addr(listener_id, &listen_addr); + .on_swarm_event(FromSwarm::NewListenAddr(NewListenAddr { + listener_id, + addr: &listen_addr, + })); return Some(SwarmEvent::NewListenAddr { listener_id, address: listen_addr, @@ -1038,9 +1074,11 @@ where if let Some(addrs) = self.listened_addrs.get_mut(&listener_id) { addrs.retain(|a| a != &listen_addr); } - #[allow(deprecated)] self.behaviour - .inject_expired_listen_addr(listener_id, &listen_addr); + .on_swarm_event(FromSwarm::ExpiredListenAddr(ExpiredListenAddr { + listener_id, + addr: &listen_addr, + })); return Some(SwarmEvent::ExpiredListenAddr { listener_id, address: listen_addr, @@ -1053,17 +1091,15 @@ 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() { - #[allow(deprecated)] - self.behaviour.inject_expired_listen_addr(listener_id, addr); + self.behaviour.on_swarm_event(FromSwarm::ExpiredListenAddr( + ExpiredListenAddr { listener_id, addr }, + )); } - #[allow(deprecated)] - self.behaviour.inject_listener_closed( - listener_id, - match &reason { - Ok(()) => Ok(()), - Err(err) => Err(err), - }, - ); + self.behaviour + .on_swarm_event(FromSwarm::ListenerClosed(ListenerClosed { + listener_id, + reason: reason.as_ref().copied(), + })); return Some(SwarmEvent::ListenerClosed { listener_id, addresses: addrs.to_vec(), @@ -1071,8 +1107,11 @@ where }); } TransportEvent::ListenerError { listener_id, error } => { - #[allow(deprecated)] - self.behaviour.inject_listener_error(listener_id, &error); + self.behaviour + .on_swarm_event(FromSwarm::ListenerError(ListenerError { + listener_id, + err: &error, + })); return Some(SwarmEvent::ListenerError { listener_id, error }); } } @@ -1868,12 +1907,12 @@ mod tests { /// Establishes multiple connections between two peers, /// after which one peer bans the other. /// - /// The test expects both behaviours to be notified via pairs of - /// [`NetworkBehaviour::inject_connection_established`] / [`NetworkBehaviour::inject_connection_closed`] - /// calls while unbanned. + /// The test expects both behaviours to be notified via calls to [`NetworkBehaviour::on_swarm_event`] + /// with pairs of [`FromSwarm::ConnectionEstablished`] / [`FromSwarm::ConnectionClosed`] + /// while unbanned. /// /// While the ban is in effect, further dials occur. For these connections no - /// [`NetworkBehaviour::inject_connection_established`], [`NetworkBehaviour::inject_connection_closed`] + /// [`FromSwarm::ConnectionEstablished`], [`FromSwarm::ConnectionClosed`] /// calls should be registered. #[test] fn test_connect_disconnect_ban() { @@ -1991,8 +2030,8 @@ mod tests { /// Establishes multiple connections between two peers, /// after which one peer disconnects the other using [`Swarm::disconnect_peer_id`]. /// - /// The test expects both behaviours to be notified via pairs of - /// [`NetworkBehaviour::inject_connection_established`] / [`NetworkBehaviour::inject_connection_closed`] calls. + /// The test expects both behaviours to be notified via calls to [`NetworkBehaviour::on_swarm_event`] + /// with pairs of [`FromSwarm::ConnectionEstablished`] / [`FromSwarm::ConnectionClosed`] #[test] fn test_swarm_disconnect() { // Since the test does not try to open any substreams, we can @@ -2057,8 +2096,8 @@ mod tests { /// after which one peer disconnects the other /// using [`NetworkBehaviourAction::CloseConnection`] returned by a [`NetworkBehaviour`]. /// - /// The test expects both behaviours to be notified via pairs of - /// [`NetworkBehaviour::inject_connection_established`] / [`NetworkBehaviour::inject_connection_closed`] calls. + /// The test expects both behaviours to be notified via calls to [`NetworkBehaviour::on_swarm_event`] + /// with pairs of [`FromSwarm::ConnectionEstablished`] / [`FromSwarm::ConnectionClosed`] #[test] fn test_behaviour_disconnect_all() { // Since the test does not try to open any substreams, we can @@ -2125,8 +2164,8 @@ mod tests { /// after which one peer closes a single connection /// using [`NetworkBehaviourAction::CloseConnection`] returned by a [`NetworkBehaviour`]. /// - /// The test expects both behaviours to be notified via pairs of - /// [`NetworkBehaviour::inject_connection_established`] / [`NetworkBehaviour::inject_connection_closed`] calls. + /// The test expects both behaviours to be notified via calls to [`NetworkBehaviour::on_swarm_event`] + /// with pairs of [`FromSwarm::ConnectionEstablished`] / [`FromSwarm::ConnectionClosed`] #[test] fn test_behaviour_disconnect_one() { // Since the test does not try to open any substreams, we can diff --git a/swarm/src/test.rs b/swarm/src/test.rs index 94a5fbfef54..d850a174bdd 100644 --- a/swarm/src/test.rs +++ b/swarm/src/test.rs @@ -127,7 +127,7 @@ where pub addresses_of_peer: Vec, pub on_connection_established: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, pub on_connection_closed: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>, - pub on_event: Vec<( + pub on_connection_handler_event: Vec<( PeerId, ConnectionId, <::Handler as ConnectionHandler>::OutEvent, @@ -155,7 +155,7 @@ where addresses_of_peer: Vec::new(), on_connection_established: Vec::new(), on_connection_closed: Vec::new(), - on_event: Vec::new(), + on_connection_handler_event: Vec::new(), on_dial_failure: Vec::new(), on_new_listener: Vec::new(), on_new_listen_addr: Vec::new(), @@ -173,7 +173,7 @@ where self.addresses_of_peer = Vec::new(); self.on_connection_established = Vec::new(); self.on_connection_closed = Vec::new(); - self.on_event = Vec::new(); + self.on_connection_handler_event = Vec::new(); self.on_dial_failure = Vec::new(); self.on_new_listen_addr = Vec::new(); self.on_new_external_addr = Vec::new(); @@ -290,15 +290,14 @@ where 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 + .on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished { + peer_id, + connection_id, + endpoint, + failed_addresses, + other_established, + })); } fn on_connection_closed( @@ -343,8 +342,8 @@ where .iter() .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." + "`on_swarm_event` with `FromSwarm::ConnectionClosed is called only for connections for\ + which `on_swarm_event` with `FromSwarm::ConnectionEstablished` was called first." ); self.on_connection_closed.push(( peer_id, @@ -352,14 +351,14 @@ where endpoint.clone(), remaining_established, )); - #[allow(deprecated)] - self.inner.inject_connection_closed( - &peer_id, - &connection_id, - endpoint, - handler, - remaining_established, - ); + self.inner + .on_swarm_event(FromSwarm::ConnectionClosed(ConnectionClosed { + peer_id, + connection_id, + endpoint, + handler, + remaining_established, + })); } } @@ -395,47 +394,60 @@ where error, }) => { self.on_dial_failure.push(peer_id); - #[allow(deprecated)] - self.inner.inject_dial_failure(peer_id, handler, error); + self.inner + .on_swarm_event(FromSwarm::DialFailure(DialFailure { + 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); + self.inner + .on_swarm_event(FromSwarm::NewListener(NewListener { 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); + self.inner + .on_swarm_event(FromSwarm::NewListenAddr(NewListenAddr { + 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); + self.inner + .on_swarm_event(FromSwarm::ExpiredListenAddr(ExpiredListenAddr { + listener_id, + addr, + })); } FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => { self.on_new_external_addr.push(addr.clone()); - #[allow(deprecated)] - self.inner.inject_new_external_addr(addr); + self.inner + .on_swarm_event(FromSwarm::NewExternalAddr(NewExternalAddr { addr })); } FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }) => { self.on_expired_external_addr.push(addr.clone()); - #[allow(deprecated)] - self.inner.inject_expired_external_addr(addr); + self.inner + .on_swarm_event(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr })); } FromSwarm::ListenerError(ListenerError { listener_id, err }) => { self.on_listener_error.push(listener_id); - #[allow(deprecated)] - self.inner.inject_listener_error(listener_id, err); + self.inner + .on_swarm_event(FromSwarm::ListenerError(ListenerError { 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); + self.inner + .on_swarm_event(FromSwarm::ListenerClosed(ListenerClosed { + listener_id, + reason, + })); } _ => {} } @@ -461,9 +473,8 @@ where "`on_connection_handler_event` is never called for closed connections." ); - self.on_event.push((p, c, e.clone())); - #[allow(deprecated)] - self.inner.inject_event(p, c, e); + self.on_connection_handler_event.push((p, c, e.clone())); + self.inner.on_connection_handler_event(p, c, e); } fn poll( From 354257e329487a85b4ae30af55da421d9886014b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 21 Dec 2022 12:24:38 +0000 Subject: [PATCH 06/11] update swarm-derive CHANGELOG and Cargo.toml. --- swarm-derive/CHANGELOG.md | 10 +++++++--- swarm-derive/Cargo.toml | 2 +- swarm/CHANGELOG.md | 2 ++ swarm/Cargo.toml | 2 +- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/swarm-derive/CHANGELOG.md b/swarm-derive/CHANGELOG.md index b29f213e4e3..b7ea340b063 100644 --- a/swarm-derive/CHANGELOG.md +++ b/swarm-derive/CHANGELOG.md @@ -1,15 +1,19 @@ -# 0.31.0 +# 0.32.0 [unreleased] - Replace `NetworkBehaviour` Derive macro deprecated `inject_*` method implementations with the new `on_swarm_event` and `on_connection_handler_event`. - See [PR 3011]. + See [PR 3011] and [PR 3264]. + +[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 +[PR 3264]: https://github.com/libp2p/rust-libp2p/pull/3264 + +# 0.31.0 - Add `prelude` configuration option. The derive-macro generates code that needs to refer to various symbols. See [PR 3055]. - Update `rust-version` to reflect the actual MSRV: 1.60.0. See [PR 3090]. -[PR 3011]: https://github.com/libp2p/rust-libp2p/pull/3011 [PR 3055]: https://github.com/libp2p/rust-libp2p/pull/3055 [PR 3090]: https://github.com/libp2p/rust-libp2p/pull/3090 diff --git a/swarm-derive/Cargo.toml b/swarm-derive/Cargo.toml index f4ffa5d7370..96d4ef4315f 100644 --- a/swarm-derive/Cargo.toml +++ b/swarm-derive/Cargo.toml @@ -3,7 +3,7 @@ name = "libp2p-swarm-derive" edition = "2021" rust-version = "1.60.0" description = "Procedural macros of libp2p-swarm" -version = "0.31.0" +version = "0.32.0" authors = ["Parity Technologies "] license = "MIT" repository = "https://github.com/libp2p/rust-libp2p" diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index a46df49392e..e7d466cd73c 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -8,6 +8,8 @@ - Remove deprecated `inject_*` methods from `NetworkBehaviour` and `ConnectionHandler`. see [PR 3260]. +- Update to `libp2p-swarm-derive` `v0.32.0`. + [PR 3170]: https://github.com/libp2p/rust-libp2p/pull/3170 [PR 3134]: https://github.com/libp2p/rust-libp2p/pull/3134 [PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153 diff --git a/swarm/Cargo.toml b/swarm/Cargo.toml index 91a5c2c45ad..8866743c168 100644 --- a/swarm/Cargo.toml +++ b/swarm/Cargo.toml @@ -17,7 +17,7 @@ futures = "0.3.1" futures-timer = "3.0.2" instant = "0.1.11" libp2p-core = { version = "0.38.0", path = "../core" } -libp2p-swarm-derive = { version = "0.31.0", path = "../swarm-derive", optional = true } +libp2p-swarm-derive = { version = "0.32.0", path = "../swarm-derive", optional = true } log = "0.4" pin-project = "1.0.0" rand = "0.8" From 0831cbae63a04a8c748f2509efaff0a62effaaf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Thu, 22 Dec 2022 22:38:07 +0000 Subject: [PATCH 07/11] review: implement transpose functions for ConnectionEvent and DialUpgradeError, to help when matching on them for Either and Select. --- swarm/src/handler/either.rs | 427 +++++++++++++++--------------------- swarm/src/handler/select.rs | 155 +++++++------ 2 files changed, 263 insertions(+), 319 deletions(-) diff --git a/swarm/src/handler/either.rs b/swarm/src/handler/either.rs index c718f5432a6..246f217b37c 100644 --- a/swarm/src/handler/either.rs +++ b/swarm/src/handler/either.rs @@ -20,8 +20,8 @@ use crate::handler::{ ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, - DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, IntoConnectionHandler, - KeepAlive, ListenUpgradeError, SubstreamProtocol, + DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, InboundUpgradeSend, + IntoConnectionHandler, KeepAlive, ListenUpgradeError, OutboundUpgradeSend, SubstreamProtocol, }; use crate::upgrade::SendWrapper; use either::Either; @@ -30,6 +30,8 @@ use libp2p_core::upgrade::{EitherUpgrade, UpgradeError}; use libp2p_core::{ConnectedPoint, PeerId}; use std::task::{Context, Poll}; +use super::AddressChange; + /// Auxiliary type to allow implementing [`IntoConnectionHandler`]. As [`IntoConnectionHandler`] is /// already implemented for T, we cannot implement it for Either. pub enum IntoEitherHandler { @@ -90,6 +92,170 @@ impl IntoEitherHandler { } } +impl<'a, RIP, LIP, LOP, ROP, LIOP, RIOP, LOOP, ROOP> + ConnectionEvent< + 'a, + EitherUpgrade, SendWrapper>, + EitherUpgrade, SendWrapper>, + Either, + Either, + > +where + RIP: InboundUpgradeSend, + LIP: InboundUpgradeSend, + LOP: OutboundUpgradeSend, + ROP: OutboundUpgradeSend, +{ + pub fn transpose( + self, + ) -> Either, ConnectionEvent<'a, RIP, ROP, RIOP, ROOP>> + { + match self { + ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { + protocol: EitherOutput::First(protocol), + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { protocol, info }, + )), + ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { + protocol: EitherOutput::Second(protocol), + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::FullyNegotiatedInbound( + FullyNegotiatedInbound { protocol, info }, + )), + ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { + protocol: EitherOutput::First(protocol), + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { protocol, info }, + )), + ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { + protocol: EitherOutput::Second(protocol), + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::FullyNegotiatedOutbound( + FullyNegotiatedOutbound { protocol, info }, + )), + ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(error))), + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + })), + ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(error))), + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + })), + ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + })), + ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + })), + ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + })), + ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + })), + ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + })), + ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::DialUpgradeError(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + })), + ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(error))), + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + })), + ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(error))), + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + })), + ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + })), + ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + })), + ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + })), + ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + })), + ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info: Either::Left(info), + }) => Either::Left(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + })), + ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info: Either::Right(info), + }) => Either::Right(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + })), + ConnectionEvent::AddressChange(AddressChange { new_address }) => { + Either::Left(ConnectionEvent::AddressChange(AddressChange { + new_address, + })) + } + _ => unreachable!(), + } + } +} /// Implementation of a [`ConnectionHandler`] that represents either of two [`ConnectionHandler`] /// implementations. impl ConnectionHandler for Either @@ -171,250 +337,19 @@ where Self::OutboundOpenInfo, >, ) { - match event { - ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { - protocol: output, - info, - }) => match (self, output, info) { - (Either::Left(handler), EitherOutput::First(output), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( - FullyNegotiatedOutbound { - protocol: output, - info, - }, - )); - } - (Either::Right(handler), EitherOutput::Second(output), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( - FullyNegotiatedOutbound { - protocol: output, - info, - }, - )); - } - _ => unreachable!(), - }, - ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { - protocol: output, - info, - }) => match (self, output, info) { - (Either::Left(handler), EitherOutput::First(output), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::FullyNegotiatedInbound( - FullyNegotiatedInbound { - protocol: output, - info, - }, - )); - } - (Either::Right(handler), EitherOutput::Second(output), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::FullyNegotiatedInbound( - FullyNegotiatedInbound { - protocol: output, - info, - }, - )); - } - _ => unreachable!(), - }, - ConnectionEvent::AddressChange(address_change) => match self { - Either::Left(handler) => { - handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) - } - Either::Right(handler) => { - handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) - } - }, - ConnectionEvent::DialUpgradeError(DialUpgradeError { info, error }) => match error { - ConnectionHandlerUpgrErr::Timer => match (self, info) { - (Either::Left(handler), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timer, - }, - )); - } - (Either::Right(handler), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timer, - }, - )); - } - _ => unreachable!(), - }, - ConnectionHandlerUpgrErr::Timeout => match (self, info) { - (Either::Left(handler), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timeout, - }, - )); - } - (Either::Right(handler), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timeout, - }, - )); - } - _ => unreachable!(), - }, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => { - match (self, info) { - (Either::Left(handler), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( - error, - )), - }, - )); - } - (Either::Right(handler), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( - error, - )), - }, - )); - } - _ => unreachable!(), - } - } - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { - match (self, info) { - (Either::Left(handler), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply( - e, - )), - }, - )); - } - _ => unreachable!(), - } - } - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { - match (self, info) { - (Either::Right(handler), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply( - e, - )), - }, - )); - } - _ => unreachable!(), - } - } - }, - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { info, error }) => { - match error { - ConnectionHandlerUpgrErr::Timer => match (self, info) { - (Either::Left(handler), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timer, - }, - )); - } - (Either::Right(handler), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timer, - }, - )); - } - _ => unreachable!(), - }, - ConnectionHandlerUpgrErr::Timeout => match (self, info) { - (Either::Left(handler), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timeout, - }, - )); - } - (Either::Right(handler), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timeout, - }, - )); - } - _ => unreachable!(), - }, - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => { - match (self, info) { - (Either::Left(handler), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade( - UpgradeError::Select(error), - ), - }, - )); - } - (Either::Right(handler), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade( - UpgradeError::Select(error), - ), - }, - )); - } - _ => unreachable!(), - } - } - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { - match (self, info) { - (Either::Left(handler), Either::Left(info)) => { - handler.on_connection_event(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade( - UpgradeError::Apply(e), - ), - }, - )); - } - _ => unreachable!(), - } - } - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { - match (self, info) { - (Either::Right(handler), Either::Right(info)) => { - handler.on_connection_event(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade( - UpgradeError::Apply(e), - ), - }, - )); - } - _ => unreachable!(), - } - } - } + match (event.transpose(), self) { + ( + Either::Left(ConnectionEvent::AddressChange(address_change)), + Either::Left(handler), + ) => handler.on_connection_event(ConnectionEvent::AddressChange(address_change)), + ( + Either::Left(ConnectionEvent::AddressChange(address_change)), + Either::Right(handler), + ) => handler.on_connection_event(ConnectionEvent::AddressChange(address_change)), + (Either::Left(event), Either::Left(handler)) => handler.on_connection_event(event), + (Either::Right(event), Either::Right(handler)) => handler.on_connection_event(event), + (Either::Left(_), Either::Right(_)) | (Either::Right(_), Either::Left(_)) => { + unreachable!() } } } diff --git a/swarm/src/handler/select.rs b/swarm/src/handler/select.rs index 6a60e9099b9..62a69ab633d 100644 --- a/swarm/src/handler/select.rs +++ b/swarm/src/handler/select.rs @@ -21,10 +21,11 @@ use crate::handler::{ AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, - IntoConnectionHandler, KeepAlive, ListenUpgradeError, SubstreamProtocol, + IntoConnectionHandler, KeepAlive, ListenUpgradeError, OutboundUpgradeSend, SubstreamProtocol, }; use crate::upgrade::SendWrapper; +use either::Either; use libp2p_core::{ either::{EitherError, EitherOutput}, upgrade::{EitherUpgrade, NegotiationError, ProtocolError, SelectUpgrade, UpgradeError}, @@ -98,6 +99,80 @@ impl ConnectionHandlerSelect { } } +impl + DialUpgradeError< + EitherOutput, + EitherUpgrade, SendWrapper>, + > +where + S1OP: OutboundUpgradeSend, + S2OP: OutboundUpgradeSend, + S1OOI: Send + 'static, + S2OOI: Send + 'static, +{ + fn transpose(self) -> Either, DialUpgradeError> { + match self { + DialUpgradeError { + info: EitherOutput::First(info), + error: ConnectionHandlerUpgrErr::Timer, + } => Either::Left(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timer, + }), + DialUpgradeError { + info: EitherOutput::First(info), + error: ConnectionHandlerUpgrErr::Timeout, + } => Either::Left(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + }), + DialUpgradeError { + info: EitherOutput::First(info), + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + } => Either::Left(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + }), + DialUpgradeError { + info: EitherOutput::First(info), + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(err))), + } => Either::Left(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), + }), + DialUpgradeError { + info: EitherOutput::Second(info), + error: ConnectionHandlerUpgrErr::Timer, + } => Either::Right(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timer, + }), + DialUpgradeError { + info: EitherOutput::Second(info), + error: ConnectionHandlerUpgrErr::Timeout, + } => Either::Right(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Timeout, + }), + DialUpgradeError { + info: EitherOutput::Second(info), + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + } => Either::Right(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + }), + DialUpgradeError { + info: EitherOutput::Second(info), + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(err))), + } => Either::Right(DialUpgradeError { + info, + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), + }), + _ => panic!("Wrong API usage; the upgrade error doesn't match the outbound open info"), + } + } +} + impl ConnectionHandlerSelect where TProto1: ConnectionHandler, @@ -163,84 +238,18 @@ where fn on_dial_upgrade_error( &mut self, - DialUpgradeError { info, error }: DialUpgradeError< + err: DialUpgradeError< ::OutboundOpenInfo, ::OutboundProtocol, >, ) { - match (info, error) { - (EitherOutput::First(info), ConnectionHandlerUpgrErr::Timer) => self - .proto1 - .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timer, - })), - (EitherOutput::First(info), ConnectionHandlerUpgrErr::Timeout) => self + match err.transpose() { + Either::Left(err) => self .proto1 - .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timeout, - })), - ( - EitherOutput::First(info), - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), - ) => self - .proto1 - .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), - })), - ( - EitherOutput::First(info), - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(err))), - ) => self - .proto1 - .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), - })), - ( - EitherOutput::First(_), - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(_))), - ) => { - panic!("Wrong API usage; the upgrade error doesn't match the outbound open info"); - } - (EitherOutput::Second(info), ConnectionHandlerUpgrErr::Timeout) => self - .proto2 - .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timeout, - })), - (EitherOutput::Second(info), ConnectionHandlerUpgrErr::Timer) => self + .on_connection_event(ConnectionEvent::DialUpgradeError(err)), + Either::Right(err) => self .proto2 - .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Timer, - })), - ( - EitherOutput::Second(info), - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), - ) => self - .proto2 - .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), - })), - ( - EitherOutput::Second(info), - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(err))), - ) => self - .proto2 - .on_connection_event(ConnectionEvent::DialUpgradeError(DialUpgradeError { - info, - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), - })), - ( - EitherOutput::Second(_), - ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(_))), - ) => { - panic!("Wrong API usage; the upgrade error doesn't match the outbound open info"); - } + .on_connection_event(ConnectionEvent::DialUpgradeError(err)), } } From b9afb312575c1fe43a650f1d28b05c60336fbb9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 23 Dec 2022 15:28:08 +0000 Subject: [PATCH 08/11] review: implement transpose on swarm::handler::select, for the remaining ConnectionEvents that is useful to implement on. --- swarm/src/handler/select.rs | 155 ++++++++++++++++++------------------ 1 file changed, 76 insertions(+), 79 deletions(-) diff --git a/swarm/src/handler/select.rs b/swarm/src/handler/select.rs index 62a69ab633d..c979d91c71e 100644 --- a/swarm/src/handler/select.rs +++ b/swarm/src/handler/select.rs @@ -21,7 +21,8 @@ use crate::handler::{ AddressChange, ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, DialUpgradeError, FullyNegotiatedInbound, FullyNegotiatedOutbound, - IntoConnectionHandler, KeepAlive, ListenUpgradeError, OutboundUpgradeSend, SubstreamProtocol, + InboundUpgradeSend, IntoConnectionHandler, KeepAlive, ListenUpgradeError, OutboundUpgradeSend, + SubstreamProtocol, }; use crate::upgrade::SendWrapper; @@ -99,6 +100,56 @@ impl ConnectionHandlerSelect { } } +impl + FullyNegotiatedOutbound< + EitherUpgrade, SendWrapper>, + EitherOutput, + > +where + S1OP: OutboundUpgradeSend, + S2OP: OutboundUpgradeSend, + S1OOI: Send + 'static, + S2OOI: Send + 'static, +{ + fn transpose( + self, + ) -> Either, FullyNegotiatedOutbound> { + match self { + FullyNegotiatedOutbound { + protocol: EitherOutput::First(protocol), + info: EitherOutput::First(info), + } => Either::Left(FullyNegotiatedOutbound { protocol, info }), + FullyNegotiatedOutbound { + protocol: EitherOutput::Second(protocol), + info: EitherOutput::Second(info), + } => Either::Right(FullyNegotiatedOutbound { protocol, info }), + _ => panic!("wrong API usage: the protocol doesn't match the upgrade info"), + } + } +} + +impl + FullyNegotiatedInbound, SendWrapper>, (S1IOI, S2IOI)> +where + S1IP: InboundUpgradeSend, + S2IP: InboundUpgradeSend, +{ + fn transpose( + self, + ) -> Either, FullyNegotiatedInbound> { + match self { + FullyNegotiatedInbound { + protocol: EitherOutput::First(protocol), + info: (i1, _i2), + } => Either::Left(FullyNegotiatedInbound { protocol, info: i1 }), + FullyNegotiatedInbound { + protocol: EitherOutput::Second(protocol), + info: (_i1, i2), + } => Either::Right(FullyNegotiatedInbound { protocol, info: i2 }), + } + } +} + impl DialUpgradeError< EitherOutput, @@ -178,81 +229,6 @@ where TProto1: ConnectionHandler, TProto2: ConnectionHandler, { - fn on_fully_negotiated_outbound( - &mut self, - FullyNegotiatedOutbound { - protocol, - info: endpoint, - }: FullyNegotiatedOutbound< - ::OutboundProtocol, - ::OutboundOpenInfo, - >, - ) { - match (protocol, endpoint) { - (EitherOutput::First(protocol), EitherOutput::First(info)) => { - self.proto1 - .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( - FullyNegotiatedOutbound { protocol, info }, - )); - } - (EitherOutput::Second(protocol), EitherOutput::Second(info)) => { - self.proto2 - .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( - FullyNegotiatedOutbound { protocol, info }, - )); - } - (EitherOutput::First(_), EitherOutput::Second(_)) => { - panic!("wrong API usage: the protocol doesn't match the upgrade info") - } - (EitherOutput::Second(_), EitherOutput::First(_)) => { - panic!("wrong API usage: the protocol doesn't match the upgrade info") - } - } - } - - fn on_fully_negotiated_inbound( - &mut self, - FullyNegotiatedInbound { - protocol, - info: (i1, i2), - }: FullyNegotiatedInbound< - ::InboundProtocol, - ::InboundOpenInfo, - >, - ) { - match protocol { - EitherOutput::First(protocol) => { - self.proto1 - .on_connection_event(ConnectionEvent::FullyNegotiatedInbound( - FullyNegotiatedInbound { protocol, info: i1 }, - )); - } - EitherOutput::Second(protocol) => { - self.proto2 - .on_connection_event(ConnectionEvent::FullyNegotiatedInbound( - FullyNegotiatedInbound { protocol, info: i2 }, - )); - } - } - } - - fn on_dial_upgrade_error( - &mut self, - err: DialUpgradeError< - ::OutboundOpenInfo, - ::OutboundProtocol, - >, - ) { - match err.transpose() { - Either::Left(err) => self - .proto1 - .on_connection_event(ConnectionEvent::DialUpgradeError(err)), - Either::Right(err) => self - .proto2 - .on_connection_event(ConnectionEvent::DialUpgradeError(err)), - } - } - fn on_listen_upgrade_error( &mut self, ListenUpgradeError { @@ -462,10 +438,24 @@ where ) { match event { ConnectionEvent::FullyNegotiatedOutbound(fully_negotiated_outbound) => { - self.on_fully_negotiated_outbound(fully_negotiated_outbound) + match fully_negotiated_outbound.transpose() { + Either::Left(f) => self + .proto1 + .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound(f)), + Either::Right(f) => self + .proto2 + .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound(f)), + } } ConnectionEvent::FullyNegotiatedInbound(fully_negotiated_inbound) => { - self.on_fully_negotiated_inbound(fully_negotiated_inbound) + match fully_negotiated_inbound.transpose() { + Either::Left(f) => self + .proto1 + .on_connection_event(ConnectionEvent::FullyNegotiatedInbound(f)), + Either::Right(f) => self + .proto2 + .on_connection_event(ConnectionEvent::FullyNegotiatedInbound(f)), + } } ConnectionEvent::AddressChange(address) => { self.proto1 @@ -479,7 +469,14 @@ where })); } ConnectionEvent::DialUpgradeError(dial_upgrade_error) => { - self.on_dial_upgrade_error(dial_upgrade_error) + match dial_upgrade_error.transpose() { + Either::Left(err) => self + .proto1 + .on_connection_event(ConnectionEvent::DialUpgradeError(err)), + Either::Right(err) => self + .proto2 + .on_connection_event(ConnectionEvent::DialUpgradeError(err)), + } } ConnectionEvent::ListenUpgradeError(listen_upgrade_error) => { self.on_listen_upgrade_error(listen_upgrade_error) From 2325c6b288f2961b28df3ea655a77ae1e6faca0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Fri, 23 Dec 2022 15:52:35 +0000 Subject: [PATCH 09/11] review: change ConnectionEvent::transpose return type to Result and document it. --- swarm/src/handler/either.rs | 213 +++++++++++++++++++++--------------- 1 file changed, 125 insertions(+), 88 deletions(-) diff --git a/swarm/src/handler/either.rs b/swarm/src/handler/either.rs index 246f217b37c..078fc1ed8aa 100644 --- a/swarm/src/handler/either.rs +++ b/swarm/src/handler/either.rs @@ -106,151 +106,188 @@ where LOP: OutboundUpgradeSend, ROP: OutboundUpgradeSend, { + /// Transposes a [`ConnectionEvent`] with Either's on it's inner fields to an [`Either`] of connection events. + /// Returns Err in case of the [`ConnectionEvent`] being [`AddressChange`] as it isn't transposable. pub fn transpose( self, - ) -> Either, ConnectionEvent<'a, RIP, ROP, RIOP, ROOP>> - { + ) -> Result< + Either< + ConnectionEvent<'a, LIP, LOP, LIOP, LOOP>, + ConnectionEvent<'a, RIP, ROP, RIOP, ROOP>, + >, + AddressChange<'a>, + > { match self { ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { protocol: EitherOutput::First(protocol), info: Either::Left(info), - }) => Either::Left(ConnectionEvent::FullyNegotiatedInbound( + }) => Ok(Either::Left(ConnectionEvent::FullyNegotiatedInbound( FullyNegotiatedInbound { protocol, info }, - )), + ))), ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { protocol: EitherOutput::Second(protocol), info: Either::Right(info), - }) => Either::Right(ConnectionEvent::FullyNegotiatedInbound( + }) => Ok(Either::Right(ConnectionEvent::FullyNegotiatedInbound( FullyNegotiatedInbound { protocol, info }, - )), + ))), ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { protocol: EitherOutput::First(protocol), info: Either::Left(info), - }) => Either::Left(ConnectionEvent::FullyNegotiatedOutbound( + }) => Ok(Either::Left(ConnectionEvent::FullyNegotiatedOutbound( FullyNegotiatedOutbound { protocol, info }, - )), + ))), ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { protocol: EitherOutput::Second(protocol), info: Either::Right(info), - }) => Either::Right(ConnectionEvent::FullyNegotiatedOutbound( + }) => Ok(Either::Right(ConnectionEvent::FullyNegotiatedOutbound( FullyNegotiatedOutbound { protocol, info }, - )), + ))), ConnectionEvent::DialUpgradeError(DialUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(error))), info: Either::Left(info), - }) => Either::Left(ConnectionEvent::DialUpgradeError(DialUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), - info, - })), + }) => Ok(Either::Left(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + }, + ))), ConnectionEvent::DialUpgradeError(DialUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(error))), info: Either::Right(info), - }) => Either::Right(ConnectionEvent::DialUpgradeError(DialUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), - info, - })), + }) => Ok(Either::Right(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + }, + ))), ConnectionEvent::DialUpgradeError(DialUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), info: Either::Left(info), - }) => Either::Left(ConnectionEvent::DialUpgradeError(DialUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - info, - })), + }) => Ok(Either::Left(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + }, + ))), ConnectionEvent::DialUpgradeError(DialUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), info: Either::Right(info), - }) => Either::Right(ConnectionEvent::DialUpgradeError(DialUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - info, - })), + }) => Ok(Either::Right(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + }, + ))), ConnectionEvent::DialUpgradeError(DialUpgradeError { error: ConnectionHandlerUpgrErr::Timer, info: Either::Left(info), - }) => Either::Left(ConnectionEvent::DialUpgradeError(DialUpgradeError { - error: ConnectionHandlerUpgrErr::Timer, - info, - })), + }) => Ok(Either::Left(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + }, + ))), ConnectionEvent::DialUpgradeError(DialUpgradeError { error: ConnectionHandlerUpgrErr::Timer, info: Either::Right(info), - }) => Either::Right(ConnectionEvent::DialUpgradeError(DialUpgradeError { - error: ConnectionHandlerUpgrErr::Timer, - info, - })), + }) => Ok(Either::Right(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + }, + ))), ConnectionEvent::DialUpgradeError(DialUpgradeError { error: ConnectionHandlerUpgrErr::Timeout, info: Either::Left(info), - }) => Either::Left(ConnectionEvent::DialUpgradeError(DialUpgradeError { - error: ConnectionHandlerUpgrErr::Timeout, - info, - })), + }) => Ok(Either::Left(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + }, + ))), ConnectionEvent::DialUpgradeError(DialUpgradeError { error: ConnectionHandlerUpgrErr::Timeout, info: Either::Right(info), - }) => Either::Right(ConnectionEvent::DialUpgradeError(DialUpgradeError { - error: ConnectionHandlerUpgrErr::Timeout, - info, - })), + }) => Ok(Either::Right(ConnectionEvent::DialUpgradeError( + DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + }, + ))), ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(error))), info: Either::Left(info), - }) => Either::Left(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), - info, - })), + }) => Ok(Either::Left(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + }, + ))), ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(error))), info: Either::Right(info), - }) => Either::Right(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), - info, - })), + }) => Ok(Either::Right(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + }, + ))), ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), info: Either::Left(info), - }) => Either::Left(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - info, - })), + }) => Ok(Either::Left(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + }, + ))), ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), info: Either::Right(info), - }) => Either::Right(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - info, - })), + }) => Ok(Either::Right(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + }, + ))), ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error: ConnectionHandlerUpgrErr::Timer, info: Either::Left(info), - }) => Either::Left(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Timer, - info, - })), + }) => Ok(Either::Left(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + }, + ))), ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error: ConnectionHandlerUpgrErr::Timer, info: Either::Right(info), - }) => Either::Right(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Timer, - info, - })), + }) => Ok(Either::Right(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + }, + ))), ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error: ConnectionHandlerUpgrErr::Timeout, info: Either::Left(info), - }) => Either::Left(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Timeout, - info, - })), + }) => Ok(Either::Left(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + }, + ))), ConnectionEvent::ListenUpgradeError(ListenUpgradeError { error: ConnectionHandlerUpgrErr::Timeout, info: Either::Right(info), - }) => Either::Right(ConnectionEvent::ListenUpgradeError(ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Timeout, - info, - })), + }) => Ok(Either::Right(ConnectionEvent::ListenUpgradeError( + ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + }, + ))), ConnectionEvent::AddressChange(AddressChange { new_address }) => { - Either::Left(ConnectionEvent::AddressChange(AddressChange { - new_address, - })) + Err(AddressChange { new_address }) } _ => unreachable!(), } @@ -338,17 +375,17 @@ where >, ) { match (event.transpose(), self) { - ( - Either::Left(ConnectionEvent::AddressChange(address_change)), - Either::Left(handler), - ) => handler.on_connection_event(ConnectionEvent::AddressChange(address_change)), - ( - Either::Left(ConnectionEvent::AddressChange(address_change)), - Either::Right(handler), - ) => handler.on_connection_event(ConnectionEvent::AddressChange(address_change)), - (Either::Left(event), Either::Left(handler)) => handler.on_connection_event(event), - (Either::Right(event), Either::Right(handler)) => handler.on_connection_event(event), - (Either::Left(_), Either::Right(_)) | (Either::Right(_), Either::Left(_)) => { + (Err(address_change), Either::Left(handler)) => { + handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) + } + (Err(address_change), Either::Right(handler)) => { + handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) + } + (Ok(Either::Left(event)), Either::Left(handler)) => handler.on_connection_event(event), + (Ok(Either::Right(event)), Either::Right(handler)) => { + handler.on_connection_event(event) + } + (Ok(Either::Left(_)), Either::Right(_)) | (Ok(Either::Right(_)), Either::Left(_)) => { unreachable!() } } From e2e8d93dd6d59ce2c2e9f874b365fa9966f79345 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 11 Jan 2023 14:42:12 +0000 Subject: [PATCH 10/11] review: fix PR typo in changelog --- swarm/CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index 68e38fe4a00..25969d67052 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -8,7 +8,7 @@ - Add `estblished_in` to `SwarmEvent::ConnectionEstablished`. See [PR 3134]. - Remove deprecated `inject_*` methods from `NetworkBehaviour` and `ConnectionHandler`. - see [PR 3260]. + see [PR 3264]. - Update to `libp2p-swarm-derive` `v0.32.0`. @@ -18,7 +18,7 @@ [PR 3170]: https://github.com/libp2p/rust-libp2p/pull/3170 [PR 3134]: https://github.com/libp2p/rust-libp2p/pull/3134 [PR 3153]: https://github.com/libp2p/rust-libp2p/pull/3153 -[PR 3260]: https://github.com/libp2p/rust-libp2p/pull/3260 +[PR 3264]: https://github.com/libp2p/rust-libp2p/pull/3264 [PR 3272]: https://github.com/libp2p/rust-libp2p/pull/3272 # 0.41.1 From a6c052de85f5a81dd93ab4179e19950f25a045d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Oliveira?= Date: Wed, 11 Jan 2023 14:45:42 +0000 Subject: [PATCH 11/11] review: update Select transpose of ConnectionEvent do it per variant instead of on the ConnectionEvent itself, so that we no longer need the Err on the case of AddressChange. --- swarm/src/handler/either.rs | 350 +++++++++++++++++++----------------- 1 file changed, 187 insertions(+), 163 deletions(-) diff --git a/swarm/src/handler/either.rs b/swarm/src/handler/either.rs index 078fc1ed8aa..4be677a55f6 100644 --- a/swarm/src/handler/either.rs +++ b/swarm/src/handler/either.rs @@ -30,8 +30,6 @@ use libp2p_core::upgrade::{EitherUpgrade, UpgradeError}; use libp2p_core::{ConnectedPoint, PeerId}; use std::task::{Context, Poll}; -use super::AddressChange; - /// Auxiliary type to allow implementing [`IntoConnectionHandler`]. As [`IntoConnectionHandler`] is /// already implemented for T, we cannot implement it for Either. pub enum IntoEitherHandler { @@ -92,207 +90,190 @@ impl IntoEitherHandler { } } -impl<'a, RIP, LIP, LOP, ROP, LIOP, RIOP, LOOP, ROOP> - ConnectionEvent< - 'a, - EitherUpgrade, SendWrapper>, - EitherUpgrade, SendWrapper>, - Either, - Either, - > +impl + FullyNegotiatedInbound, SendWrapper>, Either> where RIP: InboundUpgradeSend, LIP: InboundUpgradeSend, - LOP: OutboundUpgradeSend, - ROP: OutboundUpgradeSend, { - /// Transposes a [`ConnectionEvent`] with Either's on it's inner fields to an [`Either`] of connection events. - /// Returns Err in case of the [`ConnectionEvent`] being [`AddressChange`] as it isn't transposable. - pub fn transpose( + fn transpose( self, - ) -> Result< - Either< - ConnectionEvent<'a, LIP, LOP, LIOP, LOOP>, - ConnectionEvent<'a, RIP, ROP, RIOP, ROOP>, - >, - AddressChange<'a>, - > { + ) -> Either, FullyNegotiatedInbound> { match self { - ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { + FullyNegotiatedInbound { protocol: EitherOutput::First(protocol), info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::FullyNegotiatedInbound( - FullyNegotiatedInbound { protocol, info }, - ))), - ConnectionEvent::FullyNegotiatedInbound(FullyNegotiatedInbound { + } => Either::Left(FullyNegotiatedInbound { protocol, info }), + FullyNegotiatedInbound { protocol: EitherOutput::Second(protocol), info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::FullyNegotiatedInbound( - FullyNegotiatedInbound { protocol, info }, - ))), - ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { + } => Either::Right(FullyNegotiatedInbound { protocol, info }), + _ => unreachable!(), + } + } +} + +impl + FullyNegotiatedOutbound, SendWrapper>, Either> +where + LOP: OutboundUpgradeSend, + ROP: OutboundUpgradeSend, +{ + fn transpose( + self, + ) -> Either, FullyNegotiatedOutbound> { + match self { + FullyNegotiatedOutbound { protocol: EitherOutput::First(protocol), info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::FullyNegotiatedOutbound( - FullyNegotiatedOutbound { protocol, info }, - ))), - ConnectionEvent::FullyNegotiatedOutbound(FullyNegotiatedOutbound { + } => Either::Left(FullyNegotiatedOutbound { protocol, info }), + FullyNegotiatedOutbound { protocol: EitherOutput::Second(protocol), info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::FullyNegotiatedOutbound( - FullyNegotiatedOutbound { protocol, info }, - ))), - ConnectionEvent::DialUpgradeError(DialUpgradeError { + } => Either::Right(FullyNegotiatedOutbound { protocol, info }), + _ => unreachable!(), + } + } +} + +impl + DialUpgradeError, EitherUpgrade, SendWrapper>> +where + LOP: OutboundUpgradeSend, + ROP: OutboundUpgradeSend, +{ + fn transpose(self) -> Either, DialUpgradeError> { + match self { + DialUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(error))), info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), - info, - }, - ))), - ConnectionEvent::DialUpgradeError(DialUpgradeError { + } => Either::Left(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + }), + DialUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(error))), info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), - info, - }, - ))), - ConnectionEvent::DialUpgradeError(DialUpgradeError { + } => Either::Right(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + }), + DialUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - info, - }, - ))), - ConnectionEvent::DialUpgradeError(DialUpgradeError { + } => Either::Left(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + }), + DialUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - info, - }, - ))), - ConnectionEvent::DialUpgradeError(DialUpgradeError { + } => Either::Right(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + }), + DialUpgradeError { error: ConnectionHandlerUpgrErr::Timer, info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - error: ConnectionHandlerUpgrErr::Timer, - info, - }, - ))), - ConnectionEvent::DialUpgradeError(DialUpgradeError { + } => Either::Left(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + }), + DialUpgradeError { error: ConnectionHandlerUpgrErr::Timer, info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - error: ConnectionHandlerUpgrErr::Timer, - info, - }, - ))), - ConnectionEvent::DialUpgradeError(DialUpgradeError { + } => Either::Right(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + }), + DialUpgradeError { error: ConnectionHandlerUpgrErr::Timeout, info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - error: ConnectionHandlerUpgrErr::Timeout, - info, - }, - ))), - ConnectionEvent::DialUpgradeError(DialUpgradeError { + } => Either::Left(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + }), + DialUpgradeError { error: ConnectionHandlerUpgrErr::Timeout, info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::DialUpgradeError( - DialUpgradeError { - error: ConnectionHandlerUpgrErr::Timeout, - info, - }, - ))), - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + } => Either::Right(DialUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + }), + _ => unreachable!(), + } + } +} + +impl + ListenUpgradeError, EitherUpgrade, SendWrapper>> +where + RIP: InboundUpgradeSend, + LIP: InboundUpgradeSend, +{ + fn transpose(self) -> Either, ListenUpgradeError> { + match self { + ListenUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(error))), info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), - info, - }, - ))), - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + } => Either::Left(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + }), + ListenUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(error))), info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), - info, - }, - ))), - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + } => Either::Right(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(error)), + info, + }), + ListenUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - info, - }, - ))), - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + } => Either::Left(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + }), + ListenUpgradeError { error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), - info, - }, - ))), - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + } => Either::Right(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + info, + }), + ListenUpgradeError { error: ConnectionHandlerUpgrErr::Timer, info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Timer, - info, - }, - ))), - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + } => Either::Left(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + }), + ListenUpgradeError { error: ConnectionHandlerUpgrErr::Timer, info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Timer, - info, - }, - ))), - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + } => Either::Right(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timer, + info, + }), + ListenUpgradeError { error: ConnectionHandlerUpgrErr::Timeout, info: Either::Left(info), - }) => Ok(Either::Left(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Timeout, - info, - }, - ))), - ConnectionEvent::ListenUpgradeError(ListenUpgradeError { + } => Either::Left(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + }), + ListenUpgradeError { error: ConnectionHandlerUpgrErr::Timeout, info: Either::Right(info), - }) => Ok(Either::Right(ConnectionEvent::ListenUpgradeError( - ListenUpgradeError { - error: ConnectionHandlerUpgrErr::Timeout, - info, - }, - ))), - ConnectionEvent::AddressChange(AddressChange { new_address }) => { - Err(AddressChange { new_address }) - } + } => Either::Right(ListenUpgradeError { + error: ConnectionHandlerUpgrErr::Timeout, + info, + }), _ => unreachable!(), } } } + /// Implementation of a [`ConnectionHandler`] that represents either of two [`ConnectionHandler`] /// implementations. impl ConnectionHandler for Either @@ -374,20 +355,63 @@ where Self::OutboundOpenInfo, >, ) { - match (event.transpose(), self) { - (Err(address_change), Either::Left(handler)) => { - handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) + match event { + ConnectionEvent::FullyNegotiatedInbound(fully_negotiated_inbound) => { + match (fully_negotiated_inbound.transpose(), self) { + (Either::Left(fully_negotiated_inbound), Either::Left(handler)) => handler + .on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + fully_negotiated_inbound, + )), + (Either::Right(fully_negotiated_inbound), Either::Right(handler)) => handler + .on_connection_event(ConnectionEvent::FullyNegotiatedInbound( + fully_negotiated_inbound, + )), + _ => unreachable!(), + } } - (Err(address_change), Either::Right(handler)) => { - handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) + ConnectionEvent::FullyNegotiatedOutbound(fully_negotiated_outbound) => { + match (fully_negotiated_outbound.transpose(), self) { + (Either::Left(fully_negotiated_outbound), Either::Left(handler)) => handler + .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + fully_negotiated_outbound, + )), + (Either::Right(fully_negotiated_outbound), Either::Right(handler)) => handler + .on_connection_event(ConnectionEvent::FullyNegotiatedOutbound( + fully_negotiated_outbound, + )), + _ => unreachable!(), + } } - (Ok(Either::Left(event)), Either::Left(handler)) => handler.on_connection_event(event), - (Ok(Either::Right(event)), Either::Right(handler)) => { - handler.on_connection_event(event) + ConnectionEvent::DialUpgradeError(dial_upgrade_error) => { + match (dial_upgrade_error.transpose(), self) { + (Either::Left(dial_upgrade_error), Either::Left(handler)) => handler + .on_connection_event(ConnectionEvent::DialUpgradeError(dial_upgrade_error)), + (Either::Right(dial_upgrade_error), Either::Right(handler)) => handler + .on_connection_event(ConnectionEvent::DialUpgradeError(dial_upgrade_error)), + _ => unreachable!(), + } } - (Ok(Either::Left(_)), Either::Right(_)) | (Ok(Either::Right(_)), Either::Left(_)) => { - unreachable!() + ConnectionEvent::ListenUpgradeError(listen_upgrade_error) => { + match (listen_upgrade_error.transpose(), self) { + (Either::Left(listen_upgrade_error), Either::Left(handler)) => handler + .on_connection_event(ConnectionEvent::ListenUpgradeError( + listen_upgrade_error, + )), + (Either::Right(listen_upgrade_error), Either::Right(handler)) => handler + .on_connection_event(ConnectionEvent::ListenUpgradeError( + listen_upgrade_error, + )), + _ => unreachable!(), + } } + ConnectionEvent::AddressChange(address_change) => match self { + Either::Left(handler) => { + handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) + } + Either::Right(handler) => { + handler.on_connection_event(ConnectionEvent::AddressChange(address_change)) + } + }, } } }