diff --git a/README.md b/README.md index bcd31b8f..d3316870 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ The main components of this repository are structured as follows: Multiplexing protocols are (mandatory) `Transport` upgrades. * `swarm/`: The implementation of `libp2p-swarm` building on `libp2p-core` - with the central interfaces `NetworkBehaviour` and `ProtocolsHandler` used + with the central interfaces `NetworkBehaviour` and `ConnectionHandler` used to implement application protocols (see `protocols/`). * `protocols/`: Implementations of application protocols based on the diff --git a/core/src/upgrade.rs b/core/src/upgrade.rs index d9edd649..2cb3c060 100644 --- a/core/src/upgrade.rs +++ b/core/src/upgrade.rs @@ -53,7 +53,7 @@ //! //! > **Note**: You can use the `apply_inbound` or `apply_outbound` methods to try upgrade a //! connection or substream. However if you use the recommended `Swarm` or -//! `ProtocolsHandler` APIs, the upgrade is automatically handled for you and you don't +//! `ConnectionHandler` APIs, the upgrade is automatically handled for you and you don't //! need to use these methods. //! diff --git a/examples/file-sharing.rs b/examples/file-sharing.rs index c1d203aa..183bd9d6 100644 --- a/examples/file-sharing.rs +++ b/examples/file-sharing.rs @@ -217,7 +217,7 @@ mod network { ProtocolSupport, RequestId, RequestResponse, RequestResponseCodec, RequestResponseEvent, RequestResponseMessage, ResponseChannel, }; - use libp2p::swarm::{ProtocolsHandlerUpgrErr, SwarmBuilder, SwarmEvent}; + use libp2p::swarm::{ConnectionHandlerUpgrErr, SwarmBuilder, SwarmEvent}; use libp2p::{NetworkBehaviour, Swarm}; use std::collections::{HashMap, HashSet}; use std::iter; @@ -404,7 +404,7 @@ mod network { &mut self, event: SwarmEvent< ComposedEvent, - EitherError, io::Error>, + EitherError, io::Error>, >, ) { match event { diff --git a/protocols/autonat/src/behaviour.rs b/protocols/autonat/src/behaviour.rs index b2e13b11..ce5b1a92 100644 --- a/protocols/autonat/src/behaviour.rs +++ b/protocols/autonat/src/behaviour.rs @@ -37,7 +37,7 @@ use libp2p_request_response::{ RequestResponseConfig, RequestResponseEvent, RequestResponseMessage, ResponseChannel, }; use libp2p_swarm::{ - DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, + DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, }; use std::{ collections::{HashMap, VecDeque}, @@ -294,7 +294,7 @@ impl Behaviour { } impl NetworkBehaviour for Behaviour { - type ProtocolsHandler = as NetworkBehaviour>::ProtocolsHandler; + type ConnectionHandler = as NetworkBehaviour>::ConnectionHandler; type OutEvent = Event; fn inject_connection_established( @@ -347,7 +347,7 @@ impl NetworkBehaviour for Behaviour { peer: &PeerId, conn: &ConnectionId, endpoint: &ConnectedPoint, - handler: ::Handler, + handler: ::Handler, remaining_established: usize, ) { self.inner @@ -363,7 +363,7 @@ impl NetworkBehaviour for Behaviour { fn inject_dial_failure( &mut self, peer: Option, - handler: Self::ProtocolsHandler, + handler: Self::ConnectionHandler, error: &DialError, ) { self.inner.inject_dial_failure(peer, handler, error); @@ -459,7 +459,7 @@ impl NetworkBehaviour for Behaviour { } } - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { self.inner.new_handler() } @@ -480,7 +480,7 @@ impl NetworkBehaviour for Behaviour { &mut self, local_addr: &Multiaddr, send_back_addr: &Multiaddr, - handler: Self::ProtocolsHandler, + handler: Self::ConnectionHandler, ) { self.inner .inject_listen_failure(local_addr, send_back_addr, handler) @@ -501,7 +501,7 @@ impl NetworkBehaviour for Behaviour { type Action = NetworkBehaviourAction< ::OutEvent, - ::ProtocolsHandler, + ::ConnectionHandler, >; // Trait implemented for `AsClient` as `AsServer` to handle events from the inner [`RequestResponse`] Protocol. diff --git a/protocols/dcutr/src/behaviour.rs b/protocols/dcutr/src/behaviour.rs index f1966abf..89314889 100644 --- a/protocols/dcutr/src/behaviour.rs +++ b/protocols/dcutr/src/behaviour.rs @@ -28,8 +28,8 @@ use libp2p_core::multiaddr::Protocol; use libp2p_core::{Multiaddr, PeerId}; use libp2p_swarm::dial_opts::{self, DialOpts}; use libp2p_swarm::{ - DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, - PollParameters, ProtocolsHandler, ProtocolsHandlerUpgrErr, + ConnectionHandler, ConnectionHandlerUpgrErr, DialError, IntoConnectionHandler, + NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use std::collections::{HashMap, HashSet, VecDeque}; use std::task::{Context, Poll}; @@ -62,7 +62,7 @@ pub enum UpgradeError { #[error("Failed to dial peer.")] Dial, #[error("Failed to establish substream: {0}.")] - Handler(ProtocolsHandlerUpgrErr), + Handler(ConnectionHandlerUpgrErr), } pub struct Behaviour { @@ -83,10 +83,10 @@ impl Behaviour { } impl NetworkBehaviour for Behaviour { - type ProtocolsHandler = handler::Prototype; + type ConnectionHandler = handler::Prototype; type OutEvent = Event; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { handler::Prototype::UnknownConnection } @@ -142,7 +142,7 @@ impl NetworkBehaviour for Behaviour { fn inject_dial_failure( &mut self, peer_id: Option, - handler: Self::ProtocolsHandler, + handler: Self::ConnectionHandler, _error: &DialError, ) { match handler { @@ -187,7 +187,7 @@ impl NetworkBehaviour for Behaviour { peer_id: &PeerId, connection_id: &ConnectionId, connected_point: &ConnectedPoint, - _handler: <::ProtocolsHandler as IntoProtocolsHandler>::Handler, + _handler: <::ConnectionHandler as IntoConnectionHandler>::Handler, _remaining_established: usize, ) { if !connected_point.is_relayed() { @@ -209,7 +209,7 @@ impl NetworkBehaviour for Behaviour { &mut self, event_source: PeerId, connection: ConnectionId, - handler_event: <::Handler as ProtocolsHandler>::OutEvent, + handler_event: <::Handler as ConnectionHandler>::OutEvent, ) { match handler_event { Either::Left(handler::relayed::Event::InboundConnectRequest { @@ -313,7 +313,7 @@ impl NetworkBehaviour for Behaviour { &mut self, _cx: &mut Context<'_>, poll_parameters: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(action) = self.queued_actions.pop_front() { return Poll::Ready(action.build(poll_parameters)); } diff --git a/protocols/dcutr/src/handler.rs b/protocols/dcutr/src/handler.rs index 4dcc0f4d..12eb8f40 100644 --- a/protocols/dcutr/src/handler.rs +++ b/protocols/dcutr/src/handler.rs @@ -23,9 +23,9 @@ use either::Either; use libp2p_core::connection::ConnectionId; use libp2p_core::upgrade::{self, DeniedUpgrade}; use libp2p_core::{ConnectedPoint, PeerId}; -use libp2p_swarm::protocols_handler::DummyProtocolsHandler; -use libp2p_swarm::protocols_handler::SendWrapper; -use libp2p_swarm::{IntoProtocolsHandler, ProtocolsHandler}; +use libp2p_swarm::handler::DummyConnectionHandler; +use libp2p_swarm::handler::SendWrapper; +use libp2p_swarm::{ConnectionHandler, IntoConnectionHandler}; pub mod direct; pub mod relayed; @@ -43,8 +43,8 @@ pub enum Role { Listener, } -impl IntoProtocolsHandler for Prototype { - type Handler = Either>; +impl IntoConnectionHandler for Prototype { + type Handler = Either>; fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { match self { @@ -52,7 +52,7 @@ impl IntoProtocolsHandler for Prototype { if endpoint.is_relayed() { Either::Left(relayed::Handler::new(endpoint.clone())) } else { - Either::Right(Either::Right(DummyProtocolsHandler::default())) + Either::Right(Either::Right(DummyConnectionHandler::default())) } } Self::DirectConnection { @@ -68,7 +68,7 @@ impl IntoProtocolsHandler for Prototype { } } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { match self { Prototype::UnknownConnection => upgrade::EitherUpgrade::A(SendWrapper( upgrade::EitherUpgrade::A(protocol::inbound::Upgrade {}), diff --git a/protocols/dcutr/src/handler/direct.rs b/protocols/dcutr/src/handler/direct.rs index 980e6e7f..7e0237d7 100644 --- a/protocols/dcutr/src/handler/direct.rs +++ b/protocols/dcutr/src/handler/direct.rs @@ -18,13 +18,13 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -//! [`ProtocolsHandler`] handling direct connection upgraded through a relayed connection. +//! [`ConnectionHandler`] handling direct connection upgraded through a relayed connection. use libp2p_core::connection::ConnectionId; use libp2p_core::upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade}; use libp2p_swarm::{ - KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + NegotiatedSubstream, SubstreamProtocol, }; use std::task::{Context, Poll}; use void::Void; @@ -48,10 +48,10 @@ impl Handler { } } -impl ProtocolsHandler for Handler { +impl ConnectionHandler for Handler { type InEvent = void::Void; type OutEvent = Event; - type Error = ProtocolsHandlerUpgrErr; + type Error = ConnectionHandlerUpgrErr; type InboundProtocol = DeniedUpgrade; type OutboundProtocol = DeniedUpgrade; type OutboundOpenInfo = Void; @@ -80,7 +80,7 @@ impl ProtocolsHandler for Handler { fn inject_dial_upgrade_error( &mut self, _: Self::OutboundOpenInfo, - _: ProtocolsHandlerUpgrErr< + _: ConnectionHandlerUpgrErr< >::Error, >, ) { @@ -94,7 +94,7 @@ impl ProtocolsHandler for Handler { &mut self, _: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -103,7 +103,7 @@ impl ProtocolsHandler for Handler { > { if !self.reported { self.reported = true; - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::DirectConnectionUpgradeSucceeded { relayed_connection_id: self.relayed_connection_id, }, diff --git a/protocols/dcutr/src/handler/relayed.rs b/protocols/dcutr/src/handler/relayed.rs index b44af7cd..dfa8eede 100644 --- a/protocols/dcutr/src/handler/relayed.rs +++ b/protocols/dcutr/src/handler/relayed.rs @@ -18,7 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -//! [`ProtocolsHandler`] handling relayed connection potentially upgraded to a direct connection. +//! [`ConnectionHandler`] handling relayed connection potentially upgraded to a direct connection. use crate::protocol; use futures::future::{BoxFuture, FutureExt}; @@ -28,10 +28,10 @@ use libp2p_core::either::{EitherError, EitherOutput}; use libp2p_core::multiaddr::Multiaddr; use libp2p_core::upgrade::{self, DeniedUpgrade, NegotiationError, UpgradeError}; use libp2p_core::ConnectedPoint; -use libp2p_swarm::protocols_handler::{InboundUpgradeSend, OutboundUpgradeSend}; +use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_swarm::{ - KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + NegotiatedSubstream, SubstreamProtocol, }; use std::collections::VecDeque; use std::fmt; @@ -81,11 +81,11 @@ pub enum Event { remote_addr: Multiaddr, }, InboundNegotiationFailed { - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, InboundConnectNegotiated(Vec), OutboundNegotiationFailed { - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, OutboundConnectNegotiated { remote_addrs: Vec, @@ -131,17 +131,17 @@ pub struct Handler { endpoint: ConnectedPoint, /// A pending fatal error that results in the connection being closed. pending_error: Option< - ProtocolsHandlerUpgrErr< + ConnectionHandlerUpgrErr< EitherError, >, >, /// Queue of events to return when polled. queued_events: VecDeque< - ProtocolsHandlerEvent< - ::OutboundProtocol, - ::OutboundOpenInfo, - ::OutEvent, - ::Error, + ConnectionHandlerEvent< + ::OutboundProtocol, + ::OutboundOpenInfo, + ::OutEvent, + ::Error, >, >, /// Inbound connects, accepted by the behaviour, pending completion. @@ -163,10 +163,10 @@ impl Handler { } } -impl ProtocolsHandler for Handler { +impl ConnectionHandler for Handler { type InEvent = Command; type OutEvent = Event; - type Error = ProtocolsHandlerUpgrErr< + type Error = ConnectionHandlerUpgrErr< EitherError, >; type InboundProtocol = upgrade::EitherUpgrade; @@ -199,9 +199,9 @@ impl ProtocolsHandler for Handler { EitherOutput::First(inbound_connect) => { let remote_addr = match &self.endpoint { ConnectedPoint::Dialer { address, role_override: _ } => address.clone(), - ConnectedPoint::Listener { ..} => unreachable!("`::listen_protocol` denies all incoming substreams as a listener."), + ConnectedPoint::Listener { ..} => unreachable!("`::listen_protocol` denies all incoming substreams as a listener."), }; - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::InboundConnectRequest { inbound_connect, remote_addr, @@ -224,7 +224,7 @@ impl ProtocolsHandler for Handler { self.endpoint.is_listener(), "A connection dialer never initiates a connection upgrade." ); - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::OutboundConnectNegotiated { remote_addrs: obs_addrs, attempt, @@ -236,7 +236,7 @@ impl ProtocolsHandler for Handler { match event { Command::Connect { obs_addrs, attempt } => { self.queued_events - .push_back(ProtocolsHandlerEvent::OutboundSubstreamRequest { + .push_back(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new( protocol::outbound::Upgrade::new(obs_addrs), attempt, @@ -259,31 +259,31 @@ impl ProtocolsHandler for Handler { fn inject_listen_upgrade_error( &mut self, _: Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { match error { - ProtocolsHandlerUpgrErr::Timeout => { - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + ConnectionHandlerUpgrErr::Timeout => { + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::InboundNegotiationFailed { - error: ProtocolsHandlerUpgrErr::Timeout, + error: ConnectionHandlerUpgrErr::Timeout, }, )); } - ProtocolsHandlerUpgrErr::Timer => { - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + ConnectionHandlerUpgrErr::Timer => { + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::InboundNegotiationFailed { - error: ProtocolsHandlerUpgrErr::Timer, + error: ConnectionHandlerUpgrErr::Timer, }, )); } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { // The remote merely doesn't support the DCUtR protocol. // This is no reason to close the connection, which may // successfully communicate with other protocols already. self.keep_alive = KeepAlive::No; - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::InboundNegotiationFailed { - error: ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( NegotiationError::Failed, )), }, @@ -305,25 +305,25 @@ impl ProtocolsHandler for Handler { fn inject_dial_upgrade_error( &mut self, _open_info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { self.keep_alive = KeepAlive::No; match error { - ProtocolsHandlerUpgrErr::Timeout => { - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + ConnectionHandlerUpgrErr::Timeout => { + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::OutboundNegotiationFailed { - error: ProtocolsHandlerUpgrErr::Timeout, + error: ConnectionHandlerUpgrErr::Timeout, }, )); } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { // The remote merely doesn't support the DCUtR protocol. // This is no reason to close the connection, which may // successfully communicate with other protocols already. - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::OutboundNegotiationFailed { - error: ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( NegotiationError::Failed, )), }, @@ -346,7 +346,7 @@ impl ProtocolsHandler for Handler { &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -356,7 +356,7 @@ impl ProtocolsHandler for Handler { // Check for a pending (fatal) error. if let Some(err) = self.pending_error.take() { // The handler will not be polled again by the `Swarm`. - return Poll::Ready(ProtocolsHandlerEvent::Close(err)); + return Poll::Ready(ConnectionHandlerEvent::Close(err)); } // Return queued events. @@ -367,13 +367,13 @@ impl ProtocolsHandler for Handler { while let Poll::Ready(Some(result)) = self.inbound_connects.poll_next_unpin(cx) { match result { Ok(addresses) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::InboundConnectNegotiated(addresses), )); } Err(e) => { - return Poll::Ready(ProtocolsHandlerEvent::Close( - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))), + return Poll::Ready(ConnectionHandlerEvent::Close( + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))), )) } } diff --git a/protocols/floodsub/src/layer.rs b/protocols/floodsub/src/layer.rs index 6f22e804..059ff505 100644 --- a/protocols/floodsub/src/layer.rs +++ b/protocols/floodsub/src/layer.rs @@ -281,10 +281,10 @@ impl Floodsub { } impl NetworkBehaviour for Floodsub { - type ProtocolsHandler = OneShotHandler; + type ConnectionHandler = OneShotHandler; type OutEvent = FloodsubEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { Default::default() } @@ -327,7 +327,7 @@ impl NetworkBehaviour for Floodsub { id: &PeerId, _: &ConnectionId, _: &ConnectedPoint, - _: Self::ProtocolsHandler, + _: Self::ConnectionHandler, remaining_established: usize, ) { if remaining_established > 0 { @@ -474,7 +474,7 @@ impl NetworkBehaviour for Floodsub { &mut self, _: &mut Context<'_>, _: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(event) = self.events.pop_front() { return Poll::Ready(event); } diff --git a/protocols/gossipsub/src/behaviour.rs b/protocols/gossipsub/src/behaviour.rs index b8232ece..4f3fdcfb 100644 --- a/protocols/gossipsub/src/behaviour.rs +++ b/protocols/gossipsub/src/behaviour.rs @@ -42,7 +42,7 @@ use libp2p_core::{ }; use libp2p_swarm::{ dial_opts::{self, DialOpts}, - IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, + IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use wasm_timer::Instant; @@ -3051,10 +3051,10 @@ where C: Send + 'static + DataTransform, F: Send + 'static + TopicSubscriptionFilter, { - type ProtocolsHandler = GossipsubHandler; + type ConnectionHandler = GossipsubHandler; type OutEvent = GossipsubEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { GossipsubHandler::new( self.config.protocol_id_prefix().clone(), self.config.max_transmit_size(), @@ -3156,7 +3156,7 @@ where peer_id: &PeerId, connection_id: &ConnectionId, endpoint: &ConnectedPoint, - _: ::Handler, + _: ::Handler, remaining_established: usize, ) { // Remove IP from peer scoring system @@ -3443,7 +3443,7 @@ where &mut self, cx: &mut Context<'_>, _: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(event) = self.events.pop_front() { return Poll::Ready(event.map_in(|e: Arc| { // clone send event reference if others references are present diff --git a/protocols/gossipsub/src/handler.rs b/protocols/gossipsub/src/handler.rs index 7fc1bd43..c0034f09 100644 --- a/protocols/gossipsub/src/handler.rs +++ b/protocols/gossipsub/src/handler.rs @@ -27,8 +27,9 @@ use futures::prelude::*; use futures::StreamExt; use instant::Instant; use libp2p_core::upgrade::{InboundUpgrade, NegotiationError, OutboundUpgrade, UpgradeError}; -use libp2p_swarm::protocols_handler::{ - KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, +use libp2p_swarm::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + SubstreamProtocol, }; use libp2p_swarm::NegotiatedSubstream; use log::{error, trace, warn}; @@ -123,7 +124,7 @@ pub struct GossipsubHandler { idle_timeout: Duration, /// Collection of errors from attempting an upgrade. - upgrade_errors: VecDeque>, + upgrade_errors: VecDeque>, /// Flag determining whether to maintain the connection to the peer. keep_alive: KeepAlive, @@ -196,7 +197,7 @@ impl GossipsubHandler { } } -impl ProtocolsHandler for GossipsubHandler { +impl ConnectionHandler for GossipsubHandler { type InEvent = GossipsubHandlerIn; type OutEvent = HandlerEvent; type Error = GossipsubHandlerError; @@ -285,7 +286,7 @@ impl ProtocolsHandler for GossipsubHandler { fn inject_dial_upgrade_error( &mut self, _: Self::OutboundOpenInfo, - e: ProtocolsHandlerUpgrErr< + e: ConnectionHandlerUpgrErr< >::Error, >, ) { @@ -302,7 +303,7 @@ impl ProtocolsHandler for GossipsubHandler { &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -313,12 +314,12 @@ impl ProtocolsHandler for GossipsubHandler { if let Some(error) = self.upgrade_errors.pop_front() { let reported_error = match error { // Timeout errors get mapped to NegotiationTimeout and we close the connection. - ProtocolsHandlerUpgrErr::Timeout | ProtocolsHandlerUpgrErr::Timer => { + ConnectionHandlerUpgrErr::Timeout | ConnectionHandlerUpgrErr::Timer => { Some(GossipsubHandlerError::NegotiationTimeout) } // There was an error post negotiation, close the connection. - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)) => Some(e), - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(negotiation_error)) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)) => Some(e), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(negotiation_error)) => { match negotiation_error { NegotiationError::Failed => { // The protocol is not supported @@ -329,7 +330,7 @@ impl ProtocolsHandler for GossipsubHandler { self.inbound_substream = None; self.outbound_substream = None; self.keep_alive = KeepAlive::No; - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( HandlerEvent::PeerKind(PeerKind::NotSupported), )); } else { @@ -345,14 +346,14 @@ impl ProtocolsHandler for GossipsubHandler { // If there was a fatal error, close the connection. if let Some(error) = reported_error { - return Poll::Ready(ProtocolsHandlerEvent::Close(error)); + return Poll::Ready(ConnectionHandlerEvent::Close(error)); } } if !self.peer_kind_sent { if let Some(peer_kind) = self.peer_kind.as_ref() { self.peer_kind_sent = true; - return Poll::Ready(ProtocolsHandlerEvent::Custom(HandlerEvent::PeerKind( + return Poll::Ready(ConnectionHandlerEvent::Custom(HandlerEvent::PeerKind( peer_kind.clone(), ))); } @@ -360,7 +361,7 @@ impl ProtocolsHandler for GossipsubHandler { if self.inbound_substreams_created > MAX_SUBSTREAM_CREATION { // Too many inbound substreams have been created, end the connection. - return Poll::Ready(ProtocolsHandlerEvent::Close( + return Poll::Ready(ConnectionHandlerEvent::Close( GossipsubHandlerError::MaxInboundSubstreams, )); } @@ -371,14 +372,14 @@ impl ProtocolsHandler for GossipsubHandler { && !self.outbound_substream_establishing { if self.outbound_substreams_created >= MAX_SUBSTREAM_CREATION { - return Poll::Ready(ProtocolsHandlerEvent::Close( + return Poll::Ready(ConnectionHandlerEvent::Close( GossipsubHandlerError::MaxOutboundSubstreams, )); } let message = self.send_queue.remove(0); self.send_queue.shrink_to_fit(); self.outbound_substream_establishing = true; - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: self.listen_protocol.clone().map_info(|()| message), }); } @@ -398,7 +399,7 @@ impl ProtocolsHandler for GossipsubHandler { } self.inbound_substream = Some(InboundSubstreamState::WaitingInput(substream)); - return Poll::Ready(ProtocolsHandlerEvent::Custom(message)); + return Poll::Ready(ConnectionHandlerEvent::Custom(message)); } Poll::Ready(Some(Err(error))) => { match error { @@ -496,13 +497,13 @@ impl ProtocolsHandler for GossipsubHandler { } Err(e) => { error!("Error sending message: {}", e); - return Poll::Ready(ProtocolsHandlerEvent::Close(e)); + return Poll::Ready(ConnectionHandlerEvent::Close(e)); } } } Poll::Ready(Err(e)) => { error!("Outbound substream error while sending output: {:?}", e); - return Poll::Ready(ProtocolsHandlerEvent::Close(e)); + return Poll::Ready(ConnectionHandlerEvent::Close(e)); } Poll::Pending => { self.keep_alive = KeepAlive::Yes; @@ -523,7 +524,9 @@ impl ProtocolsHandler for GossipsubHandler { self.outbound_substream = Some(OutboundSubstreamState::WaitingOutput(substream)) } - Poll::Ready(Err(e)) => return Poll::Ready(ProtocolsHandlerEvent::Close(e)), + Poll::Ready(Err(e)) => { + return Poll::Ready(ConnectionHandlerEvent::Close(e)) + } Poll::Pending => { self.keep_alive = KeepAlive::Yes; self.outbound_substream = @@ -544,7 +547,7 @@ impl ProtocolsHandler for GossipsubHandler { } Poll::Ready(Err(e)) => { warn!("Outbound substream error while closing: {:?}", e); - return Poll::Ready(ProtocolsHandlerEvent::Close( + return Poll::Ready(ConnectionHandlerEvent::Close( io::Error::new( io::ErrorKind::BrokenPipe, "Failed to close outbound substream", diff --git a/protocols/identify/src/handler.rs b/protocols/identify/src/handler.rs index 4ceb8d25..f22c0bd3 100644 --- a/protocols/identify/src/handler.rs +++ b/protocols/identify/src/handler.rs @@ -28,8 +28,8 @@ use libp2p_core::upgrade::{ EitherUpgrade, InboundUpgrade, OutboundUpgrade, SelectUpgrade, UpgradeError, }; use libp2p_swarm::{ - KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + NegotiatedSubstream, SubstreamProtocol, }; use smallvec::SmallVec; use std::{io, pin::Pin, task::Context, task::Poll, time::Duration}; @@ -42,7 +42,7 @@ use std::{io, pin::Pin, task::Context, task::Poll, time::Duration}; pub struct IdentifyHandler { /// Pending events to yield. events: SmallVec< - [ProtocolsHandlerEvent< + [ConnectionHandlerEvent< EitherUpgrade>, (), IdentifyHandlerEvent, @@ -70,7 +70,7 @@ pub enum IdentifyHandlerEvent { /// We received a request for identification. Identify(ReplySubstream), /// Failed to identify the remote. - IdentificationError(ProtocolsHandlerUpgrErr), + IdentificationError(ConnectionHandlerUpgrErr), } /// Identifying information of the local node that is pushed to a remote. @@ -89,7 +89,7 @@ impl IdentifyHandler { } } -impl ProtocolsHandler for IdentifyHandler { +impl ConnectionHandler for IdentifyHandler { type InEvent = IdentifyPush; type OutEvent = IdentifyHandlerEvent; type Error = io::Error; @@ -111,10 +111,10 @@ impl ProtocolsHandler for IdentifyHandler { _: Self::InboundOpenInfo, ) { match output { - EitherOutput::First(substream) => self.events.push(ProtocolsHandlerEvent::Custom( + EitherOutput::First(substream) => self.events.push(ConnectionHandlerEvent::Custom( IdentifyHandlerEvent::Identify(substream), )), - EitherOutput::Second(info) => self.events.push(ProtocolsHandlerEvent::Custom( + EitherOutput::Second(info) => self.events.push(ConnectionHandlerEvent::Custom( IdentifyHandlerEvent::Identified(info), )), } @@ -127,12 +127,12 @@ impl ProtocolsHandler for IdentifyHandler { ) { match output { EitherOutput::First(remote_info) => { - self.events.push(ProtocolsHandlerEvent::Custom( + self.events.push(ConnectionHandlerEvent::Custom( IdentifyHandlerEvent::Identified(remote_info), )); self.keep_alive = KeepAlive::No; } - EitherOutput::Second(()) => self.events.push(ProtocolsHandlerEvent::Custom( + EitherOutput::Second(()) => self.events.push(ConnectionHandlerEvent::Custom( IdentifyHandlerEvent::IdentificationPushed, )), } @@ -140,7 +140,7 @@ impl ProtocolsHandler for IdentifyHandler { fn inject_event(&mut self, IdentifyPush(push): Self::InEvent) { self.events - .push(ProtocolsHandlerEvent::OutboundSubstreamRequest { + .push(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new( EitherUpgrade::B(IdentifyPushProtocol::outbound(push)), (), @@ -151,7 +151,7 @@ impl ProtocolsHandler for IdentifyHandler { fn inject_dial_upgrade_error( &mut self, _info: Self::OutboundOpenInfo, - err: ProtocolsHandlerUpgrErr< + err: ConnectionHandlerUpgrErr< >::Error, >, ) { @@ -160,7 +160,7 @@ impl ProtocolsHandler for IdentifyHandler { UpgradeError::Apply(EitherError::A(ioe)) => UpgradeError::Apply(ioe), UpgradeError::Apply(EitherError::B(ioe)) => UpgradeError::Apply(ioe), }); - self.events.push(ProtocolsHandlerEvent::Custom( + self.events.push(ConnectionHandlerEvent::Custom( IdentifyHandlerEvent::IdentificationError(err), )); self.keep_alive = KeepAlive::No; @@ -175,7 +175,7 @@ impl ProtocolsHandler for IdentifyHandler { &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, IdentifyHandlerEvent, @@ -191,7 +191,7 @@ impl ProtocolsHandler for IdentifyHandler { Poll::Pending => Poll::Pending, Poll::Ready(()) => { self.next_id.reset(self.interval); - let ev = ProtocolsHandlerEvent::OutboundSubstreamRequest { + let ev = ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new(EitherUpgrade::A(IdentifyProtocol), ()), }; Poll::Ready(ev) diff --git a/protocols/identify/src/identify.rs b/protocols/identify/src/identify.rs index f5ab6944..54c00ab8 100644 --- a/protocols/identify/src/identify.rs +++ b/protocols/identify/src/identify.rs @@ -29,9 +29,8 @@ use libp2p_core::{ }; use libp2p_swarm::{ dial_opts::{self, DialOpts}, - AddressScore, DialError, IntoProtocolsHandler, NegotiatedSubstream, NetworkBehaviour, - NetworkBehaviourAction, NotifyHandler, PollParameters, ProtocolsHandler, - ProtocolsHandlerUpgrErr, + AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError, IntoConnectionHandler, + NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use lru::LruCache; use std::{ @@ -213,10 +212,10 @@ impl Identify { } impl NetworkBehaviour for Identify { - type ProtocolsHandler = IdentifyHandler; + type ConnectionHandler = IdentifyHandler; type OutEvent = IdentifyEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { IdentifyHandler::new(self.config.initial_delay, self.config.interval) } @@ -254,7 +253,7 @@ impl NetworkBehaviour for Identify { peer_id: &PeerId, conn: &ConnectionId, _: &ConnectedPoint, - _: ::Handler, + _: ::Handler, remaining_established: usize, ) { if remaining_established == 0 { @@ -268,7 +267,7 @@ impl NetworkBehaviour for Identify { fn inject_dial_failure( &mut self, peer_id: Option, - _: Self::ProtocolsHandler, + _: Self::ConnectionHandler, error: &DialError, ) { if let Some(peer_id) = peer_id { @@ -302,7 +301,7 @@ impl NetworkBehaviour for Identify { &mut self, peer_id: PeerId, connection: ConnectionId, - event: ::OutEvent, + event: ::OutEvent, ) { match event { IdentifyHandlerEvent::Identified(mut info) => { @@ -356,7 +355,7 @@ impl NetworkBehaviour for Identify { &mut self, cx: &mut Context<'_>, params: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(event) = self.events.pop_front() { return Poll::Ready(event); } @@ -433,7 +432,7 @@ impl NetworkBehaviour for Identify { Poll::Ready(Err(err)) => { let event = IdentifyEvent::Error { peer_id: peer, - error: ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply( + error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply( err, )), }; @@ -486,7 +485,7 @@ pub enum IdentifyEvent { /// The peer with whom the error originated. peer_id: PeerId, /// The error that occurred. - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, } diff --git a/protocols/kad/src/behaviour.rs b/protocols/kad/src/behaviour.rs index be45798d..fe56eaa6 100644 --- a/protocols/kad/src/behaviour.rs +++ b/protocols/kad/src/behaviour.rs @@ -1783,10 +1783,10 @@ where for<'a> TStore: RecordStore<'a>, TStore: Send + 'static, { - type ProtocolsHandler = KademliaHandlerProto; + type ConnectionHandler = KademliaHandlerProto; type OutEvent = KademliaEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { KademliaHandlerProto::new(KademliaHandlerConfig { protocol_config: self.protocol_config.clone(), allow_listening: true, @@ -1916,7 +1916,7 @@ where fn inject_dial_failure( &mut self, peer_id: Option, - _: Self::ProtocolsHandler, + _: Self::ConnectionHandler, error: &DialError, ) { let peer_id = match peer_id { @@ -1962,7 +1962,7 @@ where id: &PeerId, _: &ConnectionId, _: &ConnectedPoint, - _: ::Handler, + _: ::Handler, remaining_established: usize, ) { if remaining_established == 0 { @@ -2243,7 +2243,7 @@ where &mut self, cx: &mut Context<'_>, parameters: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { let now = Instant::now(); // Calculate the available capacity for queries triggered by background jobs. diff --git a/protocols/kad/src/handler.rs b/protocols/kad/src/handler.rs index 2b3e92ff..30d22c90 100644 --- a/protocols/kad/src/handler.rs +++ b/protocols/kad/src/handler.rs @@ -31,8 +31,8 @@ use libp2p_core::{ ConnectedPoint, PeerId, }; use libp2p_swarm::{ - IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, + KeepAlive, NegotiatedSubstream, SubstreamProtocol, }; use log::trace; use std::{ @@ -54,14 +54,14 @@ impl KademliaHandlerProto { } } -impl IntoProtocolsHandler for KademliaHandlerProto { +impl IntoConnectionHandler for KademliaHandlerProto { type Handler = KademliaHandler; fn into_handler(self, _: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { KademliaHandler::new(self.config, endpoint.clone()) } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { if self.config.allow_listening { upgrade::EitherUpgrade::A(self.config.protocol_config.clone()) } else { @@ -297,7 +297,7 @@ pub enum KademliaHandlerEvent { #[derive(Debug)] pub enum KademliaHandlerQueryErr { /// Error while trying to perform the query. - Upgrade(ProtocolsHandlerUpgrErr), + Upgrade(ConnectionHandlerUpgrErr), /// Received an answer that doesn't correspond to the request. UnexpectedMessage, /// I/O error in the substream. @@ -333,8 +333,8 @@ impl error::Error for KademliaHandlerQueryErr { } } -impl From> for KademliaHandlerQueryErr { - fn from(err: ProtocolsHandlerUpgrErr) -> Self { +impl From> for KademliaHandlerQueryErr { + fn from(err: ConnectionHandlerUpgrErr) -> Self { KademliaHandlerQueryErr::Upgrade(err) } } @@ -466,7 +466,7 @@ impl KademliaHandler { } } -impl ProtocolsHandler for KademliaHandler +impl ConnectionHandler for KademliaHandler where TUserData: Clone + fmt::Debug + Send + 'static, { @@ -676,7 +676,7 @@ where fn inject_dial_upgrade_error( &mut self, (_, user_data): Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, ) { // TODO: cache the fact that the remote doesn't support kademlia at all, so that we don't // continue trying @@ -694,7 +694,7 @@ where &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -707,7 +707,7 @@ where if let ProtocolStatus::Confirmed = self.protocol_status { self.protocol_status = ProtocolStatus::Reported; - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( KademliaHandlerEvent::ProtocolConfirmed { endpoint: self.endpoint.clone(), }, @@ -778,7 +778,7 @@ fn advance_substream( ) -> ( Option>, Option< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< KademliaProtocolConfig, (KadRequestMsg, Option), KademliaHandlerEvent, @@ -789,7 +789,7 @@ fn advance_substream( ) { match state { SubstreamState::OutPendingOpen(msg, user_data) => { - let ev = ProtocolsHandlerEvent::OutboundSubstreamRequest { + let ev = ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new(upgrade, (msg, user_data)), }; (None, Some(ev), false) @@ -804,7 +804,7 @@ fn advance_substream( ), Err(error) => { let event = user_data.map(|user_data| { - ProtocolsHandlerEvent::Custom(KademliaHandlerEvent::QueryError { + ConnectionHandlerEvent::Custom(KademliaHandlerEvent::QueryError { error: KademliaHandlerQueryErr::Io(error), user_data, }) @@ -820,7 +820,7 @@ fn advance_substream( ), Poll::Ready(Err(error)) => { let event = user_data.map(|user_data| { - ProtocolsHandlerEvent::Custom(KademliaHandlerEvent::QueryError { + ConnectionHandlerEvent::Custom(KademliaHandlerEvent::QueryError { error: KademliaHandlerQueryErr::Io(error), user_data, }) @@ -850,7 +850,7 @@ fn advance_substream( ), Poll::Ready(Err(error)) => { let event = user_data.map(|user_data| { - ProtocolsHandlerEvent::Custom(KademliaHandlerEvent::QueryError { + ConnectionHandlerEvent::Custom(KademliaHandlerEvent::QueryError { error: KademliaHandlerQueryErr::Io(error), user_data, }) @@ -867,7 +867,7 @@ fn advance_substream( let event = process_kad_response(msg, user_data); ( Some(new_state), - Some(ProtocolsHandlerEvent::Custom(event)), + Some(ConnectionHandlerEvent::Custom(event)), true, ) } @@ -881,20 +881,20 @@ fn advance_substream( error: KademliaHandlerQueryErr::Io(error), user_data, }; - (None, Some(ProtocolsHandlerEvent::Custom(event)), false) + (None, Some(ConnectionHandlerEvent::Custom(event)), false) } Poll::Ready(None) => { let event = KademliaHandlerEvent::QueryError { error: KademliaHandlerQueryErr::Io(io::ErrorKind::UnexpectedEof.into()), user_data, }; - (None, Some(ProtocolsHandlerEvent::Custom(event)), false) + (None, Some(ConnectionHandlerEvent::Custom(event)), false) } } } SubstreamState::OutReportError(error, user_data) => { let event = KademliaHandlerEvent::QueryError { error, user_data }; - (None, Some(ProtocolsHandlerEvent::Custom(event)), false) + (None, Some(ConnectionHandlerEvent::Custom(event)), false) } SubstreamState::OutClosing(mut stream) => match Sink::poll_close(Pin::new(&mut stream), cx) { @@ -908,7 +908,7 @@ fn advance_substream( if let Ok(ev) = process_kad_request(msg, id) { ( Some(SubstreamState::InWaitingUser(id, substream)), - Some(ProtocolsHandlerEvent::Custom(ev)), + Some(ConnectionHandlerEvent::Custom(ev)), false, ) } else { diff --git a/protocols/mdns/src/behaviour.rs b/protocols/mdns/src/behaviour.rs index 5e58f8bc..1c22a068 100644 --- a/protocols/mdns/src/behaviour.rs +++ b/protocols/mdns/src/behaviour.rs @@ -28,8 +28,8 @@ use if_watch::{IfEvent, IfWatcher}; use libp2p_core::connection::ListenerId; use libp2p_core::{Multiaddr, PeerId}; use libp2p_swarm::{ - protocols_handler::DummyProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, - PollParameters, ProtocolsHandler, + handler::DummyConnectionHandler, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, + PollParameters, }; use smallvec::SmallVec; use std::collections::hash_map::{Entry, HashMap}; @@ -96,11 +96,11 @@ impl Mdns { } impl NetworkBehaviour for Mdns { - type ProtocolsHandler = DummyProtocolsHandler; + type ConnectionHandler = DummyConnectionHandler; type OutEvent = MdnsEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { - DummyProtocolsHandler::default() + fn new_handler(&mut self) -> Self::ConnectionHandler { + DummyConnectionHandler::default() } fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec { @@ -115,7 +115,7 @@ impl NetworkBehaviour for Mdns { &mut self, _: PeerId, _: libp2p_core::connection::ConnectionId, - ev: ::OutEvent, + ev: ::OutEvent, ) { void::unreachable(ev) } @@ -132,7 +132,7 @@ impl NetworkBehaviour for Mdns { peer: &PeerId, _: &libp2p_core::connection::ConnectionId, _: &libp2p_core::ConnectedPoint, - _: Self::ProtocolsHandler, + _: Self::ConnectionHandler, remaining_established: usize, ) { if remaining_established == 0 { @@ -144,7 +144,7 @@ impl NetworkBehaviour for Mdns { &mut self, cx: &mut Context<'_>, params: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { // Poll ifwatch. while let Poll::Ready(event) = Pin::new(&mut self.if_watch).poll(cx) { match event { diff --git a/protocols/ping/src/handler.rs b/protocols/ping/src/handler.rs index afdb882e..87937687 100644 --- a/protocols/ping/src/handler.rs +++ b/protocols/ping/src/handler.rs @@ -24,8 +24,8 @@ use futures::prelude::*; use futures_timer::Delay; use libp2p_core::{upgrade::NegotiationError, UpgradeError}; use libp2p_swarm::{ - KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + NegotiatedSubstream, SubstreamProtocol, }; use std::collections::VecDeque; use std::{ @@ -108,7 +108,7 @@ impl Config { /// is determined by other protocol handlers. /// /// If the maximum number of allowed ping failures is reached, the - /// connection is always terminated as a result of [`ProtocolsHandler::poll`] + /// connection is always terminated as a result of [`ConnectionHandler::poll`] /// returning an error, regardless of the keep-alive setting. pub fn with_keep_alive(mut self, b: bool) -> Self { self.keep_alive = b; @@ -215,7 +215,7 @@ impl Handler { } } -impl ProtocolsHandler for Handler { +impl ConnectionHandler for Handler { type InEvent = Void; type OutEvent = crate::Result; type Error = Failure; @@ -239,18 +239,18 @@ impl ProtocolsHandler for Handler { fn inject_event(&mut self, _: Void) {} - fn inject_dial_upgrade_error(&mut self, _info: (), error: ProtocolsHandlerUpgrErr) { + fn inject_dial_upgrade_error(&mut self, _info: (), error: ConnectionHandlerUpgrErr) { self.outbound = None; // Request a new substream on the next `poll`. let error = match error { - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { debug_assert_eq!(self.state, State::Active); self.state = State::Inactive { reported: false }; return; } // Note: This timeout only covers protocol negotiation. - ProtocolsHandlerUpgrErr::Timeout => Failure::Timeout, + ConnectionHandlerUpgrErr::Timeout => Failure::Timeout, e => Failure::Other { error: Box::new(e) }, }; @@ -268,14 +268,14 @@ impl ProtocolsHandler for Handler { fn poll( &mut self, cx: &mut Context<'_>, - ) -> Poll> { + ) -> Poll> { match self.state { State::Inactive { reported: true } => { return Poll::Pending; // nothing to do on this connection } State::Inactive { reported: false } => { self.state = State::Inactive { reported: true }; - return Poll::Ready(ProtocolsHandlerEvent::Custom(Err(Failure::Unsupported))); + return Poll::Ready(ConnectionHandlerEvent::Custom(Err(Failure::Unsupported))); } State::Active => {} } @@ -291,7 +291,7 @@ impl ProtocolsHandler for Handler { Poll::Ready(Ok(stream)) => { // A ping from a remote peer has been answered, wait for the next. self.inbound = Some(protocol::recv_ping(stream).boxed()); - return Poll::Ready(ProtocolsHandlerEvent::Custom(Ok(Success::Pong))); + return Poll::Ready(ConnectionHandlerEvent::Custom(Ok(Success::Pong))); } } } @@ -313,10 +313,10 @@ impl ProtocolsHandler for Handler { if self.failures > 1 || self.config.max_failures.get() > 1 { if self.failures >= self.config.max_failures.get() { log::debug!("Too many failures ({}). Closing connection.", self.failures); - return Poll::Ready(ProtocolsHandlerEvent::Close(error)); + return Poll::Ready(ConnectionHandlerEvent::Close(error)); } - return Poll::Ready(ProtocolsHandlerEvent::Custom(Err(error))); + return Poll::Ready(ConnectionHandlerEvent::Custom(Err(error))); } } @@ -335,7 +335,7 @@ impl ProtocolsHandler for Handler { self.failures = 0; self.timer.reset(self.config.interval); self.outbound = Some(PingState::Idle(stream)); - return Poll::Ready(ProtocolsHandlerEvent::Custom(Ok(Success::Ping { + return Poll::Ready(ConnectionHandlerEvent::Custom(Ok(Success::Ping { rtt, }))); } @@ -362,7 +362,7 @@ impl ProtocolsHandler for Handler { self.outbound = Some(PingState::OpenStream); let protocol = SubstreamProtocol::new(protocol::Ping, ()) .with_timeout(self.config.timeout); - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol, }); } diff --git a/protocols/ping/src/lib.rs b/protocols/ping/src/lib.rs index e0c6bdf1..75aee971 100644 --- a/protocols/ping/src/lib.rs +++ b/protocols/ping/src/lib.rs @@ -103,10 +103,10 @@ impl Default for Behaviour { } impl NetworkBehaviour for Behaviour { - type ProtocolsHandler = Handler; + type ConnectionHandler = Handler; type OutEvent = Event; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { Handler::new(self.config.clone()) } @@ -118,7 +118,7 @@ impl NetworkBehaviour for Behaviour { &mut self, _: &mut Context<'_>, _: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(e) = self.events.pop_back() { Poll::Ready(NetworkBehaviourAction::GenerateEvent(e)) } else { diff --git a/protocols/relay/src/v1/behaviour.rs b/protocols/relay/src/v1/behaviour.rs index 88219410..b0e3ed8d 100644 --- a/protocols/relay/src/v1/behaviour.rs +++ b/protocols/relay/src/v1/behaviour.rs @@ -31,7 +31,7 @@ use libp2p_core::multiaddr::Multiaddr; use libp2p_core::PeerId; use libp2p_swarm::{ dial_opts::{self, DialOpts}, - DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use std::collections::{hash_map::Entry, HashMap, HashSet, VecDeque}; @@ -154,10 +154,10 @@ impl Relay { } impl NetworkBehaviour for Relay { - type ProtocolsHandler = RelayHandlerProto; + type ConnectionHandler = RelayHandlerProto; type OutEvent = (); - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { RelayHandlerProto { config: RelayHandlerConfig { connection_idle_timeout: self.config.connection_idle_timeout, @@ -301,7 +301,7 @@ impl NetworkBehaviour for Relay { fn inject_dial_failure( &mut self, peer_id: Option, - _: Self::ProtocolsHandler, + _: Self::ConnectionHandler, error: &DialError, ) { if let DialError::DialPeerConditionFalse( @@ -352,7 +352,7 @@ impl NetworkBehaviour for Relay { peer: &PeerId, connection: &ConnectionId, _: &ConnectedPoint, - _: ::Handler, + _: ::Handler, remaining_established: usize, ) { // Remove connection from the set of connections for the given peer. In case the set is @@ -570,7 +570,7 @@ impl NetworkBehaviour for Relay { &mut self, cx: &mut Context<'_>, poll_parameters: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if !self.outbox_to_listeners.is_empty() { let relay_peer_id = self.outbox_to_listeners[0].0; diff --git a/protocols/relay/src/v1/handler.rs b/protocols/relay/src/v1/handler.rs index f6fd3216..97bfff7c 100644 --- a/protocols/relay/src/v1/handler.rs +++ b/protocols/relay/src/v1/handler.rs @@ -29,8 +29,8 @@ use libp2p_core::connection::ConnectionId; use libp2p_core::either::{EitherError, EitherOutput}; use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId}; use libp2p_swarm::{ - IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, + KeepAlive, NegotiatedSubstream, SubstreamProtocol, }; use log::warn; use std::fmt; @@ -46,7 +46,7 @@ pub struct RelayHandlerProto { pub config: RelayHandlerConfig, } -impl IntoProtocolsHandler for RelayHandlerProto { +impl IntoConnectionHandler for RelayHandlerProto { type Handler = RelayHandler; fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { @@ -57,7 +57,7 @@ impl IntoProtocolsHandler for RelayHandlerProto { ) } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { protocol::RelayListen::new() } } @@ -118,7 +118,7 @@ pub struct RelayHandler { keep_alive: KeepAlive, /// A pending fatal error that results in the connection being closed. pending_error: Option< - ProtocolsHandlerUpgrErr< + ConnectionHandlerUpgrErr< EitherError< protocol::RelayListenError, EitherError, @@ -347,10 +347,10 @@ impl RelayHandler { } } -impl ProtocolsHandler for RelayHandler { +impl ConnectionHandler for RelayHandler { type InEvent = RelayHandlerIn; type OutEvent = RelayHandlerEvent; - type Error = ProtocolsHandlerUpgrErr< + type Error = ConnectionHandlerUpgrErr< EitherError< protocol::RelayListenError, EitherError, @@ -478,22 +478,22 @@ impl ProtocolsHandler for RelayHandler { fn inject_listen_upgrade_error( &mut self, _: Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, ) { match error { - ProtocolsHandlerUpgrErr::Timeout | ProtocolsHandlerUpgrErr::Timer => {} - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Timeout | ConnectionHandlerUpgrErr::Timer => {} + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, )) => {} - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)), )); } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::A(error)), )) } @@ -503,7 +503,7 @@ impl ProtocolsHandler for RelayHandler { fn inject_dial_upgrade_error( &mut self, open_info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr< + error: ConnectionHandlerUpgrErr< EitherError, >, ) { @@ -513,20 +513,20 @@ impl ProtocolsHandler for RelayHandler { request_id, } => { match error { - ProtocolsHandlerUpgrErr::Timeout | ProtocolsHandlerUpgrErr::Timer => {} - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Timeout | ConnectionHandlerUpgrErr::Timer => {} + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, )) => {} - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), ), )); } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( EitherError::A(error), )) => match error { protocol::OutgoingRelayReqError::Decode(_) @@ -536,7 +536,7 @@ impl ProtocolsHandler for RelayHandler { | protocol::OutgoingRelayReqError::UnexpectedSrcPeerWithStatusType | protocol::OutgoingRelayReqError::UnexpectedDstPeerWithStatusType | protocol::OutgoingRelayReqError::ExpectedStatusType(_) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::B(EitherError::A(error))), )); } @@ -550,7 +550,7 @@ impl ProtocolsHandler for RelayHandler { circuit_relay::Status::HopSrcAddrTooLong | circuit_relay::Status::HopSrcMultiaddrInvalid | circuit_relay::Status::MalformedMessage => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::B( EitherError::A(error), )), @@ -574,7 +574,7 @@ impl ProtocolsHandler for RelayHandler { } } }, - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( EitherError::B(_), )) => { unreachable!("Can not receive an OutgoingDstReqError when dialing a relay.") @@ -593,28 +593,28 @@ impl ProtocolsHandler for RelayHandler { .. } => { let err_code = match error { - ProtocolsHandlerUpgrErr::Timeout | ProtocolsHandlerUpgrErr::Timer => { + ConnectionHandlerUpgrErr::Timeout | ConnectionHandlerUpgrErr::Timer => { circuit_relay::Status::HopCantOpenDstStream } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, )) => circuit_relay::Status::HopCantSpeakRelay, - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), ), )); circuit_relay::Status::HopCantSpeakRelay } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( EitherError::A(_), )) => unreachable!( "Can not receive an OutgoingRelayReqError when dialing a destination." ), - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( EitherError::B(error), )) => { match error { @@ -625,7 +625,7 @@ impl ProtocolsHandler for RelayHandler { | protocol::OutgoingDstReqError::UnexpectedSrcPeerWithStatusType | protocol::OutgoingDstReqError::UnexpectedDstPeerWithStatusType | protocol::OutgoingDstReqError::ExpectedStatusType(_) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::B(EitherError::B( error, ))), @@ -651,7 +651,7 @@ impl ProtocolsHandler for RelayHandler { | circuit_relay::Status::HopSrcAddrTooLong | circuit_relay::Status::HopSrcMultiaddrInvalid => { self.pending_error = - Some(ProtocolsHandlerUpgrErr::Upgrade( + Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::B( EitherError::B(error), )), @@ -663,7 +663,7 @@ impl ProtocolsHandler for RelayHandler { | circuit_relay::Status::StopDstMultiaddrInvalid | circuit_relay::Status::MalformedMessage => { self.pending_error = - Some(ProtocolsHandlerUpgrErr::Upgrade( + Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::B( EitherError::B(error), )), @@ -699,7 +699,7 @@ impl ProtocolsHandler for RelayHandler { &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -709,7 +709,7 @@ impl ProtocolsHandler for RelayHandler { // Check for a pending (fatal) error. if let Some(err) = self.pending_error.take() { // The handler will not be polled again by the `Swarm`. - return Poll::Ready(ProtocolsHandlerEvent::Close(err)); + return Poll::Ready(ConnectionHandlerEvent::Close(err)); } // Request the remote to act as a relay. @@ -721,7 +721,7 @@ impl ProtocolsHandler for RelayHandler { dst_addr, } = self.outgoing_relay_reqs.remove(0); self.outgoing_relay_reqs.shrink_to_fit(); - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new( upgrade::EitherUpgrade::A(protocol::OutgoingRelayReq::new( src_peer_id, @@ -746,7 +746,7 @@ impl ProtocolsHandler for RelayHandler { incoming_relay_req, } = self.outgoing_dst_reqs.remove(0); self.outgoing_dst_reqs.shrink_to_fit(); - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new( upgrade::EitherUpgrade::B(protocol::OutgoingDstReq::new( src_peer_id, @@ -772,7 +772,7 @@ impl ProtocolsHandler for RelayHandler { relay_peer_id: self.remote_peer_id, relay_addr: self.remote_address.clone(), }; - return Poll::Ready(ProtocolsHandlerEvent::Custom(event)); + return Poll::Ready(ConnectionHandlerEvent::Custom(event)); } Poll::Ready(Some(Err(e))) => { log::debug!("Failed to accept destination future: {:?}", e); @@ -796,7 +796,7 @@ impl ProtocolsHandler for RelayHandler { // Report the queued events. if !self.queued_events.is_empty() { let event = self.queued_events.remove(0); - return Poll::Ready(ProtocolsHandlerEvent::Custom(event)); + return Poll::Ready(ConnectionHandlerEvent::Custom(event)); } while let Poll::Ready(Some(Err(Canceled))) = diff --git a/protocols/relay/src/v2/client.rs b/protocols/relay/src/v2/client.rs index fa4447df..139e4a8b 100644 --- a/protocols/relay/src/v2/client.rs +++ b/protocols/relay/src/v2/client.rs @@ -35,10 +35,10 @@ use futures::stream::StreamExt; use libp2p_core::connection::{ConnectedPoint, ConnectionId}; use libp2p_core::{Multiaddr, PeerId}; use libp2p_swarm::dial_opts::DialOpts; -use libp2p_swarm::protocols_handler::DummyProtocolsHandler; +use libp2p_swarm::handler::DummyConnectionHandler; use libp2p_swarm::{ - NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, - ProtocolsHandlerUpgrErr, + ConnectionHandlerUpgrErr, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, + NotifyHandler, PollParameters, }; use std::collections::{hash_map, HashMap, VecDeque}; use std::io::{Error, IoSlice}; @@ -60,7 +60,7 @@ pub enum Event { relay_peer_id: PeerId, /// Indicates whether the request replaces an existing reservation. renewal: bool, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, OutboundCircuitEstablished { relay_peer_id: PeerId, @@ -68,7 +68,7 @@ pub enum Event { }, OutboundCircuitReqFailed { relay_peer_id: PeerId, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// An inbound circuit has been established. InboundCircuitEstablished { @@ -77,7 +77,7 @@ pub enum Event { }, InboundCircuitReqFailed { relay_peer_id: PeerId, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// An inbound circuit request has been denied. InboundCircuitReqDenied { src_peer_id: PeerId }, @@ -116,10 +116,10 @@ impl Client { } impl NetworkBehaviour for Client { - type ProtocolsHandler = handler::Prototype; + type ConnectionHandler = handler::Prototype; type OutEvent = Event; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { handler::Prototype::new(self.local_peer_id, None) } @@ -144,7 +144,7 @@ impl NetworkBehaviour for Client { peer_id: &PeerId, connection_id: &ConnectionId, endpoint: &ConnectedPoint, - _handler: Either, + _handler: Either, _remaining_established: usize, ) { if !endpoint.is_relayed() { @@ -231,7 +231,7 @@ impl NetworkBehaviour for Client { &mut self, cx: &mut Context<'_>, _poll_parameters: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(event) = self.queued_actions.pop_front() { return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); } diff --git a/protocols/relay/src/v2/client/handler.rs b/protocols/relay/src/v2/client/handler.rs index b9f327dd..94a69f6b 100644 --- a/protocols/relay/src/v2/client/handler.rs +++ b/protocols/relay/src/v2/client/handler.rs @@ -31,12 +31,12 @@ use instant::Instant; use libp2p_core::either::EitherError; use libp2p_core::multiaddr::Protocol; use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId}; -use libp2p_swarm::protocols_handler::{ - DummyProtocolsHandler, InboundUpgradeSend, OutboundUpgradeSend, SendWrapper, +use libp2p_swarm::handler::{ + DummyConnectionHandler, InboundUpgradeSend, OutboundUpgradeSend, SendWrapper, }; use libp2p_swarm::{ - IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, + KeepAlive, NegotiatedSubstream, SubstreamProtocol, }; use log::debug; use std::collections::VecDeque; @@ -79,12 +79,12 @@ pub enum Event { ReservationReqFailed { /// Indicates whether the request replaces an existing reservation. renewal: bool, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// An outbound circuit has been established. OutboundCircuitEstablished { limit: Option }, OutboundCircuitReqFailed { - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// An inbound circuit has been established. InboundCircuitEstablished { @@ -93,7 +93,7 @@ pub enum Event { }, /// An inbound circuit request has failed. InboundCircuitReqFailed { - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// An inbound circuit request has been denied. InboundCircuitReqDenied { src_peer_id: PeerId }, @@ -119,8 +119,8 @@ impl Prototype { } } -impl IntoProtocolsHandler for Prototype { - type Handler = Either; +impl IntoConnectionHandler for Prototype { + type Handler = Either; fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { if endpoint.is_relayed() { @@ -133,7 +133,7 @@ impl IntoProtocolsHandler for Prototype { } // Deny all substreams on relayed connection. - Either::Right(DummyProtocolsHandler::default()) + Either::Right(DummyConnectionHandler::default()) } else { let mut handler = Handler { remote_peer_id: *remote_peer_id, @@ -156,7 +156,7 @@ impl IntoProtocolsHandler for Prototype { } } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { upgrade::EitherUpgrade::A(SendWrapper(inbound_stop::Upgrade {})) } } @@ -167,7 +167,7 @@ pub struct Handler { remote_addr: Multiaddr, /// A pending fatal error that results in the connection being closed. pending_error: Option< - ProtocolsHandlerUpgrErr< + ConnectionHandlerUpgrErr< EitherError, >, >, @@ -176,11 +176,11 @@ pub struct Handler { /// Queue of events to return when polled. queued_events: VecDeque< - ProtocolsHandlerEvent< - ::OutboundProtocol, - ::OutboundOpenInfo, - ::OutEvent, - ::Error, + ConnectionHandlerEvent< + ::OutboundProtocol, + ::OutboundOpenInfo, + ::OutEvent, + ::Error, >, >, @@ -201,14 +201,14 @@ pub struct Handler { /// Futures that try to send errors to the transport. /// /// We may drop errors if this handler ends up in a terminal state (by returning - /// [`ProtocolsHandlerEvent::Close`]). + /// [`ConnectionHandlerEvent::Close`]). send_error_futs: FuturesUnordered>, } -impl ProtocolsHandler for Handler { +impl ConnectionHandler for Handler { type InEvent = In; type OutEvent = Event; - type Error = ProtocolsHandlerUpgrErr< + type Error = ConnectionHandlerUpgrErr< EitherError, >; type InboundProtocol = inbound_stop::Upgrade; @@ -242,7 +242,7 @@ impl ProtocolsHandler for Handler { relay_addr: self.remote_addr.clone(), }); - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::InboundCircuitEstablished { src_peer_id: self.remote_peer_id, limit, @@ -285,7 +285,7 @@ impl ProtocolsHandler for Handler { ); self.queued_events - .push_back(ProtocolsHandlerEvent::Custom(event)); + .push_back(ConnectionHandlerEvent::Custom(event)); } // Outbound circuit @@ -305,7 +305,7 @@ impl ProtocolsHandler for Handler { ))) { Ok(()) => { self.alive_lend_out_substreams.push(rx); - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::OutboundCircuitEstablished { limit }, )); } @@ -325,7 +325,7 @@ impl ProtocolsHandler for Handler { match event { In::Reserve { to_listener } => { self.queued_events - .push_back(ProtocolsHandlerEvent::OutboundSubstreamRequest { + .push_back(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new( outbound_hop::Upgrade::Reserve, OutboundOpenInfo::Reserve { to_listener }, @@ -337,7 +337,7 @@ impl ProtocolsHandler for Handler { dst_peer_id, } => { self.queued_events - .push_back(ProtocolsHandlerEvent::OutboundSubstreamRequest { + .push_back(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new( outbound_hop::Upgrade::Connect { dst_peer_id }, OutboundOpenInfo::Connect { send_back }, @@ -350,35 +350,35 @@ impl ProtocolsHandler for Handler { fn inject_listen_upgrade_error( &mut self, _: Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { let non_fatal_error = match error { - ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, - ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout, + ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer, + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, - )) => ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + )) => ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, )), - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)), )); return; } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( inbound_stop::UpgradeError::Fatal(error), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::A(error)), )); return; } }; - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::InboundCircuitReqFailed { error: non_fatal_error, }, @@ -388,38 +388,38 @@ impl ProtocolsHandler for Handler { fn inject_dial_upgrade_error( &mut self, open_info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { match open_info { OutboundOpenInfo::Reserve { mut to_listener } => { let non_fatal_error = match error { - ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, - ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout, + ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer, + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, - )) => ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + )) => ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, )), - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), ), )); return; } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { match error { outbound_hop::UpgradeError::Fatal(error) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::B(error)), )); return; } outbound_hop::UpgradeError::ReservationFailed(error) => { - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( error, )) } @@ -447,7 +447,7 @@ impl ProtocolsHandler for Handler { } let renewal = self.reservation.failed(); - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::ReservationReqFailed { renewal, error: non_fatal_error, @@ -456,33 +456,33 @@ impl ProtocolsHandler for Handler { } OutboundOpenInfo::Connect { send_back } => { let non_fatal_error = match error { - ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, - ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout, + ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer, + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, - )) => ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + )) => ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, )), - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), ), )); return; } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { match error { outbound_hop::UpgradeError::Fatal(error) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::B(error)), )); return; } outbound_hop::UpgradeError::CircuitFailed(error) => { - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( error, )) } @@ -497,7 +497,7 @@ impl ProtocolsHandler for Handler { let _ = send_back.send(Err(())); - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::OutboundCircuitReqFailed { error: non_fatal_error, }, @@ -514,7 +514,7 @@ impl ProtocolsHandler for Handler { &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -524,7 +524,7 @@ impl ProtocolsHandler for Handler { // Check for a pending (fatal) error. if let Some(err) = self.pending_error.take() { // The handler will not be polled again by the `Swarm`. - return Poll::Ready(ProtocolsHandlerEvent::Close(err)); + return Poll::Ready(ConnectionHandlerEvent::Close(err)); } // Return queued events. @@ -533,7 +533,7 @@ impl ProtocolsHandler for Handler { } if let Poll::Ready(Some(protocol)) = self.reservation.poll(cx) { - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }); + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }); } // Deny incoming circuit requests. @@ -541,12 +541,12 @@ impl ProtocolsHandler for Handler { { match result { Ok(()) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::InboundCircuitReqDenied { src_peer_id }, )) } Err(error) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::InboundCircuitReqDenyFailed { src_peer_id, error }, )) } diff --git a/protocols/relay/src/v2/relay.rs b/protocols/relay/src/v2/relay.rs index e724976d..42841878 100644 --- a/protocols/relay/src/v2/relay.rs +++ b/protocols/relay/src/v2/relay.rs @@ -30,10 +30,10 @@ use instant::Instant; use libp2p_core::connection::{ConnectedPoint, ConnectionId}; use libp2p_core::multiaddr::Protocol; use libp2p_core::PeerId; -use libp2p_swarm::protocols_handler::DummyProtocolsHandler; +use libp2p_swarm::handler::DummyConnectionHandler; use libp2p_swarm::{ - NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, - ProtocolsHandlerUpgrErr, + ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + PollParameters, }; use std::collections::{hash_map, HashMap, HashSet, VecDeque}; use std::num::NonZeroU32; @@ -151,7 +151,7 @@ pub enum Event { ReservationTimedOut { src_peer_id: PeerId }, CircuitReqReceiveFailed { src_peer_id: PeerId, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// An inbound circuit request has been denied. CircuitReqDenied { @@ -173,7 +173,7 @@ pub enum Event { CircuitReqOutboundConnectFailed { src_peer_id: PeerId, dst_peer_id: PeerId, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// Accepting an inbound circuit request failed. CircuitReqAcceptFailed { @@ -216,10 +216,10 @@ impl Relay { } impl NetworkBehaviour for Relay { - type ProtocolsHandler = handler::Prototype; + type ConnectionHandler = handler::Prototype; type OutEvent = Event; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { handler::Prototype { config: handler::Config { reservation_duration: self.config.reservation_duration, @@ -234,7 +234,7 @@ impl NetworkBehaviour for Relay { peer: &PeerId, connection: &ConnectionId, _: &ConnectedPoint, - _handler: Either, + _handler: Either, _remaining_established: usize, ) { if let hash_map::Entry::Occupied(mut peer) = self.reservations.entry(*peer) { @@ -283,7 +283,7 @@ impl NetworkBehaviour for Relay { assert!( !endpoint.is_relayed(), - "`DummyProtocolsHandler` handles relayed connections. It \ + "`DummyConnectionHandler` handles relayed connections. It \ denies all inbound substreams." ); @@ -410,7 +410,7 @@ impl NetworkBehaviour for Relay { assert!( !endpoint.is_relayed(), - "`DummyProtocolsHandler` handles relayed connections. It \ + "`DummyConnectionHandler` handles relayed connections. It \ denies all inbound substreams." ); @@ -622,7 +622,7 @@ impl NetworkBehaviour for Relay { &mut self, _cx: &mut Context<'_>, poll_parameters: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(action) = self.queued_actions.pop_front() { return Poll::Ready(action.build(poll_parameters)); } diff --git a/protocols/relay/src/v2/relay/handler.rs b/protocols/relay/src/v2/relay/handler.rs index e42f3735..1b9c881d 100644 --- a/protocols/relay/src/v2/relay/handler.rs +++ b/protocols/relay/src/v2/relay/handler.rs @@ -33,11 +33,11 @@ use instant::Instant; use libp2p_core::connection::ConnectionId; use libp2p_core::either::EitherError; use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId}; -use libp2p_swarm::protocols_handler::{DummyProtocolsHandler, SendWrapper}; -use libp2p_swarm::protocols_handler::{InboundUpgradeSend, OutboundUpgradeSend}; +use libp2p_swarm::handler::{DummyConnectionHandler, SendWrapper}; +use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_swarm::{ - IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, + KeepAlive, NegotiatedSubstream, SubstreamProtocol, }; use std::collections::VecDeque; use std::fmt; @@ -167,7 +167,7 @@ pub enum Event { }, /// Receiving an inbound circuit request failed. CircuitReqReceiveFailed { - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// An inbound circuit request has been denied. CircuitReqDenied { @@ -209,7 +209,7 @@ pub enum Event { src_connection_id: ConnectionId, inbound_circuit_req: inbound_hop::CircuitReq, status: Status, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, }, /// An inbound circuit has closed. CircuitClosed { @@ -341,13 +341,13 @@ pub struct Prototype { pub config: Config, } -impl IntoProtocolsHandler for Prototype { - type Handler = Either; +impl IntoConnectionHandler for Prototype { + type Handler = Either; fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { if endpoint.is_relayed() { // Deny all substreams on relayed connection. - Either::Right(DummyProtocolsHandler::default()) + Either::Right(DummyConnectionHandler::default()) } else { Either::Left(Handler { endpoint: endpoint.clone(), @@ -366,7 +366,7 @@ impl IntoProtocolsHandler for Prototype { } } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { upgrade::EitherUpgrade::A(SendWrapper(inbound_hop::Upgrade { reservation_duration: self.config.reservation_duration, max_circuit_duration: self.config.max_circuit_duration, @@ -375,7 +375,7 @@ impl IntoProtocolsHandler for Prototype { } } -/// [`ProtocolsHandler`] that manages substreams for a relay on a single +/// [`ConnectionHandler`] that manages substreams for a relay on a single /// connection with a peer. pub struct Handler { endpoint: ConnectedPoint, @@ -385,17 +385,17 @@ pub struct Handler { /// Queue of events to return when polled. queued_events: VecDeque< - ProtocolsHandlerEvent< - ::OutboundProtocol, - ::OutboundOpenInfo, - ::OutEvent, - ::Error, + ConnectionHandlerEvent< + ::OutboundProtocol, + ::OutboundOpenInfo, + ::OutEvent, + ::Error, >, >, /// A pending fatal error that results in the connection being closed. pending_error: Option< - ProtocolsHandlerUpgrErr< + ConnectionHandlerUpgrErr< EitherError, >, >, @@ -429,10 +429,10 @@ pub struct Handler { type Futures = FuturesUnordered>; -impl ProtocolsHandler for Handler { +impl ConnectionHandler for Handler { type InEvent = In; type OutEvent = Event; - type Error = ProtocolsHandlerUpgrErr< + type Error = ConnectionHandlerUpgrErr< EitherError, >; type InboundProtocol = inbound_hop::Upgrade; @@ -458,7 +458,7 @@ impl ProtocolsHandler for Handler { ) { match request { inbound_hop::Req::Reserve(inbound_reservation_req) => { - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::ReservationReqReceived { inbound_reservation_req, endpoint: self.endpoint.clone(), @@ -467,7 +467,7 @@ impl ProtocolsHandler for Handler { )); } inbound_hop::Req::Connect(inbound_circuit_req) => { - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::CircuitReqReceived { inbound_circuit_req, endpoint: self.endpoint.clone(), @@ -493,7 +493,7 @@ impl ProtocolsHandler for Handler { let (tx, rx) = oneshot::channel(); self.alive_lend_out_substreams.push(rx); - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::OutboundConnectNegotiated { circuit_id, src_peer_id, @@ -530,7 +530,7 @@ impl ProtocolsHandler for Handler { src_connection_id, } => { self.queued_events - .push_back(ProtocolsHandlerEvent::OutboundSubstreamRequest { + .push_back(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new( outbound_stop::Upgrade { relay_peer_id, @@ -589,35 +589,35 @@ impl ProtocolsHandler for Handler { fn inject_listen_upgrade_error( &mut self, _: Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { let non_fatal_error = match error { - ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, - ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout, + ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer, + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, - )) => ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + )) => ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, )), - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)), )); return; } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( inbound_hop::UpgradeError::Fatal(error), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::A(error)), )); return; } }; - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::CircuitReqReceiveFailed { error: non_fatal_error, }, @@ -627,36 +627,36 @@ impl ProtocolsHandler for Handler { fn inject_dial_upgrade_error( &mut self, open_info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { let (non_fatal_error, status) = match error { - ProtocolsHandlerUpgrErr::Timeout => { - (ProtocolsHandlerUpgrErr::Timeout, Status::ConnectionFailed) + ConnectionHandlerUpgrErr::Timeout => { + (ConnectionHandlerUpgrErr::Timeout, Status::ConnectionFailed) } - ProtocolsHandlerUpgrErr::Timer => { - (ProtocolsHandlerUpgrErr::Timer, Status::ConnectionFailed) + ConnectionHandlerUpgrErr::Timer => { + (ConnectionHandlerUpgrErr::Timer, Status::ConnectionFailed) } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::Failed, )) => { // The remote has previously done a reservation. Doing a reservation but not // supporting the stop protocol is pointless, thus disconnecting. - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select(upgrade::NegotiationError::Failed), )); return; } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( upgrade::NegotiationError::ProtocolError(e), )) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)), )); return; } - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => match error { + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => match error { outbound_stop::UpgradeError::Fatal(error) => { - self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( + self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade( upgrade::UpgradeError::Apply(EitherError::B(error)), )); return; @@ -671,7 +671,7 @@ impl ProtocolsHandler for Handler { } }; ( - ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)), + ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)), status, ) } @@ -685,7 +685,7 @@ impl ProtocolsHandler for Handler { src_connection_id, } = open_info; - self.queued_events.push_back(ProtocolsHandlerEvent::Custom( + self.queued_events.push_back(ConnectionHandlerEvent::Custom( Event::OutboundConnectNegotiationFailed { circuit_id, src_peer_id, @@ -705,7 +705,7 @@ impl ProtocolsHandler for Handler { &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -715,7 +715,7 @@ impl ProtocolsHandler for Handler { // Check for a pending (fatal) error. if let Some(err) = self.pending_error.take() { // The handler will not be polled again by the `Swarm`. - return Poll::Ready(ProtocolsHandlerEvent::Close(err)); + return Poll::Ready(ConnectionHandlerEvent::Close(err)); } // Return queued events. @@ -728,14 +728,14 @@ impl ProtocolsHandler for Handler { { match result { Ok(()) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::CircuitClosed { + return Poll::Ready(ConnectionHandlerEvent::Custom(Event::CircuitClosed { circuit_id, dst_peer_id, error: None, })) } Err(e) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::CircuitClosed { + return Poll::Ready(ConnectionHandlerEvent::Custom(Event::CircuitClosed { circuit_id, dst_peer_id, error: Some(e), @@ -751,12 +751,12 @@ impl ProtocolsHandler for Handler { .active_reservation .replace(Delay::new(self.config.reservation_duration)) .is_some(); - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::ReservationReqAccepted { renewed }, )); } Err(error) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::ReservationReqAcceptFailed { error }, )); } @@ -766,12 +766,12 @@ impl ProtocolsHandler for Handler { if let Poll::Ready(Some(result)) = self.reservation_deny_futures.poll_next_unpin(cx) { match result { Ok(()) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::ReservationReqDenied {}, )) } Err(error) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::ReservationReqDenyFailed { error }, )); } @@ -819,13 +819,15 @@ impl ProtocolsHandler for Handler { self.circuits.push(circuit); - return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::CircuitReqAccepted { - circuit_id, - dst_peer_id, - })); + return Poll::Ready(ConnectionHandlerEvent::Custom( + Event::CircuitReqAccepted { + circuit_id, + dst_peer_id, + }, + )); } Err((circuit_id, dst_peer_id, error)) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::CircuitReqAcceptFailed { circuit_id, dst_peer_id, @@ -841,13 +843,13 @@ impl ProtocolsHandler for Handler { { match result { Ok(()) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::CircuitReqDenied { + return Poll::Ready(ConnectionHandlerEvent::Custom(Event::CircuitReqDenied { circuit_id, dst_peer_id, })); } Err(error) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( Event::CircuitReqDenyFailed { circuit_id, dst_peer_id, @@ -868,7 +870,9 @@ impl ProtocolsHandler for Handler { .map(|fut| fut.poll_unpin(cx)) { self.active_reservation = None; - return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::ReservationTimedOut {})); + return Poll::Ready(ConnectionHandlerEvent::Custom( + Event::ReservationTimedOut {}, + )); } if self.reservation_accept_futures.is_empty() diff --git a/protocols/relay/tests/v1.rs b/protocols/relay/tests/v1.rs index 69d08ae7..6d6f97ac 100644 --- a/protocols/relay/tests/v1.rs +++ b/protocols/relay/tests/v1.rs @@ -34,7 +34,7 @@ use libp2p_kad::{GetClosestPeersOk, Kademlia, KademliaEvent, QueryResult}; use libp2p_ping as ping; use libp2p_plaintext::PlainText2Config; use libp2p_relay::v1::{new_transport_and_behaviour, Relay, RelayConfig}; -use libp2p_swarm::protocols_handler::KeepAlive; +use libp2p_swarm::handler::KeepAlive; use libp2p_swarm::{ DialError, DummyBehaviour, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters, Swarm, SwarmEvent, @@ -1162,7 +1162,7 @@ impl CombinedBehaviour { &mut self, _: &mut Context, _: &mut impl PollParameters, - ) -> Poll::ProtocolsHandler>> + ) -> Poll::ConnectionHandler>> { if !self.events.is_empty() { return Poll::Ready(NetworkBehaviourAction::GenerateEvent(self.events.remove(0))); diff --git a/protocols/rendezvous/src/client.rs b/protocols/rendezvous/src/client.rs index 0195de37..77ea2ae9 100644 --- a/protocols/rendezvous/src/client.rs +++ b/protocols/rendezvous/src/client.rs @@ -22,7 +22,7 @@ use crate::codec::{Cookie, ErrorCode, Namespace, NewRegistration, Registration, use crate::handler; use crate::handler::outbound; use crate::handler::outbound::OpenInfo; -use crate::substream_handler::SubstreamProtocolsHandler; +use crate::substream_handler::SubstreamConnectionHandler; use futures::future::BoxFuture; use futures::future::FutureExt; use futures::stream::FuturesUnordered; @@ -43,7 +43,7 @@ pub struct Behaviour { events: VecDeque< NetworkBehaviourAction< Event, - SubstreamProtocolsHandler, + SubstreamConnectionHandler, >, >, keypair: Keypair, @@ -164,14 +164,14 @@ pub enum Event { } impl NetworkBehaviour for Behaviour { - type ProtocolsHandler = - SubstreamProtocolsHandler; + type ConnectionHandler = + SubstreamConnectionHandler; type OutEvent = Event; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { let initial_keep_alive = Duration::from_secs(30); - SubstreamProtocolsHandler::new_outbound_only(initial_keep_alive) + SubstreamConnectionHandler::new_outbound_only(initial_keep_alive) } fn addresses_of_peer(&mut self, peer: &PeerId) -> Vec { @@ -215,7 +215,7 @@ impl NetworkBehaviour for Behaviour { &mut self, cx: &mut Context<'_>, poll_params: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(event) = self.events.pop_front() { return Poll::Ready(event); } @@ -275,7 +275,7 @@ fn handle_outbound_event( ) -> Vec< NetworkBehaviourAction< Event, - SubstreamProtocolsHandler, + SubstreamConnectionHandler, >, > { match event { diff --git a/protocols/rendezvous/src/server.rs b/protocols/rendezvous/src/server.rs index 1ec933ce..dd4731d8 100644 --- a/protocols/rendezvous/src/server.rs +++ b/protocols/rendezvous/src/server.rs @@ -20,7 +20,7 @@ use crate::codec::{Cookie, ErrorCode, Namespace, NewRegistration, Registration, Ttl}; use crate::handler::inbound; -use crate::substream_handler::{InboundSubstreamId, SubstreamProtocolsHandler}; +use crate::substream_handler::{InboundSubstreamId, SubstreamConnectionHandler}; use crate::{handler, MAX_TTL, MIN_TTL}; use bimap::BiMap; use futures::future::BoxFuture; @@ -40,7 +40,7 @@ use void::Void; pub struct Behaviour { events: VecDeque< - NetworkBehaviourAction>, + NetworkBehaviourAction>, >, registrations: Registrations, } @@ -109,13 +109,13 @@ pub enum Event { } impl NetworkBehaviour for Behaviour { - type ProtocolsHandler = SubstreamProtocolsHandler; + type ConnectionHandler = SubstreamConnectionHandler; type OutEvent = Event; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { let initial_keep_alive = Duration::from_secs(30); - SubstreamProtocolsHandler::new_inbound_only(initial_keep_alive) + SubstreamConnectionHandler::new_inbound_only(initial_keep_alive) } fn inject_event( @@ -147,7 +147,7 @@ impl NetworkBehaviour for Behaviour { &mut self, cx: &mut Context<'_>, _: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Poll::Ready(ExpiredRegistration(registration)) = self.registrations.poll(cx) { return Poll::Ready(NetworkBehaviourAction::GenerateEvent( Event::RegistrationExpired(registration), @@ -168,7 +168,7 @@ fn handle_inbound_event( connection: ConnectionId, id: InboundSubstreamId, registrations: &mut Registrations, -) -> Vec>> { +) -> Vec>> { match event { // bad registration inbound::OutEvent::RegistrationRequested(registration) diff --git a/protocols/rendezvous/src/substream_handler.rs b/protocols/rendezvous/src/substream_handler.rs index 55b2a363..2a4be470 100644 --- a/protocols/rendezvous/src/substream_handler.rs +++ b/protocols/rendezvous/src/substream_handler.rs @@ -18,7 +18,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -//! A generic [`ProtocolsHandler`] that delegates the handling of substreams to [`SubstreamHandler`]s. +//! A generic [`ConnectionHandler`] that delegates the handling of substreams to [`SubstreamHandler`]s. //! //! This module is an attempt to simplify the implementation of protocols by freeing implementations from dealing with aspects such as concurrent substreams. //! Particularly for outbound substreams, it greatly simplifies the definition of protocols through the [`FutureSubstream`] helper. @@ -29,10 +29,10 @@ use futures::future::{self, BoxFuture, Fuse, FusedFuture}; use futures::FutureExt; use instant::Instant; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; -use libp2p_swarm::protocols_handler::{InboundUpgradeSend, OutboundUpgradeSend}; +use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_swarm::{ - KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + NegotiatedSubstream, SubstreamProtocol, }; use std::collections::{HashMap, VecDeque}; use std::fmt; @@ -172,8 +172,8 @@ impl OutboundUpgrade for PassthroughProtocol { } } -/// An implementation of [`ProtocolsHandler`] that delegates to individual [`SubstreamHandler`]s. -pub struct SubstreamProtocolsHandler { +/// An implementation of [`ConnectionHandler`] that delegates to individual [`SubstreamHandler`]s. +pub struct SubstreamConnectionHandler { inbound_substreams: HashMap, outbound_substreams: HashMap, next_inbound_substream_id: InboundSubstreamId, @@ -185,7 +185,7 @@ pub struct SubstreamProtocolsHandler - SubstreamProtocolsHandler + SubstreamConnectionHandler { pub fn new(initial_keep_alive: Duration) -> Self { Self { @@ -200,7 +200,7 @@ impl } impl - SubstreamProtocolsHandler + SubstreamConnectionHandler { pub fn new_outbound_only(initial_keep_alive: Duration) -> Self { Self { @@ -215,7 +215,7 @@ impl } impl - SubstreamProtocolsHandler + SubstreamConnectionHandler { pub fn new_inbound_only(initial_keep_alive: Duration) -> Self { Self { @@ -231,7 +231,7 @@ impl /// Poll all substreams within the given HashMap. /// -/// This is defined as a separate function because we call it with two different fields stored within [`SubstreamProtocolsHandler`]. +/// This is defined as a separate function because we call it with two different fields stored within [`SubstreamConnectionHandler`]. fn poll_substreams( substreams: &mut HashMap, cx: &mut Context<'_>, @@ -273,7 +273,7 @@ where Poll::Pending } -/// Event sent from the [`libp2p_swarm::NetworkBehaviour`] to the [`SubstreamProtocolsHandler`]. +/// Event sent from the [`libp2p_swarm::NetworkBehaviour`] to the [`SubstreamConnectionHandler`]. #[derive(Debug)] pub enum InEvent { /// Open a new substream using the provided `open_info`. @@ -290,7 +290,7 @@ pub enum InEvent { }, } -/// Event produced by the [`SubstreamProtocolsHandler`] for the corresponding [`libp2p_swarm::NetworkBehaviour`]. +/// Event produced by the [`SubstreamConnectionHandler`] for the corresponding [`libp2p_swarm::NetworkBehaviour`]. #[derive(Debug)] pub enum OutEvent { /// An inbound substream produced an event. @@ -325,8 +325,8 @@ impl< TOutboundError, TInboundSubstreamHandler, TOutboundSubstreamHandler, - > ProtocolsHandler - for SubstreamProtocolsHandler< + > ConnectionHandler + for SubstreamConnectionHandler< TInboundSubstreamHandler, TOutboundSubstreamHandler, TOutboundOpenInfo, @@ -421,7 +421,7 @@ where fn inject_dial_upgrade_error( &mut self, _: Self::OutboundOpenInfo, - _: ProtocolsHandlerUpgrErr, + _: ConnectionHandlerUpgrErr, ) { // TODO: Handle upgrade errors properly } @@ -447,7 +447,7 @@ where &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -455,20 +455,20 @@ where >, > { if let Some(open_info) = self.new_substreams.pop_front() { - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: TOutboundSubstreamHandler::upgrade(open_info), }); } match poll_substreams(&mut self.inbound_substreams, cx) { Poll::Ready(Ok((id, message))) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(OutEvent::InboundEvent { + return Poll::Ready(ConnectionHandlerEvent::Custom(OutEvent::InboundEvent { id, message, })) } Poll::Ready(Err((id, error))) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(OutEvent::InboundError { + return Poll::Ready(ConnectionHandlerEvent::Custom(OutEvent::InboundError { id, error, })) @@ -478,13 +478,13 @@ where match poll_substreams(&mut self.outbound_substreams, cx) { Poll::Ready(Ok((id, message))) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(OutEvent::OutboundEvent { + return Poll::Ready(ConnectionHandlerEvent::Custom(OutEvent::OutboundEvent { id, message, })) } Poll::Ready(Err((id, error))) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(OutEvent::OutboundError { + return Poll::Ready(ConnectionHandlerEvent::Custom(OutEvent::OutboundError { id, error, })) diff --git a/protocols/request-response/src/handler.rs b/protocols/request-response/src/handler.rs index e0b482cc..fd843b7d 100644 --- a/protocols/request-response/src/handler.rs +++ b/protocols/request-response/src/handler.rs @@ -29,9 +29,7 @@ use futures::{channel::oneshot, future::BoxFuture, prelude::*, stream::FuturesUn use instant::Instant; use libp2p_core::upgrade::{NegotiationError, UpgradeError}; use libp2p_swarm::{ - protocols_handler::{ - KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, - }, + handler::{ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive}, SubstreamProtocol, }; use smallvec::SmallVec; @@ -65,7 +63,7 @@ where /// The current connection keep-alive. keep_alive: KeepAlive, /// A pending fatal error that results in the connection being closed. - pending_error: Option>, + pending_error: Option>, /// Queue of events to emit in `poll()`. pending_events: VecDeque>, /// Outbound upgrades waiting to be emitted as an `OutboundSubstreamRequest`. @@ -192,13 +190,13 @@ impl fmt::Debug for RequestResponseHandlerEvent ProtocolsHandler for RequestResponseHandler +impl ConnectionHandler for RequestResponseHandler where TCodec: RequestResponseCodec + Send + Clone + 'static, { type InEvent = RequestProtocol; type OutEvent = RequestResponseHandlerEvent; - type Error = ProtocolsHandlerUpgrErr; + type Error = ConnectionHandlerUpgrErr; type InboundProtocol = ResponseProtocol; type OutboundProtocol = RequestProtocol; type OutboundOpenInfo = RequestId; @@ -268,14 +266,14 @@ where fn inject_dial_upgrade_error( &mut self, info: RequestId, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, ) { match error { - ProtocolsHandlerUpgrErr::Timeout => { + ConnectionHandlerUpgrErr::Timeout => { self.pending_events .push_back(RequestResponseHandlerEvent::OutboundTimeout(info)); } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { // The remote merely doesn't support the protocol(s) we requested. // This is no reason to close the connection, which may // successfully communicate with other protocols already. @@ -296,13 +294,13 @@ where fn inject_listen_upgrade_error( &mut self, info: RequestId, - error: ProtocolsHandlerUpgrErr, + error: ConnectionHandlerUpgrErr, ) { match error { - ProtocolsHandlerUpgrErr::Timeout => self + ConnectionHandlerUpgrErr::Timeout => self .pending_events .push_back(RequestResponseHandlerEvent::InboundTimeout(info)), - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { // The local peer merely doesn't support the protocol(s) requested. // This is no reason to close the connection, which may // successfully communicate with other protocols already. @@ -327,17 +325,17 @@ where fn poll( &mut self, cx: &mut Context<'_>, - ) -> Poll, RequestId, Self::OutEvent, Self::Error>> + ) -> Poll, RequestId, Self::OutEvent, Self::Error>> { // Check for a pending (fatal) error. if let Some(err) = self.pending_error.take() { // The handler will not be polled again by the `Swarm`. - return Poll::Ready(ProtocolsHandlerEvent::Close(err)); + return Poll::Ready(ConnectionHandlerEvent::Close(err)); } // Drain pending events. if let Some(event) = self.pending_events.pop_front() { - return Poll::Ready(ProtocolsHandlerEvent::Custom(event)); + return Poll::Ready(ConnectionHandlerEvent::Custom(event)); } else if self.pending_events.capacity() > EMPTY_QUEUE_SHRINK_THRESHOLD { self.pending_events.shrink_to_fit(); } @@ -348,7 +346,7 @@ where Ok(((id, rq), rs_sender)) => { // We received an inbound request. self.keep_alive = KeepAlive::Yes; - return Poll::Ready(ProtocolsHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::Custom( RequestResponseHandlerEvent::Request { request_id: id, request: rq, @@ -367,7 +365,7 @@ where // Emit outbound requests. if let Some(request) = self.outbound.pop_front() { let info = request.request_id; - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new(request, info) .with_timeout(self.substream_timeout), }); diff --git a/protocols/request-response/src/lib.rs b/protocols/request-response/src/lib.rs index 27041b15..a0c53101 100644 --- a/protocols/request-response/src/lib.rs +++ b/protocols/request-response/src/lib.rs @@ -67,7 +67,7 @@ use handler::{RequestProtocol, RequestResponseHandler, RequestResponseHandlerEve use libp2p_core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId}; use libp2p_swarm::{ dial_opts::{self, DialOpts}, - DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, + DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, }; use smallvec::SmallVec; @@ -567,10 +567,10 @@ impl NetworkBehaviour for RequestResponse where TCodec: RequestResponseCodec + Send + Clone + 'static, { - type ProtocolsHandler = RequestResponseHandler; + type ConnectionHandler = RequestResponseHandler; type OutEvent = RequestResponseEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { RequestResponseHandler::new( self.inbound_protocols.clone(), self.codec.clone(), @@ -646,7 +646,7 @@ where peer_id: &PeerId, conn: &ConnectionId, _: &ConnectedPoint, - _: ::Handler, + _: ::Handler, remaining_established: usize, ) { let connections = self @@ -691,7 +691,7 @@ where fn inject_dial_failure( &mut self, peer: Option, - _: Self::ProtocolsHandler, + _: Self::ConnectionHandler, _: &DialError, ) { if let Some(peer) = peer { @@ -872,7 +872,7 @@ where &mut self, _: &mut Context<'_>, _: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(ev) = self.pending_events.pop_front() { return Poll::Ready(ev); } else if self.pending_events.capacity() > EMPTY_QUEUE_SHRINK_THRESHOLD { diff --git a/swarm-derive/src/lib.rs b/swarm-derive/src/lib.rs index 8cb35c9c..67499e7a 100644 --- a/swarm-derive/src/lib.rs +++ b/swarm-derive/src/lib.rs @@ -50,9 +50,9 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { let net_behv_event_proc = quote! {::libp2p::swarm::NetworkBehaviourEventProcess}; let either_ident = quote! {::libp2p::core::either::EitherOutput}; let network_behaviour_action = quote! {::libp2p::swarm::NetworkBehaviourAction}; - let into_protocols_handler = quote! {::libp2p::swarm::IntoProtocolsHandler}; - let protocols_handler = quote! {::libp2p::swarm::ProtocolsHandler}; - let into_proto_select_ident = quote! {::libp2p::swarm::IntoProtocolsHandlerSelect}; + let into_protocols_handler = quote! {::libp2p::swarm::IntoConnectionHandler}; + let protocols_handler = quote! {::libp2p::swarm::ConnectionHandler}; + let into_proto_select_ident = quote! {::libp2p::swarm::IntoConnectionHandlerSelect}; let peer_id = quote! {::libp2p::core::PeerId}; let connection_id = quote! {::libp2p::core::connection::ConnectionId}; let dial_errors = quote! {Option<&Vec<::libp2p::core::Multiaddr>>}; @@ -431,7 +431,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { }) }); - // The `ProtocolsHandler` associated type. + // The [`ConnectionHandler`] associated type. let protocols_handler_ty = { let mut ph_ty = None; for field in data_struct.fields.iter() { @@ -439,7 +439,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { continue; } let ty = &field.ty; - let field_info = quote! { <#ty as #trait_to_impl>::ProtocolsHandler }; + let field_info = quote! { <#ty as #trait_to_impl>::ConnectionHandler }; match ph_ty { Some(ev) => ph_ty = Some(quote! { #into_proto_select_ident<#ev, #field_info> }), ref mut ev @ None => *ev = Some(field_info), @@ -601,10 +601,10 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { impl #impl_generics #trait_to_impl for #name #ty_generics #where_clause { - type ProtocolsHandler = #protocols_handler_ty; + type ConnectionHandler = #protocols_handler_ty; type OutEvent = #out_event; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { use #into_protocols_handler; #new_handler } @@ -623,15 +623,15 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { #(#inject_address_change_stmts);* } - fn inject_connection_closed(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, endpoint: &#connected_point, handlers: ::Handler, remaining_established: usize) { + fn inject_connection_closed(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, endpoint: &#connected_point, handlers: ::Handler, remaining_established: usize) { #(#inject_connection_closed_stmts);* } - fn inject_dial_failure(&mut self, peer_id: Option<#peer_id>, handlers: Self::ProtocolsHandler, error: &#dial_error) { + fn inject_dial_failure(&mut self, peer_id: Option<#peer_id>, handlers: Self::ConnectionHandler, error: &#dial_error) { #(#inject_dial_failure_stmts);* } - fn inject_listen_failure(&mut self, local_addr: &#multiaddr, send_back_addr: &#multiaddr, handlers: Self::ProtocolsHandler) { + fn inject_listen_failure(&mut self, local_addr: &#multiaddr, send_back_addr: &#multiaddr, handlers: Self::ConnectionHandler) { #(#inject_listen_failure_stmts);* } @@ -667,17 +667,17 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream { &mut self, peer_id: #peer_id, connection_id: #connection_id, - event: <::Handler as #protocols_handler>::OutEvent + event: <::Handler as #protocols_handler>::OutEvent ) { match event { #(#inject_node_event_stmts),* } } - fn poll(&mut self, cx: &mut std::task::Context, poll_params: &mut impl #poll_parameters) -> std::task::Poll<#network_behaviour_action> { + fn poll(&mut self, cx: &mut std::task::Context, poll_params: &mut impl #poll_parameters) -> std::task::Poll<#network_behaviour_action> { use libp2p::futures::prelude::*; #(#poll_stmts)* - let f: std::task::Poll<#network_behaviour_action> = #poll_method; + let f: std::task::Poll<#network_behaviour_action> = #poll_method; f } } diff --git a/swarm-derive/tests/test.rs b/swarm-derive/tests/test.rs index c5182b04..db50c463 100644 --- a/swarm-derive/tests/test.rs +++ b/swarm-derive/tests/test.rs @@ -160,7 +160,7 @@ fn custom_polling() { ) -> std::task::Poll< libp2p::swarm::NetworkBehaviourAction< ::OutEvent, - ::ProtocolsHandler, + ::ConnectionHandler, >, > { std::task::Poll::Pending @@ -223,7 +223,7 @@ fn custom_event_and_polling() { ) -> std::task::Poll< libp2p::swarm::NetworkBehaviourAction< ::OutEvent, - ::ProtocolsHandler, + ::ConnectionHandler, >, > { std::task::Poll::Pending diff --git a/swarm/CHANGELOG.md b/swarm/CHANGELOG.md index e4c6f763..50fe402c 100644 --- a/swarm/CHANGELOG.md +++ b/swarm/CHANGELOG.md @@ -1,5 +1,9 @@ # 0.34.0 [unreleased] +- Rename `ProtocolsHandler` to `ConnectionHandler`. Upgrade should be as simple as renaming all + occurences of `ProtocolsHandler` to `ConnectionHandler` with your favorite text manipulation tool + across your codebase. See [PR 2527]. + - Fold `libp2p-core`'s `Network` into `Swarm`. See [PR 2492]. - Update to `libp2p-core` `v0.32.0`. @@ -10,6 +14,7 @@ [PR 2492]: https://github.com/libp2p/rust-libp2p/pull/2492 [PR 2517]: https://github.com/libp2p/rust-libp2p/pull/2517 +[PR 2527]: https://github.com/libp2p/rust-libp2p/pull/2527 # 0.33.0 [2022-01-27] diff --git a/swarm/src/behaviour.rs b/swarm/src/behaviour.rs index 0be2c4ca..20b607c3 100644 --- a/swarm/src/behaviour.rs +++ b/swarm/src/behaviour.rs @@ -22,7 +22,7 @@ pub mod either; pub mod toggle; use crate::dial_opts::DialOpts; -use crate::protocols_handler::{IntoProtocolsHandler, ProtocolsHandler}; +use crate::handler::{ConnectionHandler, IntoConnectionHandler}; use crate::{AddressRecord, AddressScore, DialError}; use libp2p_core::{ connection::{ConnectionId, ListenerId}, @@ -30,12 +30,12 @@ use libp2p_core::{ }; use std::{task::Context, task::Poll}; -/// Custom event that can be received by the [`ProtocolsHandler`]. +/// Custom event that can be received by the [`ConnectionHandler`]. pub(crate) type THandlerInEvent = - <::Handler as ProtocolsHandler>::InEvent; + <::Handler as ConnectionHandler>::InEvent; pub(crate) type THandlerOutEvent = - <::Handler as ProtocolsHandler>::OutEvent; + <::Handler as ConnectionHandler>::OutEvent; /// A [`NetworkBehaviour`] defines the behaviour of the local node on the network. /// @@ -167,12 +167,12 @@ pub(crate) type THandlerOutEvent = /// function and will be called last within the generated [`NetworkBehaviour`] implementation. pub trait NetworkBehaviour: Send + 'static { /// Handler for all the protocols the network behaviour supports. - type ProtocolsHandler: IntoProtocolsHandler; + type ConnectionHandler: IntoConnectionHandler; /// Event generated by the `NetworkBehaviour` and that the swarm will report back. type OutEvent: Send + 'static; - /// Creates a new `ProtocolsHandler` for a connection with a peer. + /// Creates a new [`ConnectionHandler`] for a connection with a peer. /// /// Every time an incoming connection is opened, and every time another [`NetworkBehaviour`] /// emitted a dial request, this method is called. @@ -188,7 +188,7 @@ pub trait NetworkBehaviour: Send + 'static { /// /// Note that the handler is returned to the [`NetworkBehaviour`] on connection failure and /// connection closing. - fn new_handler(&mut self) -> Self::ProtocolsHandler; + fn new_handler(&mut self) -> Self::ConnectionHandler; /// Addresses that this behaviour is aware of for this specific peer, and that may allow /// reaching the peer. @@ -221,7 +221,7 @@ pub trait NetworkBehaviour: Send + 'static { _: &PeerId, _: &ConnectionId, _: &ConnectedPoint, - _: ::Handler, + _: ::Handler, _remaining_established: usize, ) { } @@ -245,14 +245,14 @@ pub trait NetworkBehaviour: Send + 'static { &mut self, peer_id: PeerId, connection: ConnectionId, - event: <::Handler as ProtocolsHandler>::OutEvent, + event: <::Handler as ConnectionHandler>::OutEvent, ); /// Indicates to the behaviour that the dial to a known or unknown node failed. fn inject_dial_failure( &mut self, _peer_id: Option, - _handler: Self::ProtocolsHandler, + _handler: Self::ConnectionHandler, _error: &DialError, ) { } @@ -266,7 +266,7 @@ pub trait NetworkBehaviour: Send + 'static { &mut self, _local_addr: &Multiaddr, _send_back_addr: &Multiaddr, - _handler: Self::ProtocolsHandler, + _handler: Self::ConnectionHandler, ) { } @@ -301,7 +301,7 @@ pub trait NetworkBehaviour: Send + 'static { &mut self, cx: &mut Context<'_>, params: &mut impl PollParameters, - ) -> Poll>; + ) -> Poll>; } /// Parameters passed to `poll()`, that the `NetworkBehaviour` has access to. @@ -353,7 +353,7 @@ pub trait NetworkBehaviourEventProcess { #[derive(Debug)] pub enum NetworkBehaviourAction< TOutEvent, - THandler: IntoProtocolsHandler, + THandler: IntoConnectionHandler, TInEvent = THandlerInEvent, > { /// Instructs the `Swarm` to return an event when it is being polled. @@ -382,9 +382,9 @@ pub enum NetworkBehaviourAction< /// # use libp2p::core::PeerId; /// # use libp2p::plaintext::PlainText2Config; /// # use libp2p::swarm::{ - /// # DialError, IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, - /// # NetworkBehaviour, NetworkBehaviourAction, PollParameters, ProtocolsHandler, - /// # ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, Swarm, SwarmEvent, + /// # DialError, IntoConnectionHandler, KeepAlive, NegotiatedSubstream, + /// # NetworkBehaviour, NetworkBehaviourAction, PollParameters, ConnectionHandler, + /// # ConnectionHandlerEvent, ConnectionHandlerUpgrErr, SubstreamProtocol, Swarm, SwarmEvent, /// # }; /// # use libp2p::swarm::dial_opts::{DialOpts, PeerCondition}; /// # use libp2p::yamux; @@ -439,10 +439,10 @@ pub enum NetworkBehaviourAction< /// } /// # /// impl NetworkBehaviour for MyBehaviour { - /// # type ProtocolsHandler = MyHandler; + /// # type ConnectionHandler = MyHandler; /// # type OutEvent = PreciousMessage; /// # - /// # fn new_handler(&mut self) -> Self::ProtocolsHandler { + /// # fn new_handler(&mut self) -> Self::ConnectionHandler { /// # MyHandler { message: None } /// # } /// # @@ -451,7 +451,7 @@ pub enum NetworkBehaviourAction< /// # &mut self, /// # _: PeerId, /// # _: ConnectionId, - /// # _: <::Handler as ProtocolsHandler>::OutEvent, + /// # _: <::Handler as ConnectionHandler>::OutEvent, /// # ) { /// # unreachable!(); /// # } @@ -459,7 +459,7 @@ pub enum NetworkBehaviourAction< /// fn inject_dial_failure( /// &mut self, /// _: Option, - /// handler: Self::ProtocolsHandler, + /// handler: Self::ConnectionHandler, /// _: &DialError, /// ) { /// // As expected, sending the message failed. But lucky us, we got the handler back, thus @@ -473,7 +473,7 @@ pub enum NetworkBehaviourAction< /// # &mut self, /// # _: &mut Context<'_>, /// # _: &mut impl PollParameters, - /// # ) -> Poll> { + /// # ) -> Poll> { /// # if let Some(action) = self.outbox_to_swarm.pop_front() { /// # return Poll::Ready(action); /// # } @@ -485,7 +485,7 @@ pub enum NetworkBehaviourAction< /// # message: Option, /// # } /// # - /// # impl ProtocolsHandler for MyHandler { + /// # impl ConnectionHandler for MyHandler { /// # type InEvent = Void; /// # type OutEvent = Void; /// # type Error = Void; @@ -519,7 +519,7 @@ pub enum NetworkBehaviourAction< /// # fn inject_dial_upgrade_error( /// # &mut self, /// # _: Self::OutboundOpenInfo, - /// # _: ProtocolsHandlerUpgrErr, + /// # _: ConnectionHandlerUpgrErr, /// # ) { /// # } /// # @@ -531,7 +531,7 @@ pub enum NetworkBehaviourAction< /// # &mut self, /// # _: &mut Context<'_>, /// # ) -> Poll< - /// # ProtocolsHandlerEvent< + /// # ConnectionHandlerEvent< /// # Self::OutboundProtocol, /// # Self::OutboundOpenInfo, /// # Self::OutEvent, @@ -550,19 +550,19 @@ pub enum NetworkBehaviourAction< /// connection with a peer. /// /// If the `Swarm` is connected to the peer, the message is delivered to the - /// `ProtocolsHandler` instance identified by the peer ID and connection ID. + /// [`ConnectionHandler`] instance identified by the peer ID and connection ID. /// /// 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 /// respond to a request on the same connection (and possibly the same - /// substream, as per the implementation of `ProtocolsHandler`). + /// substream, as per the implementation of [`ConnectionHandler`]). /// /// Note that even if the peer is currently connected, connections can get closed /// at any time and thus the event may not reach a handler. NotifyHandler { - /// The peer for whom a `ProtocolsHandler` should be notified. + /// The peer for whom a [`ConnectionHandler`] should be notified. peer_id: PeerId, /// The options w.r.t. which connection handler to notify of the event. handler: NotifyHandler, @@ -591,11 +591,11 @@ pub enum NetworkBehaviourAction< /// /// Note: Closing a connection via /// [`NetworkBehaviourAction::CloseConnection`] does not inform the - /// corresponding [`ProtocolsHandler`]. - /// Closing a connection via a [`ProtocolsHandler`] can be done - /// either in a collaborative manner across [`ProtocolsHandler`]s - /// with [`ProtocolsHandler::connection_keep_alive`] or directly with - /// [`ProtocolsHandlerEvent::Close`](crate::ProtocolsHandlerEvent::Close). + /// corresponding [`ConnectionHandler`]. + /// Closing a connection via a [`ConnectionHandler`] can be done + /// either in a collaborative manner across [`ConnectionHandler`]s + /// with [`ConnectionHandler::connection_keep_alive`] or directly with + /// [`ConnectionHandlerEvent::Close`](crate::ConnectionHandlerEvent::Close). CloseConnection { /// The peer to disconnect. peer_id: PeerId, @@ -604,7 +604,7 @@ pub enum NetworkBehaviourAction< }, } -impl +impl NetworkBehaviourAction { /// Map the handler event. @@ -640,7 +640,7 @@ impl } } -impl NetworkBehaviourAction { +impl NetworkBehaviourAction { /// Map the event the swarm will return. pub fn map_out(self, f: impl FnOnce(TOutEvent) -> E) -> NetworkBehaviourAction { match self { @@ -673,8 +673,8 @@ impl NetworkBehaviourAction NetworkBehaviourAction where - THandlerOld: IntoProtocolsHandler, - ::Handler: ProtocolsHandler, + THandlerOld: IntoConnectionHandler, + ::Handler: ConnectionHandler, { /// Map the handler. pub fn map_handler( @@ -682,8 +682,8 @@ where f: impl FnOnce(THandlerOld) -> THandlerNew, ) -> NetworkBehaviourAction where - THandlerNew: IntoProtocolsHandler, - ::Handler: ProtocolsHandler, + THandlerNew: IntoConnectionHandler, + ::Handler: ConnectionHandler, { match self { NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(e), @@ -716,8 +716,8 @@ where impl NetworkBehaviourAction where - THandlerOld: IntoProtocolsHandler, - ::Handler: ProtocolsHandler, + THandlerOld: IntoConnectionHandler, + ::Handler: ConnectionHandler, { /// Map the handler and handler event. pub fn map_handler_and_in( @@ -726,8 +726,8 @@ where f_in_event: impl FnOnce(TInEventOld) -> TInEventNew, ) -> NetworkBehaviourAction where - THandlerNew: IntoProtocolsHandler, - ::Handler: ProtocolsHandler, + THandlerNew: IntoConnectionHandler, + ::Handler: ConnectionHandler, { match self { NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(e), diff --git a/swarm/src/behaviour/either.rs b/swarm/src/behaviour/either.rs index c48b2bea..6d837105 100644 --- a/swarm/src/behaviour/either.rs +++ b/swarm/src/behaviour/either.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::protocols_handler::{either::IntoEitherHandler, IntoProtocolsHandler, ProtocolsHandler}; +use crate::handler::{either::IntoEitherHandler, ConnectionHandler, IntoConnectionHandler}; use crate::{ DialError, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, PollParameters, @@ -36,10 +36,10 @@ where L: NetworkBehaviour, R: NetworkBehaviour, { - type ProtocolsHandler = IntoEitherHandler; + type ConnectionHandler = IntoEitherHandler; type OutEvent = Either; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { match self { Either::Left(a) => IntoEitherHandler::Left(a.new_handler()), Either::Right(b) => IntoEitherHandler::Right(b.new_handler()), @@ -84,7 +84,7 @@ where peer_id: &PeerId, connection: &ConnectionId, endpoint: &ConnectedPoint, - handler: ::Handler, + handler: ::Handler, remaining_established: usize, ) { match (self, handler) { @@ -124,7 +124,7 @@ where &mut self, peer_id: PeerId, connection: ConnectionId, - event: <::Handler as ProtocolsHandler>::OutEvent, + event: <::Handler as ConnectionHandler>::OutEvent, ) { match (self, event) { (Either::Left(behaviour), Either::Left(event)) => { @@ -140,7 +140,7 @@ where fn inject_dial_failure( &mut self, peer_id: Option, - handler: Self::ProtocolsHandler, + handler: Self::ConnectionHandler, error: &DialError, ) { match (self, handler) { @@ -158,7 +158,7 @@ where &mut self, local_addr: &Multiaddr, send_back_addr: &Multiaddr, - handler: Self::ProtocolsHandler, + handler: Self::ConnectionHandler, ) { match (self, handler) { (Either::Left(behaviour), IntoEitherHandler::Left(handler)) => { @@ -224,7 +224,7 @@ where &mut self, cx: &mut Context<'_>, params: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { let event = match self { Either::Left(behaviour) => futures::ready!(behaviour.poll(cx, params)) .map_out(|e| Either::Left(e)) diff --git a/swarm/src/behaviour/toggle.rs b/swarm/src/behaviour/toggle.rs index 7aeee3cd..70eec966 100644 --- a/swarm/src/behaviour/toggle.rs +++ b/swarm/src/behaviour/toggle.rs @@ -18,9 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::protocols_handler::{ - IntoProtocolsHandler, KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, + KeepAlive, SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; use crate::{ @@ -70,10 +70,10 @@ impl NetworkBehaviour for Toggle where TBehaviour: NetworkBehaviour, { - type ProtocolsHandler = ToggleIntoProtoHandler; + type ConnectionHandler = ToggleIntoProtoHandler; type OutEvent = TBehaviour::OutEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { ToggleIntoProtoHandler { inner: self.inner.as_mut().map(|i| i.new_handler()), } @@ -110,7 +110,7 @@ where peer_id: &PeerId, connection: &ConnectionId, endpoint: &ConnectedPoint, - handler: ::Handler, + handler: ::Handler, remaining_established: usize, ) { if let Some(inner) = self.inner.as_mut() { @@ -142,7 +142,7 @@ where &mut self, peer_id: PeerId, connection: ConnectionId, - event: <::Handler as ProtocolsHandler>::OutEvent, + event: <::Handler as ConnectionHandler>::OutEvent, ) { if let Some(inner) = self.inner.as_mut() { inner.inject_event(peer_id, connection, event); @@ -152,7 +152,7 @@ where fn inject_dial_failure( &mut self, peer_id: Option, - handler: Self::ProtocolsHandler, + handler: Self::ConnectionHandler, error: &DialError, ) { if let Some(inner) = self.inner.as_mut() { @@ -166,7 +166,7 @@ where &mut self, local_addr: &Multiaddr, send_back_addr: &Multiaddr, - handler: Self::ProtocolsHandler, + handler: Self::ConnectionHandler, ) { if let Some(inner) = self.inner.as_mut() { if let Some(handler) = handler.inner { @@ -221,7 +221,7 @@ where &mut self, cx: &mut Context<'_>, params: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { if let Some(inner) = self.inner.as_mut() { inner .poll(cx, params) @@ -243,14 +243,14 @@ where } } -/// Implementation of `IntoProtocolsHandler` that can be in the disabled state. +/// Implementation of `IntoConnectionHandler` that can be in the disabled state. pub struct ToggleIntoProtoHandler { inner: Option, } -impl IntoProtocolsHandler for ToggleIntoProtoHandler +impl IntoConnectionHandler for ToggleIntoProtoHandler where - TInner: IntoProtocolsHandler, + TInner: IntoConnectionHandler, { type Handler = ToggleProtoHandler; @@ -266,7 +266,7 @@ where } } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { if let Some(inner) = self.inner.as_ref() { EitherUpgrade::A(SendWrapper(inner.inbound_protocol())) } else { @@ -275,14 +275,14 @@ where } } -/// Implementation of `ProtocolsHandler` that can be in the disabled state. +/// Implementation of [`ConnectionHandler`] that can be in the disabled state. pub struct ToggleProtoHandler { inner: Option, } -impl ProtocolsHandler for ToggleProtoHandler +impl ConnectionHandler for ToggleProtoHandler where - TInner: ProtocolsHandler, + TInner: ConnectionHandler, { type InEvent = TInner::InEvent; type OutEvent = TInner::OutEvent; @@ -354,7 +354,7 @@ where fn inject_dial_upgrade_error( &mut self, info: Self::OutboundOpenInfo, - err: ProtocolsHandlerUpgrErr<::Error>, + err: ConnectionHandlerUpgrErr<::Error>, ) { self.inner .as_mut() @@ -365,7 +365,7 @@ where fn inject_listen_upgrade_error( &mut self, info: Self::InboundOpenInfo, - err: ProtocolsHandlerUpgrErr<::Error>, + err: ConnectionHandlerUpgrErr<::Error>, ) { let (inner, info) = match (self.inner.as_mut(), info) { (Some(inner), Either::Left(info)) => (inner, info), @@ -382,10 +382,10 @@ where }; let err = match err { - ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, - ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, - ProtocolsHandlerUpgrErr::Upgrade(err) => { - ProtocolsHandlerUpgrErr::Upgrade(err.map_err(|err| match err { + ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout, + ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer, + ConnectionHandlerUpgrErr::Upgrade(err) => { + ConnectionHandlerUpgrErr::Upgrade(err.map_err(|err| match err { EitherError::A(e) => e, EitherError::B(v) => void::unreachable(v), })) @@ -406,7 +406,7 @@ where &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -424,7 +424,7 @@ where #[cfg(test)] mod tests { use super::*; - use crate::protocols_handler::DummyProtocolsHandler; + use crate::handler::DummyConnectionHandler; /// A disabled [`ToggleProtoHandler`] can receive listen upgrade errors in /// the following two cases: @@ -432,18 +432,18 @@ mod tests { /// 1. Protocol negotiation on an incoming stream failed with no protocol /// being agreed on. /// - /// 2. When combining [`ProtocolsHandler`] implementations a single - /// [`ProtocolsHandler`] might be notified of an inbound upgrade error + /// 2. When combining [`ConnectionHandler`] implementations a single + /// [`ConnectionHandler`] might be notified of an inbound upgrade error /// unrelated to its own upgrade logic. For example when nesting a /// [`ToggleProtoHandler`] in a - /// [`ProtocolsHandlerSelect`](crate::protocols_handler::ProtocolsHandlerSelect) + /// [`ConnectionHandlerSelect`](crate::protocols_handler::ConnectionHandlerSelect) /// the former might receive an inbound upgrade error even when disabled. /// /// [`ToggleProtoHandler`] should ignore the error in both of these cases. #[test] fn ignore_listen_upgrade_error_when_disabled() { - let mut handler = ToggleProtoHandler:: { inner: None }; + let mut handler = ToggleProtoHandler:: { inner: None }; - handler.inject_listen_upgrade_error(Either::Right(()), ProtocolsHandlerUpgrErr::Timeout); + handler.inject_listen_upgrade_error(Either::Right(()), ConnectionHandlerUpgrErr::Timeout); } } diff --git a/swarm/src/connection.rs b/swarm/src/connection.rs index dc567c8c..ed90da0f 100644 --- a/swarm/src/connection.rs +++ b/swarm/src/connection.rs @@ -34,7 +34,7 @@ pub use pool::{ConnectionCounters, ConnectionLimits}; pub use pool::{EstablishedConnection, PendingConnection}; pub use substream::{Close, Substream, SubstreamEndpoint}; -use crate::protocols_handler::ProtocolsHandler; +use crate::handler::ConnectionHandler; use handler_wrapper::HandlerWrapper; use libp2p_core::connection::ConnectedPoint; use libp2p_core::multiaddr::Multiaddr; @@ -56,16 +56,16 @@ pub struct Connected { /// Event generated by a [`Connection`]. #[derive(Debug, Clone)] pub enum Event { - /// Event generated by the [`ProtocolsHandler`]. + /// Event generated by the [`ConnectionHandler`]. Handler(T), /// Address of the remote has changed. AddressChange(Multiaddr), } -/// A multiplexed connection to a peer with an associated [`ProtocolsHandler`]. +/// A multiplexed connection to a peer with an associated [`ConnectionHandler`]. pub struct Connection where - THandler: ProtocolsHandler, + THandler: ConnectionHandler, { /// Node that handles the muxing. muxing: substream::Muxing>, @@ -75,7 +75,7 @@ where impl fmt::Debug for Connection where - THandler: ProtocolsHandler + fmt::Debug, + THandler: ConnectionHandler + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Connection") @@ -85,11 +85,11 @@ where } } -impl Unpin for Connection where THandler: ProtocolsHandler {} +impl Unpin for Connection where THandler: ConnectionHandler {} impl Connection where - THandler: ProtocolsHandler, + THandler: ConnectionHandler, { /// Builds a new `Connection` from the given substream multiplexer /// and connection handler. diff --git a/swarm/src/connection/handler_wrapper.rs b/swarm/src/connection/handler_wrapper.rs index 672d7b62..ad487913 100644 --- a/swarm/src/connection/handler_wrapper.rs +++ b/swarm/src/connection/handler_wrapper.rs @@ -19,8 +19,8 @@ // DEALINGS IN THE SOFTWARE. use crate::connection::{Substream, SubstreamEndpoint}; -use crate::protocols_handler::{ - KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, }; use crate::upgrade::SendWrapper; @@ -35,16 +35,16 @@ use libp2p_core::{ }; use std::{error, fmt, pin::Pin, task::Context, task::Poll, time::Duration}; -/// A wrapper for an underlying [`ProtocolsHandler`]. +/// A wrapper for an underlying [`ConnectionHandler`]. /// -/// It extends [`ProtocolsHandler`] with: +/// It extends [`ConnectionHandler`] with: /// - Enforced substream upgrade timeouts /// - Driving substream upgrades /// - Handling connection timeout // TODO: add a caching system for protocols that are supported or not pub struct HandlerWrapper where - TProtoHandler: ProtocolsHandler, + TProtoHandler: ConnectionHandler, { /// The underlying handler. handler: TProtoHandler, @@ -79,7 +79,7 @@ where substream_upgrade_protocol_override: Option, } -impl std::fmt::Debug for HandlerWrapper { +impl std::fmt::Debug for HandlerWrapper { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HandlerWrapper") .field("negotiating_in", &self.negotiating_in) @@ -94,7 +94,7 @@ impl std::fmt::Debug for HandlerWrapper HandlerWrapper { +impl HandlerWrapper { pub(crate) fn new( handler: TProtoHandler, substream_upgrade_protocol_override: Option, @@ -129,7 +129,7 @@ where { type Output = ( UserData, - Result>, + Result>, ); fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { @@ -139,7 +139,7 @@ where self.user_data .take() .expect("Future not to be polled again once ready."), - Err(ProtocolsHandlerUpgrErr::Timeout), + Err(ConnectionHandlerUpgrErr::Timeout), )) } @@ -157,7 +157,7 @@ where self.user_data .take() .expect("Future not to be polled again once ready."), - Err(ProtocolsHandlerUpgrErr::Upgrade(err)), + Err(ConnectionHandlerUpgrErr::Upgrade(err)), )), Poll::Pending => Poll::Pending, } @@ -167,8 +167,8 @@ where /// The options for a planned connection & handler shutdown. /// /// A shutdown is planned anew based on the the return value of -/// [`ProtocolsHandler::connection_keep_alive`] of the underlying handler -/// after every invocation of [`ProtocolsHandler::poll`]. +/// [`ConnectionHandler::connection_keep_alive`] of the underlying handler +/// after every invocation of [`ConnectionHandler::poll`]. /// /// A planned shutdown is always postponed for as long as there are ingoing /// or outgoing substreams being negotiated, i.e. it is a graceful, "idle" @@ -226,13 +226,13 @@ where pub type OutboundOpenInfo = ( u64, - ::OutboundOpenInfo, + ::OutboundOpenInfo, Duration, ); impl HandlerWrapper where - TProtoHandler: ProtocolsHandler, + TProtoHandler: ConnectionHandler, { pub fn inject_substream( &mut self, @@ -350,10 +350,10 @@ where }; match poll_result { - Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => { + Poll::Ready(ConnectionHandlerEvent::Custom(event)) => { return Poll::Ready(Ok(Event::Custom(event))); } - Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }) => { + Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }) => { let id = self.unique_dial_upgrade_id; let timeout = *protocol.timeout(); self.unique_dial_upgrade_id += 1; @@ -361,7 +361,7 @@ where self.queued_dial_upgrades.push((id, SendWrapper(upgrade))); return Poll::Ready(Ok(Event::OutboundSubstreamRequest((id, info, timeout)))); } - Poll::Ready(ProtocolsHandlerEvent::Close(err)) => return Poll::Ready(Err(err.into())), + Poll::Ready(ConnectionHandlerEvent::Close(err)) => return Poll::Ready(Err(err.into())), Poll::Pending => (), }; diff --git a/swarm/src/connection/pool.rs b/swarm/src/connection/pool.rs index bb8e4760..bf21976f 100644 --- a/swarm/src/connection/pool.rs +++ b/swarm/src/connection/pool.rs @@ -26,7 +26,7 @@ use crate::{ PendingInboundConnectionError, PendingOutboundConnectionError, }, transport::{Transport, TransportError}, - ConnectedPoint, Executor, IntoProtocolsHandler, Multiaddr, PeerId, ProtocolsHandler, + ConnectedPoint, ConnectionHandler, Executor, IntoConnectionHandler, Multiaddr, PeerId, }; use concurrent_dial::ConcurrentDial; use fnv::FnvHashMap; @@ -54,7 +54,7 @@ mod concurrent_dial; mod task; /// A connection `Pool` manages a set of connections for each peer. -pub struct Pool +pub struct Pool where TTrans: Transport, { @@ -68,7 +68,7 @@ where PeerId, FnvHashMap< ConnectionId, - EstablishedConnectionInfo<::InEvent>, + EstablishedConnectionInfo<::InEvent>, >, >, @@ -146,7 +146,7 @@ struct PendingConnectionInfo { abort_notifier: Option>, } -impl fmt::Debug for Pool { +impl fmt::Debug for Pool { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.debug_struct("Pool") .field("counters", &self.counters) @@ -155,13 +155,13 @@ impl fmt::Debug for Pool +pub enum PoolEvent<'a, THandler: IntoConnectionHandler, TTrans> where TTrans: Transport, { /// A new connection has been established. ConnectionEstablished { - connection: EstablishedConnection<'a, ::InEvent>, + connection: EstablishedConnection<'a, ::InEvent>, /// List of other connections to the same peer. /// /// Note: Does not include the connection reported through this event. @@ -189,7 +189,7 @@ where connected: Connected, /// The error that occurred, if any. If `None`, the connection /// was closed by the local peer. - error: Option::Error>>, + error: Option::Error>>, /// A reference to the pool that used to manage the connection. pool: &'a mut Pool, /// The remaining established connections to the same peer. @@ -242,7 +242,7 @@ where }, } -impl<'a, THandler: IntoProtocolsHandler, TTrans> fmt::Debug for PoolEvent<'a, THandler, TTrans> +impl<'a, THandler: IntoConnectionHandler, TTrans> fmt::Debug for PoolEvent<'a, THandler, TTrans> where TTrans: Transport, TTrans::Error: fmt::Debug, @@ -311,7 +311,7 @@ where impl Pool where - THandler: IntoProtocolsHandler, + THandler: IntoConnectionHandler, TTrans: Transport, { /// Creates a new empty `Pool`. @@ -465,7 +465,7 @@ where impl Pool where - THandler: IntoProtocolsHandler, + THandler: IntoConnectionHandler, TTrans: Transport + 'static, TTrans::Output: Send + 'static, TTrans::Error: Send + 'static, @@ -582,9 +582,9 @@ where pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll> where TTrans: Transport, - THandler: IntoProtocolsHandler + 'static, - THandler::Handler: ProtocolsHandler + Send, - ::OutboundOpenInfo: Send, + THandler: IntoConnectionHandler + 'static, + THandler::Handler: ConnectionHandler + Send, + ::OutboundOpenInfo: Send, { // Poll for events of established connections. // @@ -896,17 +896,17 @@ where } /// A connection in a [`Pool`]. -pub enum PoolConnection<'a, THandler: IntoProtocolsHandler> { +pub enum PoolConnection<'a, THandler: IntoConnectionHandler> { Pending(PendingConnection<'a, THandler>), Established(EstablishedConnection<'a, THandlerInEvent>), } /// A pending connection in a pool. -pub struct PendingConnection<'a, THandler: IntoProtocolsHandler> { +pub struct PendingConnection<'a, THandler: IntoConnectionHandler> { entry: hash_map::OccupiedEntry<'a, ConnectionId, PendingConnectionInfo>, } -impl PendingConnection<'_, THandler> { +impl PendingConnection<'_, THandler> { /// Aborts the connection attempt, closing the connection. pub fn abort(mut self) { if let Some(notifier) = self.entry.get_mut().abort_notifier.take() { diff --git a/swarm/src/connection/pool/task.rs b/swarm/src/connection/pool/task.rs index 7464b7a1..866049e5 100644 --- a/swarm/src/connection/pool/task.rs +++ b/swarm/src/connection/pool/task.rs @@ -27,7 +27,7 @@ use crate::{ self, ConnectionError, PendingInboundConnectionError, PendingOutboundConnectionError, }, transport::{Transport, TransportError}, - Multiaddr, PeerId, ProtocolsHandler, + ConnectionHandler, Multiaddr, PeerId, }; use futures::{ channel::{mpsc, oneshot}, @@ -72,7 +72,7 @@ where } #[derive(Debug)] -pub enum EstablishedConnectionEvent { +pub enum EstablishedConnectionEvent { /// A node we are connected to has changed its address. AddressChange { id: ConnectionId, @@ -183,7 +183,7 @@ pub async fn new_for_established_connection( mut command_receiver: mpsc::Receiver>, mut events: mpsc::Sender>, ) where - THandler: ProtocolsHandler, + THandler: ConnectionHandler, { loop { match futures::future::select( diff --git a/swarm/src/protocols_handler.rs b/swarm/src/handler.rs similarity index 69% rename from swarm/src/protocols_handler.rs rename to swarm/src/handler.rs index 5a9d71cb..2a301b70 100644 --- a/swarm/src/protocols_handler.rs +++ b/swarm/src/handler.rs @@ -18,24 +18,25 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -//! Once a connection to a remote peer is established, a `ProtocolsHandler` negotiates +//! Once a connection to a remote peer is established, a [`ConnectionHandler`] negotiates //! and handles one or more specific protocols on the connection. //! -//! Protocols are negotiated and used on individual substreams of the connection. -//! Thus a `ProtocolsHandler` defines the inbound and outbound upgrades to apply -//! when creating a new inbound or outbound substream, respectively, and is notified -//! by a `Swarm` when these upgrades have been successfully applied, including the -//! final output of the upgrade. A `ProtocolsHandler` can then continue communicating -//! with the peer over the substream using the negotiated protocol(s). +//! Protocols are negotiated and used on individual substreams of the connection. Thus a +//! [`ConnectionHandler`] defines the inbound and outbound upgrades to apply when creating a new +//! inbound or outbound substream, respectively, and is notified by a [`Swarm`](crate::Swarm) when +//! these upgrades have been successfully applied, including the final output of the upgrade. A +//! [`ConnectionHandler`] can then continue communicating with the peer over the substream using the +//! negotiated protocol(s). //! -//! Two `ProtocolsHandler`s can be composed with [`ProtocolsHandler::select()`] +//! Two [`ConnectionHandler`]s can be composed with [`ConnectionHandler::select()`] //! in order to build a new handler supporting the combined set of protocols, //! with methods being dispatched to the appropriate handler according to the //! used protocol(s) determined by the associated types of the handlers. //! -//! > **Note**: A `ProtocolsHandler` handles one or more protocols in the context of a single +//! > **Note**: A [`ConnectionHandler`] handles one or more protocols in the context of a single //! > connection with a remote. In order to handle a protocol that requires knowledge of -//! > the network as a whole, see the `NetworkBehaviour` trait. +//! > the network as a whole, see the +//! > [`NetworkBehaviour`](crate::behaviour::NetworkBehaviour) trait. mod dummy; pub mod either; @@ -51,11 +52,11 @@ use instant::Instant; use libp2p_core::{upgrade::UpgradeError, ConnectedPoint, Multiaddr, PeerId}; use std::{cmp::Ordering, error, fmt, task::Context, task::Poll, time::Duration}; -pub use dummy::DummyProtocolsHandler; +pub use dummy::DummyConnectionHandler; pub use map_in::MapInEvent; pub use map_out::MapOutEvent; pub use one_shot::{OneShotHandler, OneShotHandlerConfig}; -pub use select::{IntoProtocolsHandlerSelect, ProtocolsHandlerSelect}; +pub use select::{ConnectionHandlerSelect, IntoConnectionHandlerSelect}; /// A handler for a set of protocols used on a connection with a remote. /// @@ -67,34 +68,34 @@ pub use select::{IntoProtocolsHandlerSelect, ProtocolsHandlerSelect}; /// Communication with a remote over a set of protocols is initiated in one of two ways: /// /// 1. Dialing by initiating a new outbound substream. In order to do so, -/// [`ProtocolsHandler::poll()`] must return an [`ProtocolsHandlerEvent::OutboundSubstreamRequest`], +/// [`ConnectionHandler::poll()`] must return an [`ConnectionHandlerEvent::OutboundSubstreamRequest`], /// providing an instance of [`libp2p_core::upgrade::OutboundUpgrade`] that is used to negotiate the -/// protocol(s). Upon success, [`ProtocolsHandler::inject_fully_negotiated_outbound`] +/// protocol(s). Upon success, [`ConnectionHandler::inject_fully_negotiated_outbound`] /// is called with the final output of the upgrade. /// /// 2. Listening by accepting a new inbound substream. When a new inbound substream -/// is created on a connection, [`ProtocolsHandler::listen_protocol`] is called +/// is created on a connection, [`ConnectionHandler::listen_protocol`] is called /// to obtain an instance of [`libp2p_core::upgrade::InboundUpgrade`] that is used to /// negotiate the protocol(s). Upon success, -/// [`ProtocolsHandler::inject_fully_negotiated_inbound`] is called with the final +/// [`ConnectionHandler::inject_fully_negotiated_inbound`] is called with the final /// output of the upgrade. /// /// # Connection Keep-Alive /// -/// A `ProtocolsHandler` can influence the lifetime of the underlying connection -/// through [`ProtocolsHandler::connection_keep_alive`]. That is, the protocol +/// A [`ConnectionHandler`] can influence the lifetime of the underlying connection +/// through [`ConnectionHandler::connection_keep_alive`]. That is, the protocol /// implemented by the handler can include conditions for terminating the connection. /// The lifetime of successfully negotiated substreams is fully controlled by the handler. /// /// Implementors of this trait should keep in mind that the connection can be closed at any time. /// When a connection is closed gracefully, the substreams used by the handler may still /// continue reading data until the remote closes its side of the connection. -pub trait ProtocolsHandler: Send + 'static { +pub trait ConnectionHandler: Send + 'static { /// Custom event that can be received from the outside. type InEvent: fmt::Debug + Send + 'static; /// Custom event that can be produced by the handler and that will be returned to the outside. type OutEvent: fmt::Debug + Send + 'static; - /// The type of errors returned by [`ProtocolsHandler::poll`]. + /// The type of errors returned by [`ConnectionHandler::poll`]. type Error: error::Error + fmt::Debug + Send + 'static; /// The inbound upgrade for the protocol(s) used by the handler. type InboundProtocol: InboundUpgradeSend; @@ -124,7 +125,7 @@ pub trait ProtocolsHandler: Send + 'static { /// Injects the output of a successful upgrade on a new outbound substream. /// /// The second argument is the information that was previously passed to - /// [`ProtocolsHandlerEvent::OutboundSubstreamRequest`]. + /// [`ConnectionHandlerEvent::OutboundSubstreamRequest`]. fn inject_fully_negotiated_outbound( &mut self, protocol: ::Output, @@ -141,22 +142,22 @@ pub trait ProtocolsHandler: Send + 'static { fn inject_dial_upgrade_error( &mut self, info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ); /// Indicates to the handler that upgrading an inbound substream to the given protocol has failed. fn inject_listen_upgrade_error( &mut self, _: Self::InboundOpenInfo, - _: ProtocolsHandlerUpgrErr<::Error>, + _: ConnectionHandlerUpgrErr<::Error>, ) { } /// Returns until when the connection should be kept alive. /// /// This method is called by the `Swarm` after each invocation of - /// [`ProtocolsHandler::poll`] to determine if the connection and the associated - /// `ProtocolsHandler`s should be kept alive as far as this handler is concerned + /// [`ConnectionHandler::poll`] to determine if the connection and the associated + /// [`ConnectionHandler`]s should be kept alive as far as this handler is concerned /// and if so, for how long. /// /// Returning [`KeepAlive::No`] indicates that the connection should be @@ -169,7 +170,7 @@ pub trait ProtocolsHandler: Send + 'static { /// be kept alive until the next call to this method. /// /// > **Note**: The connection is always closed and the handler destroyed - /// > when [`ProtocolsHandler::poll`] returns an error. Furthermore, the + /// > when [`ConnectionHandler::poll`] returns an error. Furthermore, the /// > connection may be closed for reasons outside of the control /// > of the handler. fn connection_keep_alive(&self) -> KeepAlive; @@ -179,7 +180,7 @@ pub trait ProtocolsHandler: Send + 'static { &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -205,25 +206,25 @@ pub trait ProtocolsHandler: Send + 'static { MapOutEvent::new(self, map) } - /// Creates a new `ProtocolsHandler` that selects either this handler or + /// Creates a new [`ConnectionHandler`] that selects either this handler or /// `other` by delegating methods calls appropriately. /// /// > **Note**: The largest `KeepAlive` returned by the two handlers takes precedence, - /// > i.e. is returned from [`ProtocolsHandler::connection_keep_alive`] by the returned + /// > i.e. is returned from [`ConnectionHandler::connection_keep_alive`] by the returned /// > handler. - fn select(self, other: TProto2) -> ProtocolsHandlerSelect + fn select(self, other: TProto2) -> ConnectionHandlerSelect where Self: Sized, { - ProtocolsHandlerSelect::new(self, other) + ConnectionHandlerSelect::new(self, other) } } /// Configuration of inbound or outbound substream protocol(s) -/// for a [`ProtocolsHandler`]. +/// for a [`ConnectionHandler`]. /// -/// The inbound substream protocol(s) are defined by [`ProtocolsHandler::listen_protocol`] -/// and the outbound substream protocol(s) by [`ProtocolsHandlerEvent::OutboundSubstreamRequest`]. +/// The inbound substream protocol(s) are defined by [`ConnectionHandler::listen_protocol`] +/// and the outbound substream protocol(s) by [`ConnectionHandlerEvent::OutboundSubstreamRequest`]. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub struct SubstreamProtocol { upgrade: TUpgrade, @@ -297,7 +298,7 @@ impl SubstreamProtocol { /// Event produced by a handler. #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum ProtocolsHandlerEvent { +pub enum ConnectionHandlerEvent { /// Request a new outbound substream to be opened with the remote. OutboundSubstreamRequest { /// The protocol(s) to apply on the substream. @@ -306,12 +307,12 @@ pub enum ProtocolsHandlerEvent - ProtocolsHandlerEvent + ConnectionHandlerEvent { /// If this is an `OutboundSubstreamRequest`, maps the `info` member from a /// `TOutboundOpenInfo` to something else. pub fn map_outbound_open_info( self, map: F, - ) -> ProtocolsHandlerEvent + ) -> ConnectionHandlerEvent where F: FnOnce(TOutboundOpenInfo) -> I, { match self { - ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { - ProtocolsHandlerEvent::OutboundSubstreamRequest { + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => { + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: protocol.map_info(map), } } - ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val), - ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val), + ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(val), + ConnectionHandlerEvent::Close(val) => ConnectionHandlerEvent::Close(val), } } @@ -347,18 +348,18 @@ impl pub fn map_protocol( self, map: F, - ) -> ProtocolsHandlerEvent + ) -> ConnectionHandlerEvent where F: FnOnce(TConnectionUpgrade) -> I, { match self { - ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { - ProtocolsHandlerEvent::OutboundSubstreamRequest { + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => { + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: protocol.map_upgrade(map), } } - ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val), - ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val), + ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(val), + ConnectionHandlerEvent::Close(val) => ConnectionHandlerEvent::Close(val), } } @@ -366,16 +367,16 @@ impl pub fn map_custom( self, map: F, - ) -> ProtocolsHandlerEvent + ) -> ConnectionHandlerEvent where F: FnOnce(TCustom) -> I, { match self { - ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { - ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => { + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } } - ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(map(val)), - ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val), + ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(map(val)), + ConnectionHandlerEvent::Close(val) => ConnectionHandlerEvent::Close(val), } } @@ -383,23 +384,23 @@ impl pub fn map_close( self, map: F, - ) -> ProtocolsHandlerEvent + ) -> ConnectionHandlerEvent where F: FnOnce(TErr) -> I, { match self { - ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { - ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => { + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } } - ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val), - ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(map(val)), + ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(val), + ConnectionHandlerEvent::Close(val) => ConnectionHandlerEvent::Close(map(val)), } } } /// Error that can happen on an outbound substream opening attempt. #[derive(Debug)] -pub enum ProtocolsHandlerUpgrErr { +pub enum ConnectionHandlerUpgrErr { /// The opening attempt timed out before the negotiation was fully completed. Timeout, /// There was an error in the timer used. @@ -408,54 +409,54 @@ pub enum ProtocolsHandlerUpgrErr { Upgrade(UpgradeError), } -impl ProtocolsHandlerUpgrErr { +impl ConnectionHandlerUpgrErr { /// Map the inner [`UpgradeError`] type. - pub fn map_upgrade_err(self, f: F) -> ProtocolsHandlerUpgrErr + pub fn map_upgrade_err(self, f: F) -> ConnectionHandlerUpgrErr where F: FnOnce(UpgradeError) -> UpgradeError, { match self { - ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, - ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, - ProtocolsHandlerUpgrErr::Upgrade(e) => ProtocolsHandlerUpgrErr::Upgrade(f(e)), + ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout, + ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer, + ConnectionHandlerUpgrErr::Upgrade(e) => ConnectionHandlerUpgrErr::Upgrade(f(e)), } } } -impl fmt::Display for ProtocolsHandlerUpgrErr +impl fmt::Display for ConnectionHandlerUpgrErr where TUpgrErr: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - ProtocolsHandlerUpgrErr::Timeout => { + ConnectionHandlerUpgrErr::Timeout => { write!(f, "Timeout error while opening a substream") } - ProtocolsHandlerUpgrErr::Timer => { + ConnectionHandlerUpgrErr::Timer => { write!(f, "Timer error while opening a substream") } - ProtocolsHandlerUpgrErr::Upgrade(err) => write!(f, "{}", err), + ConnectionHandlerUpgrErr::Upgrade(err) => write!(f, "{}", err), } } } -impl error::Error for ProtocolsHandlerUpgrErr +impl error::Error for ConnectionHandlerUpgrErr where TUpgrErr: error::Error + 'static, { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { - ProtocolsHandlerUpgrErr::Timeout => None, - ProtocolsHandlerUpgrErr::Timer => None, - ProtocolsHandlerUpgrErr::Upgrade(err) => Some(err), + ConnectionHandlerUpgrErr::Timeout => None, + ConnectionHandlerUpgrErr::Timer => None, + ConnectionHandlerUpgrErr::Upgrade(err) => Some(err), } } } -/// Prototype for a `ProtocolsHandler`. -pub trait IntoProtocolsHandler: Send + 'static { +/// Prototype for a [`ConnectionHandler`]. +pub trait IntoConnectionHandler: Send + 'static { /// The protocols handler. - type Handler: ProtocolsHandler; + type Handler: ConnectionHandler; /// Builds the protocols handler. /// @@ -467,21 +468,21 @@ pub trait IntoProtocolsHandler: Send + 'static { ) -> Self::Handler; /// Return the handler's inbound protocol. - fn inbound_protocol(&self) -> ::InboundProtocol; + fn inbound_protocol(&self) -> ::InboundProtocol; - /// Builds an implementation of `IntoProtocolsHandler` that handles both this protocol and the + /// Builds an implementation of [`IntoConnectionHandler`] that handles both this protocol and the /// other one together. - fn select(self, other: TProto2) -> IntoProtocolsHandlerSelect + fn select(self, other: TProto2) -> IntoConnectionHandlerSelect where Self: Sized, { - IntoProtocolsHandlerSelect::new(self, other) + IntoConnectionHandlerSelect::new(self, other) } } -impl IntoProtocolsHandler for T +impl IntoConnectionHandler for T where - T: ProtocolsHandler, + T: ConnectionHandler, { type Handler = Self; @@ -489,7 +490,7 @@ where self } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { self.listen_protocol().into_upgrade().0 } } diff --git a/swarm/src/protocols_handler/dummy.rs b/swarm/src/handler/dummy.rs similarity index 87% rename from swarm/src/protocols_handler/dummy.rs rename to swarm/src/handler/dummy.rs index 700b5224..67594686 100644 --- a/swarm/src/protocols_handler/dummy.rs +++ b/swarm/src/handler/dummy.rs @@ -18,8 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::protocols_handler::{ - KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + SubstreamProtocol, }; use crate::NegotiatedSubstream; use libp2p_core::{ @@ -29,21 +30,21 @@ use libp2p_core::{ use std::task::{Context, Poll}; use void::Void; -/// Implementation of `ProtocolsHandler` that doesn't handle anything. +/// Implementation of [`ConnectionHandler`] that doesn't handle anything. #[derive(Clone, Debug)] -pub struct DummyProtocolsHandler { +pub struct DummyConnectionHandler { pub keep_alive: KeepAlive, } -impl Default for DummyProtocolsHandler { +impl Default for DummyConnectionHandler { fn default() -> Self { - DummyProtocolsHandler { + DummyConnectionHandler { keep_alive: KeepAlive::No, } } } -impl ProtocolsHandler for DummyProtocolsHandler { +impl ConnectionHandler for DummyConnectionHandler { type InEvent = Void; type OutEvent = Void; type Error = Void; @@ -81,7 +82,7 @@ impl ProtocolsHandler for DummyProtocolsHandler { fn inject_dial_upgrade_error( &mut self, _: Self::OutboundOpenInfo, - _: ProtocolsHandlerUpgrErr< + _: ConnectionHandlerUpgrErr< >::Error, >, ) { @@ -90,7 +91,7 @@ impl ProtocolsHandler for DummyProtocolsHandler { fn inject_listen_upgrade_error( &mut self, _: Self::InboundOpenInfo, - _: ProtocolsHandlerUpgrErr< + _: ConnectionHandlerUpgrErr< >::Error, >, ) { @@ -104,7 +105,7 @@ impl ProtocolsHandler for DummyProtocolsHandler { &mut self, _: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, diff --git a/swarm/src/protocols_handler/either.rs b/swarm/src/handler/either.rs similarity index 74% rename from swarm/src/protocols_handler/either.rs rename to swarm/src/handler/either.rs index c51baadd..21d386ec 100644 --- a/swarm/src/protocols_handler/either.rs +++ b/swarm/src/handler/either.rs @@ -18,9 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::protocols_handler::{ - IntoProtocolsHandler, KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, + KeepAlive, SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; use either::Either; @@ -34,12 +34,12 @@ pub enum IntoEitherHandler { Right(R), } -/// Implementation of a [`IntoProtocolsHandler`] that represents either of two [`IntoProtocolsHandler`] +/// Implementation of a [`IntoConnectionHandler`] that represents either of two [`IntoConnectionHandler`] /// implementations. -impl IntoProtocolsHandler for IntoEitherHandler +impl IntoConnectionHandler for IntoEitherHandler where - L: IntoProtocolsHandler, - R: IntoProtocolsHandler, + L: IntoConnectionHandler, + R: IntoConnectionHandler, { type Handler = Either; @@ -52,7 +52,7 @@ where } } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { match self { IntoEitherHandler::Left(into_handler) => { EitherUpgrade::A(SendWrapper(into_handler.inbound_protocol())) @@ -64,12 +64,12 @@ where } } -/// Implementation of a [`ProtocolsHandler`] that represents either of two [`ProtocolsHandler`] +/// Implementation of a [`ConnectionHandler`] that represents either of two [`ConnectionHandler`] /// implementations. -impl ProtocolsHandler for Either +impl ConnectionHandler for Either where - L: ProtocolsHandler, - R: ProtocolsHandler, + L: ConnectionHandler, + R: ConnectionHandler, { type InEvent = Either; type OutEvent = Either; @@ -144,59 +144,59 @@ where fn inject_dial_upgrade_error( &mut self, info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { match error { - ProtocolsHandlerUpgrErr::Timer => match (self, info) { + ConnectionHandlerUpgrErr::Timer => match (self, info) { (Either::Left(handler), Either::Left(info)) => { - handler.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer); + handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer); } (Either::Right(handler), Either::Right(info)) => { - handler.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer); + handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer); } _ => unreachable!(), }, - ProtocolsHandlerUpgrErr::Timeout => match (self, info) { + ConnectionHandlerUpgrErr::Timeout => match (self, info) { (Either::Left(handler), Either::Left(info)) => { - handler.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout); + handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout); } (Either::Right(handler), Either::Right(info)) => { - handler.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout); + handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout); } _ => unreachable!(), }, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => match (self, info) { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => match (self, info) { (Either::Left(handler), Either::Left(info)) => { handler.inject_dial_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), ); } (Either::Right(handler), Either::Right(info)) => { handler.inject_dial_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), ); } _ => unreachable!(), }, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { match (self, info) { (Either::Left(handler), Either::Left(info)) => { handler.inject_dial_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ); } _ => unreachable!(), } } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { match (self, info) { (Either::Right(handler), Either::Right(info)) => { handler.inject_dial_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ); } _ => unreachable!(), @@ -208,59 +208,59 @@ where fn inject_listen_upgrade_error( &mut self, info: Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { match error { - ProtocolsHandlerUpgrErr::Timer => match (self, info) { + ConnectionHandlerUpgrErr::Timer => match (self, info) { (Either::Left(handler), Either::Left(info)) => { - handler.inject_listen_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer); + handler.inject_listen_upgrade_error(info, ConnectionHandlerUpgrErr::Timer); } (Either::Right(handler), Either::Right(info)) => { - handler.inject_listen_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer); + handler.inject_listen_upgrade_error(info, ConnectionHandlerUpgrErr::Timer); } _ => unreachable!(), }, - ProtocolsHandlerUpgrErr::Timeout => match (self, info) { + ConnectionHandlerUpgrErr::Timeout => match (self, info) { (Either::Left(handler), Either::Left(info)) => { - handler.inject_listen_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout); + handler.inject_listen_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout); } (Either::Right(handler), Either::Right(info)) => { - handler.inject_listen_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout); + handler.inject_listen_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout); } _ => unreachable!(), }, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => match (self, info) { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => match (self, info) { (Either::Left(handler), Either::Left(info)) => { handler.inject_listen_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), ); } (Either::Right(handler), Either::Right(info)) => { handler.inject_listen_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), ); } _ => unreachable!(), }, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { match (self, info) { (Either::Left(handler), Either::Left(info)) => { handler.inject_listen_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ); } _ => unreachable!(), } } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { match (self, info) { (Either::Right(handler), Either::Right(info)) => { handler.inject_listen_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ); } _ => unreachable!(), @@ -280,7 +280,7 @@ where &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, diff --git a/swarm/src/protocols_handler/map_in.rs b/swarm/src/handler/map_in.rs similarity index 88% rename from swarm/src/protocols_handler/map_in.rs rename to swarm/src/handler/map_in.rs index 1c1e436e..96575bbc 100644 --- a/swarm/src/protocols_handler/map_in.rs +++ b/swarm/src/handler/map_in.rs @@ -18,8 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::protocols_handler::{ - KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_core::Multiaddr; @@ -43,9 +44,9 @@ impl MapInEvent { } } -impl ProtocolsHandler for MapInEvent +impl ConnectionHandler for MapInEvent where - TProtoHandler: ProtocolsHandler, + TProtoHandler: ConnectionHandler, TMap: Fn(TNewIn) -> Option, TNewIn: Debug + Send + 'static, TMap: Send + 'static, @@ -91,7 +92,7 @@ where fn inject_dial_upgrade_error( &mut self, info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { self.inner.inject_dial_upgrade_error(info, error) } @@ -99,7 +100,7 @@ where fn inject_listen_upgrade_error( &mut self, info: Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { self.inner.inject_listen_upgrade_error(info, error) } @@ -112,7 +113,7 @@ where &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, diff --git a/swarm/src/protocols_handler/map_out.rs b/swarm/src/handler/map_out.rs similarity index 81% rename from swarm/src/protocols_handler/map_out.rs rename to swarm/src/handler/map_out.rs index 77d0e1ea..f92958e3 100644 --- a/swarm/src/protocols_handler/map_out.rs +++ b/swarm/src/handler/map_out.rs @@ -18,8 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::protocols_handler::{ - KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_core::Multiaddr; @@ -39,9 +40,9 @@ impl MapOutEvent { } } -impl ProtocolsHandler for MapOutEvent +impl ConnectionHandler for MapOutEvent where - TProtoHandler: ProtocolsHandler, + TProtoHandler: ConnectionHandler, TMap: FnMut(TProtoHandler::OutEvent) -> TNewOut, TNewOut: Debug + Send + 'static, TMap: Send + 'static, @@ -85,7 +86,7 @@ where fn inject_dial_upgrade_error( &mut self, info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { self.inner.inject_dial_upgrade_error(info, error) } @@ -93,7 +94,7 @@ where fn inject_listen_upgrade_error( &mut self, info: Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { self.inner.inject_listen_upgrade_error(info, error) } @@ -106,7 +107,7 @@ where &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -114,10 +115,10 @@ where >, > { self.inner.poll(cx).map(|ev| match ev { - ProtocolsHandlerEvent::Custom(ev) => ProtocolsHandlerEvent::Custom((self.map)(ev)), - ProtocolsHandlerEvent::Close(err) => ProtocolsHandlerEvent::Close(err), - ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { - ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } + ConnectionHandlerEvent::Custom(ev) => ConnectionHandlerEvent::Custom((self.map)(ev)), + ConnectionHandlerEvent::Close(err) => ConnectionHandlerEvent::Close(err), + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => { + ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } } }) } diff --git a/swarm/src/protocols_handler/multi.rs b/swarm/src/handler/multi.rs similarity index 86% rename from swarm/src/protocols_handler/multi.rs rename to swarm/src/handler/multi.rs index f8654437..02ce4b24 100644 --- a/swarm/src/protocols_handler/multi.rs +++ b/swarm/src/handler/multi.rs @@ -18,12 +18,12 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -//! A [`ProtocolsHandler`] implementation that combines multiple other `ProtocolsHandler`s +//! A [`ConnectionHandler`] implementation that combines multiple other [`ConnectionHandler`]s //! indexed by some key. -use crate::protocols_handler::{ - IntoProtocolsHandler, KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, + KeepAlive, SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, UpgradeInfoSend}; use crate::NegotiatedSubstream; @@ -42,7 +42,7 @@ use std::{ time::Duration, }; -/// A [`ProtocolsHandler`] for multiple `ProtocolsHandler`s of the same type. +/// A [`ConnectionHandler`] for multiple [`ConnectionHandler`]s of the same type. #[derive(Clone)] pub struct MultiHandler { handlers: HashMap, @@ -63,7 +63,7 @@ where impl MultiHandler where K: Hash + Eq, - H: ProtocolsHandler, + H: ConnectionHandler, { /// Create and populate a `MultiHandler` from the given handler iterator. /// @@ -84,20 +84,20 @@ where } } -impl ProtocolsHandler for MultiHandler +impl ConnectionHandler for MultiHandler where K: Clone + Debug + Hash + Eq + Send + 'static, - H: ProtocolsHandler, + 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); + 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 @@ -164,7 +164,7 @@ where fn inject_dial_upgrade_error( &mut self, (key, arg): Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { if let Some(h) = self.handlers.get_mut(&key) { h.inject_dial_upgrade_error(arg, error) @@ -176,36 +176,36 @@ where fn inject_listen_upgrade_error( &mut self, mut info: Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { match error { - ProtocolsHandlerUpgrErr::Timer => { + ConnectionHandlerUpgrErr::Timer => { for (k, h) in &mut self.handlers { if let Some(i) = info.take(k) { - h.inject_listen_upgrade_error(i, ProtocolsHandlerUpgrErr::Timer) + h.inject_listen_upgrade_error(i, ConnectionHandlerUpgrErr::Timer) } } } - ProtocolsHandlerUpgrErr::Timeout => { + ConnectionHandlerUpgrErr::Timeout => { for (k, h) in &mut self.handlers { if let Some(i) = info.take(k) { - h.inject_listen_upgrade_error(i, ProtocolsHandlerUpgrErr::Timeout) + h.inject_listen_upgrade_error(i, ConnectionHandlerUpgrErr::Timeout) } } } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { for (k, h) in &mut self.handlers { if let Some(i) = info.take(k) { h.inject_listen_upgrade_error( i, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( NegotiationError::Failed, )), ) } } } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( NegotiationError::ProtocolError(e), )) => match e { ProtocolError::IoError(e) => { @@ -216,7 +216,7 @@ where )); h.inject_listen_upgrade_error( i, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), ) } } @@ -227,7 +227,7 @@ where let e = NegotiationError::ProtocolError(ProtocolError::InvalidMessage); h.inject_listen_upgrade_error( i, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), ) } } @@ -238,7 +238,7 @@ where let e = NegotiationError::ProtocolError(ProtocolError::InvalidProtocol); h.inject_listen_upgrade_error( i, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), ) } } @@ -250,18 +250,18 @@ where NegotiationError::ProtocolError(ProtocolError::TooManyProtocols); h.inject_listen_upgrade_error( i, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), ) } } } }, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply((k, e))) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply((k, e))) => { if let Some(h) = self.handlers.get_mut(&k) { if let Some(i) = info.take(&k) { h.inject_listen_upgrade_error( i, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ) } } @@ -281,7 +281,7 @@ where &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -319,7 +319,7 @@ where } } -/// A [`IntoProtocolsHandler`] for multiple other `IntoProtocolsHandler`s. +/// A [`IntoConnectionHandler`] for multiple other `IntoConnectionHandler`s. #[derive(Clone)] pub struct IntoMultiHandler { handlers: HashMap, @@ -340,7 +340,7 @@ where impl IntoMultiHandler where K: Hash + Eq, - H: IntoProtocolsHandler, + H: IntoConnectionHandler, { /// Create and populate an `IntoMultiHandler` from the given iterator. /// @@ -357,10 +357,10 @@ where } } -impl IntoProtocolsHandler for IntoMultiHandler +impl IntoConnectionHandler for IntoMultiHandler where K: Debug + Clone + Eq + Hash + Send + 'static, - H: IntoProtocolsHandler, + H: IntoConnectionHandler, { type Handler = MultiHandler; @@ -374,7 +374,7 @@ where } } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { Upgrade { upgrades: self .handlers @@ -414,7 +414,7 @@ impl Info { } } -/// Inbound and outbound upgrade for all `ProtocolsHandler`s. +/// Inbound and outbound upgrade for all [`ConnectionHandler`]s. #[derive(Clone)] pub struct Upgrade { upgrades: Vec<(K, H)>, diff --git a/swarm/src/protocols_handler/one_shot.rs b/swarm/src/handler/one_shot.rs similarity index 90% rename from swarm/src/protocols_handler/one_shot.rs rename to swarm/src/handler/one_shot.rs index 0851ff82..5db6b4d1 100644 --- a/swarm/src/protocols_handler/one_shot.rs +++ b/swarm/src/handler/one_shot.rs @@ -18,15 +18,16 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::protocols_handler::{ - KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, + SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend}; use instant::Instant; use smallvec::SmallVec; use std::{error, fmt::Debug, task::Context, task::Poll, time::Duration}; -/// A `ProtocolsHandler` that opens a new substream for each request. +/// A [`ConnectionHandler`] that opens a new substream for each request. // TODO: Debug pub struct OneShotHandler where @@ -35,7 +36,7 @@ where /// The upgrade for inbound substreams. listen_protocol: SubstreamProtocol, /// If `Some`, something bad happened and we should shut down the handler with an error. - pending_error: Option::Error>>, + pending_error: Option::Error>>, /// Queue of events to produce in `poll()`. events_out: SmallVec<[TEvent; 4]>, /// Queue of outbound substreams to open. @@ -109,7 +110,7 @@ where } } -impl ProtocolsHandler for OneShotHandler +impl ConnectionHandler for OneShotHandler where TInbound: InboundUpgradeSend + Send + 'static, TOutbound: Debug + OutboundUpgradeSend, @@ -121,7 +122,7 @@ where { type InEvent = TOutbound; type OutEvent = TEvent; - type Error = ProtocolsHandlerUpgrErr<::Error>; + type Error = ConnectionHandlerUpgrErr<::Error>; type InboundProtocol = TInbound; type OutboundProtocol = TOutbound; type OutboundOpenInfo = (); @@ -160,7 +161,7 @@ where fn inject_dial_upgrade_error( &mut self, _info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { if self.pending_error.is_none() { self.pending_error = Some(error); @@ -175,7 +176,7 @@ where &mut self, _: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -183,11 +184,11 @@ where >, > { if let Some(err) = self.pending_error.take() { - return Poll::Ready(ProtocolsHandlerEvent::Close(err)); + return Poll::Ready(ConnectionHandlerEvent::Close(err)); } if !self.events_out.is_empty() { - return Poll::Ready(ProtocolsHandlerEvent::Custom(self.events_out.remove(0))); + return Poll::Ready(ConnectionHandlerEvent::Custom(self.events_out.remove(0))); } else { self.events_out.shrink_to_fit(); } @@ -196,7 +197,7 @@ where if self.dial_negotiated < self.config.max_dial_negotiated { self.dial_negotiated += 1; let upgrade = self.dial_queue.remove(0); - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: SubstreamProtocol::new(upgrade, ()) .with_timeout(self.config.outbound_substream_timeout), }); diff --git a/swarm/src/protocols_handler/select.rs b/swarm/src/handler/select.rs similarity index 65% rename from swarm/src/protocols_handler/select.rs rename to swarm/src/handler/select.rs index cce84928..70a6f3c2 100644 --- a/swarm/src/protocols_handler/select.rs +++ b/swarm/src/handler/select.rs @@ -18,9 +18,9 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. -use crate::protocols_handler::{ - IntoProtocolsHandler, KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, - ProtocolsHandlerUpgrErr, SubstreamProtocol, +use crate::handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler, + KeepAlive, SubstreamProtocol, }; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; @@ -31,19 +31,19 @@ use libp2p_core::{ }; use std::{cmp, task::Context, task::Poll}; -/// Implementation of `IntoProtocolsHandler` that combines two protocols into one. +/// Implementation of `IntoConnectionHandler` that combines two protocols into one. #[derive(Debug, Clone)] -pub struct IntoProtocolsHandlerSelect { +pub struct IntoConnectionHandlerSelect { /// The first protocol. proto1: TProto1, /// The second protocol. proto2: TProto2, } -impl IntoProtocolsHandlerSelect { - /// Builds a `IntoProtocolsHandlerSelect`. +impl IntoConnectionHandlerSelect { + /// Builds a `IntoConnectionHandlerSelect`. pub(crate) fn new(proto1: TProto1, proto2: TProto2) -> Self { - IntoProtocolsHandlerSelect { proto1, proto2 } + IntoConnectionHandlerSelect { proto1, proto2 } } pub fn into_inner(self) -> (TProto1, TProto2) { @@ -51,25 +51,25 @@ impl IntoProtocolsHandlerSelect { } } -impl IntoProtocolsHandler for IntoProtocolsHandlerSelect +impl IntoConnectionHandler for IntoConnectionHandlerSelect where - TProto1: IntoProtocolsHandler, - TProto2: IntoProtocolsHandler, + TProto1: IntoConnectionHandler, + TProto2: IntoConnectionHandler, { - type Handler = ProtocolsHandlerSelect; + type Handler = ConnectionHandlerSelect; fn into_handler( self, remote_peer_id: &PeerId, connected_point: &ConnectedPoint, ) -> Self::Handler { - ProtocolsHandlerSelect { + ConnectionHandlerSelect { proto1: self.proto1.into_handler(remote_peer_id, connected_point), proto2: self.proto2.into_handler(remote_peer_id, connected_point), } } - fn inbound_protocol(&self) -> ::InboundProtocol { + fn inbound_protocol(&self) -> ::InboundProtocol { SelectUpgrade::new( SendWrapper(self.proto1.inbound_protocol()), SendWrapper(self.proto2.inbound_protocol()), @@ -77,19 +77,19 @@ where } } -/// Implementation of `ProtocolsHandler` that combines two protocols into one. +/// Implementation of [`ConnectionHandler`] that combines two protocols into one. #[derive(Debug, Clone)] -pub struct ProtocolsHandlerSelect { +pub struct ConnectionHandlerSelect { /// The first protocol. proto1: TProto1, /// The second protocol. proto2: TProto2, } -impl ProtocolsHandlerSelect { - /// Builds a `ProtocolsHandlerSelect`. +impl ConnectionHandlerSelect { + /// Builds a [`ConnectionHandlerSelect`]. pub(crate) fn new(proto1: TProto1, proto2: TProto2) -> Self { - ProtocolsHandlerSelect { proto1, proto2 } + ConnectionHandlerSelect { proto1, proto2 } } pub fn into_inner(self) -> (TProto1, TProto2) { @@ -97,17 +97,17 @@ impl ProtocolsHandlerSelect { } } -impl ProtocolsHandler for ProtocolsHandlerSelect +impl ConnectionHandler for ConnectionHandlerSelect where - TProto1: ProtocolsHandler, - TProto2: ProtocolsHandler, + TProto1: ConnectionHandler, + TProto2: ConnectionHandler, { type InEvent = EitherOutput; type OutEvent = EitherOutput; type Error = EitherError; type InboundProtocol = SelectUpgrade< - SendWrapper<::InboundProtocol>, - SendWrapper<::InboundProtocol>, + SendWrapper<::InboundProtocol>, + SendWrapper<::InboundProtocol>, >; type OutboundProtocol = EitherUpgrade< SendWrapper, @@ -177,58 +177,58 @@ where fn inject_dial_upgrade_error( &mut self, info: Self::OutboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { match (info, error) { - (EitherOutput::First(info), ProtocolsHandlerUpgrErr::Timer) => self + (EitherOutput::First(info), ConnectionHandlerUpgrErr::Timer) => self .proto1 - .inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer), - (EitherOutput::First(info), ProtocolsHandlerUpgrErr::Timeout) => self + .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer), + (EitherOutput::First(info), ConnectionHandlerUpgrErr::Timeout) => self .proto1 - .inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout), + .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout), ( EitherOutput::First(info), - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), ) => self.proto1.inject_dial_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), ), ( EitherOutput::First(info), - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(err))), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(err))), ) => self.proto1.inject_dial_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), ), ( EitherOutput::First(_), - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(_))), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(_))), ) => { panic!("Wrong API usage; the upgrade error doesn't match the outbound open info"); } - (EitherOutput::Second(info), ProtocolsHandlerUpgrErr::Timeout) => self + (EitherOutput::Second(info), ConnectionHandlerUpgrErr::Timeout) => self .proto2 - .inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout), - (EitherOutput::Second(info), ProtocolsHandlerUpgrErr::Timer) => self + .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout), + (EitherOutput::Second(info), ConnectionHandlerUpgrErr::Timer) => self .proto2 - .inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer), + .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer), ( EitherOutput::Second(info), - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), ) => self.proto2.inject_dial_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), ), ( EitherOutput::Second(info), - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(err))), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(err))), ) => self.proto2.inject_dial_upgrade_error( info, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), ), ( EitherOutput::Second(_), - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(_))), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(_))), ) => { panic!("Wrong API usage; the upgrade error doesn't match the outbound open info"); } @@ -238,36 +238,36 @@ where fn inject_listen_upgrade_error( &mut self, (i1, i2): Self::InboundOpenInfo, - error: ProtocolsHandlerUpgrErr<::Error>, + error: ConnectionHandlerUpgrErr<::Error>, ) { match error { - ProtocolsHandlerUpgrErr::Timer => { + ConnectionHandlerUpgrErr::Timer => { self.proto1 - .inject_listen_upgrade_error(i1, ProtocolsHandlerUpgrErr::Timer); + .inject_listen_upgrade_error(i1, ConnectionHandlerUpgrErr::Timer); self.proto2 - .inject_listen_upgrade_error(i2, ProtocolsHandlerUpgrErr::Timer) + .inject_listen_upgrade_error(i2, ConnectionHandlerUpgrErr::Timer) } - ProtocolsHandlerUpgrErr::Timeout => { + ConnectionHandlerUpgrErr::Timeout => { self.proto1 - .inject_listen_upgrade_error(i1, ProtocolsHandlerUpgrErr::Timeout); + .inject_listen_upgrade_error(i1, ConnectionHandlerUpgrErr::Timeout); self.proto2 - .inject_listen_upgrade_error(i2, ProtocolsHandlerUpgrErr::Timeout) + .inject_listen_upgrade_error(i2, ConnectionHandlerUpgrErr::Timeout) } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { self.proto1.inject_listen_upgrade_error( i1, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( NegotiationError::Failed, )), ); self.proto2.inject_listen_upgrade_error( i2, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( NegotiationError::Failed, )), ); } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select( NegotiationError::ProtocolError(e), )) => { let (e1, e2); @@ -293,23 +293,23 @@ where } self.proto1.inject_listen_upgrade_error( i1, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e1)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e1)), ); self.proto2.inject_listen_upgrade_error( i2, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e2)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e2)), ) } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { self.proto1.inject_listen_upgrade_error( i1, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ) } - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { self.proto2.inject_listen_upgrade_error( i2, - ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), + ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ) } } @@ -326,7 +326,7 @@ where &mut self, cx: &mut Context<'_>, ) -> Poll< - ProtocolsHandlerEvent< + ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, Self::OutEvent, @@ -334,14 +334,14 @@ where >, > { match self.proto1.poll(cx) { - Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(EitherOutput::First(event))); + Poll::Ready(ConnectionHandlerEvent::Custom(event)) => { + return Poll::Ready(ConnectionHandlerEvent::Custom(EitherOutput::First(event))); } - Poll::Ready(ProtocolsHandlerEvent::Close(event)) => { - return Poll::Ready(ProtocolsHandlerEvent::Close(EitherError::A(event))); + Poll::Ready(ConnectionHandlerEvent::Close(event)) => { + return Poll::Ready(ConnectionHandlerEvent::Close(EitherError::A(event))); } - Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }) => { - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }) => { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: protocol .map_upgrade(|u| EitherUpgrade::A(SendWrapper(u))) .map_info(EitherOutput::First), @@ -351,14 +351,14 @@ where }; match self.proto2.poll(cx) { - Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => { - return Poll::Ready(ProtocolsHandlerEvent::Custom(EitherOutput::Second(event))); + Poll::Ready(ConnectionHandlerEvent::Custom(event)) => { + return Poll::Ready(ConnectionHandlerEvent::Custom(EitherOutput::Second(event))); } - Poll::Ready(ProtocolsHandlerEvent::Close(event)) => { - return Poll::Ready(ProtocolsHandlerEvent::Close(EitherError::B(event))); + Poll::Ready(ConnectionHandlerEvent::Close(event)) => { + return Poll::Ready(ConnectionHandlerEvent::Close(EitherError::B(event))); } - Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }) => { - return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { + Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }) => { + return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol: protocol .map_upgrade(|u| EitherUpgrade::B(SendWrapper(u))) .map_info(EitherOutput::Second), diff --git a/swarm/src/lib.rs b/swarm/src/lib.rs index 462fabaf..c9e58ee0 100644 --- a/swarm/src/lib.rs +++ b/swarm/src/lib.rs @@ -48,7 +48,7 @@ //! //! # Protocols Handler //! -//! The [`ProtocolsHandler`] trait defines how each active connection to a +//! The [`ConnectionHandler`] trait defines how each active connection to a //! remote should behave: how to handle incoming substreams, which protocols //! are supported, when to open a new outbound substream, etc. //! @@ -61,7 +61,7 @@ mod upgrade; pub mod behaviour; pub mod dial_opts; -pub mod protocols_handler; +pub mod handler; pub use behaviour::{ CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, @@ -71,10 +71,10 @@ pub use connection::{ ConnectionCounters, ConnectionError, ConnectionLimit, ConnectionLimits, PendingConnectionError, PendingInboundConnectionError, PendingOutboundConnectionError, }; -pub use protocols_handler::{ - IntoProtocolsHandler, IntoProtocolsHandlerSelect, KeepAlive, OneShotHandler, - OneShotHandlerConfig, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerSelect, - ProtocolsHandlerUpgrErr, SubstreamProtocol, +pub use handler::{ + ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerSelect, ConnectionHandlerUpgrErr, + IntoConnectionHandler, IntoConnectionHandlerSelect, KeepAlive, OneShotHandler, + OneShotHandlerConfig, SubstreamProtocol, }; pub use registry::{AddAddressResult, AddressRecord, AddressScore}; @@ -115,22 +115,22 @@ pub type NegotiatedSubstream = Negotiated>; /// Event generated by the [`NetworkBehaviour`] that the swarm will report back. type TBehaviourOutEvent = ::OutEvent; -/// [`ProtocolsHandler`] of the [`NetworkBehaviour`] for all the protocols the [`NetworkBehaviour`] +/// [`ConnectionHandler`] of the [`NetworkBehaviour`] for all the protocols the [`NetworkBehaviour`] /// supports. -type THandler = ::ProtocolsHandler; +type THandler = ::ConnectionHandler; -/// Custom event that can be received by the [`ProtocolsHandler`] of the +/// Custom event that can be received by the [`ConnectionHandler`] of the /// [`NetworkBehaviour`]. type THandlerInEvent = - < as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent; + < as IntoConnectionHandler>::Handler as ConnectionHandler>::InEvent; -/// Custom event that can be produced by the [`ProtocolsHandler`] of the [`NetworkBehaviour`]. +/// Custom event that can be produced by the [`ConnectionHandler`] of the [`NetworkBehaviour`]. type THandlerOutEvent = - < as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent; + < as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent; -/// Custom error that can be produced by the [`ProtocolsHandler`] of the [`NetworkBehaviour`]. +/// Custom error that can be produced by the [`ConnectionHandler`] of the [`NetworkBehaviour`]. type THandlerErr = - < as IntoProtocolsHandler>::Handler as ProtocolsHandler>::Error; + < as IntoConnectionHandler>::Handler as ConnectionHandler>::Error; /// Event generated by the `Swarm`. #[derive(Debug)] @@ -370,7 +370,7 @@ where fn dial_with_handler( &mut self, swarm_dial_opts: DialOpts, - handler: ::ProtocolsHandler, + handler: ::ConnectionHandler, ) -> Result<(), DialError> { let (peer_id, addresses, dial_concurrency_factor_override, role_override) = match swarm_dial_opts.0 { @@ -604,11 +604,11 @@ where /// Returns `Ok(())` if there was one or more established connections to the peer. /// /// Note: Closing a connection via [`Swarm::disconnect_peer_id`] does - /// not inform the corresponding [`ProtocolsHandler`]. - /// Closing a connection via a [`ProtocolsHandler`] can be done either in a - /// collaborative manner across [`ProtocolsHandler`]s - /// with [`ProtocolsHandler::connection_keep_alive`] or directly with - /// [`ProtocolsHandlerEvent::Close`]. + /// not inform the corresponding [`ConnectionHandler`]. + /// Closing a connection via a [`ConnectionHandler`] can be done either in a + /// collaborative manner across [`ConnectionHandler`]s + /// with [`ConnectionHandler::connection_keep_alive`] or directly with + /// [`ConnectionHandlerEvent::Close`]. pub fn disconnect_peer_id(&mut self, peer_id: PeerId) -> Result<(), ()> { let was_connected = self.pool.is_connected(peer_id); self.pool.disconnect(peer_id); @@ -1120,8 +1120,8 @@ where TTrans: Transport, TTrans::Error: Send + 'static, TBehaviour: NetworkBehaviour, - THandler: IntoProtocolsHandler, - THandler::Handler: ProtocolsHandler< + THandler: IntoConnectionHandler, + THandler::Handler: ConnectionHandler< InEvent = THandlerInEvent, OutEvent = THandlerOutEvent, >, @@ -1253,7 +1253,7 @@ where } /// Configures the number of events from the [`NetworkBehaviour`] in - /// destination to the [`ProtocolsHandler`] that can be buffered before + /// destination to the [`ConnectionHandler`] that can be buffered before /// the [`Swarm`] has to wait. An individual buffer with this number of /// events exists for each individual connection. /// @@ -1266,14 +1266,14 @@ where self } - /// Configures the number of extra events from the [`ProtocolsHandler`] in + /// Configures the number of extra events from the [`ConnectionHandler`] in /// destination to the [`NetworkBehaviour`] that can be buffered before - /// the [`ProtocolsHandler`] has to go to sleep. + /// the [`ConnectionHandler`] has to go to sleep. /// - /// There exists a buffer of events received from [`ProtocolsHandler`]s + /// There exists a buffer of events received from [`ConnectionHandler`]s /// that the [`NetworkBehaviour`] has yet to process. This buffer is - /// shared between all instances of [`ProtocolsHandler`]. Each instance of - /// [`ProtocolsHandler`] is guaranteed one slot in this buffer, meaning + /// shared between all instances of [`ConnectionHandler`]. Each instance of + /// [`ConnectionHandler`] is guaranteed one slot in this buffer, meaning /// that delivering an event for the first time is guaranteed to be /// instantaneous. Any extra event delivery, however, must wait for that /// first event to be delivered or for an "extra slot" to be available. @@ -1284,7 +1284,7 @@ where /// /// The ideal value depends on the executor used, the CPU speed, the /// average number of connections, and the volume of events. If this value - /// is too low, then the [`ProtocolsHandler`]s will be sleeping more often + /// is too low, then the [`ConnectionHandler`]s will be sleeping more often /// than necessary. Increasing this value increases the overall memory /// usage, and more importantly the latency between the moment when an /// event is emitted and the moment when it is received by the @@ -1478,11 +1478,11 @@ impl Default for DummyBehaviour { } impl NetworkBehaviour for DummyBehaviour { - type ProtocolsHandler = protocols_handler::DummyProtocolsHandler; + type ConnectionHandler = handler::DummyConnectionHandler; type OutEvent = void::Void; - fn new_handler(&mut self) -> Self::ProtocolsHandler { - protocols_handler::DummyProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { + handler::DummyConnectionHandler { keep_alive: self.keep_alive, } } @@ -1491,7 +1491,7 @@ impl NetworkBehaviour for DummyBehaviour { &mut self, _: PeerId, _: ConnectionId, - event: ::OutEvent, + event: ::OutEvent, ) { void::unreachable(event) } @@ -1500,7 +1500,7 @@ impl NetworkBehaviour for DummyBehaviour { &mut self, _: &mut Context<'_>, _: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { Poll::Pending } } @@ -1530,7 +1530,7 @@ impl NetworkInfo { #[cfg(test)] mod tests { use super::*; - use crate::protocols_handler::DummyProtocolsHandler; + use crate::handler::DummyConnectionHandler; use crate::test::{CallTraceBehaviour, MockBehaviour}; use futures::executor::block_on; use futures::future::poll_fn; @@ -1557,7 +1557,7 @@ mod tests { handler_proto: T, ) -> SwarmBuilder>> where - T: ProtocolsHandler + Clone, + T: ConnectionHandler + Clone, T::OutEvent: Clone, O: Send + 'static, { @@ -1581,7 +1581,7 @@ mod tests { ) -> bool where TBehaviour: NetworkBehaviour, - <::Handler as ProtocolsHandler>::OutEvent: Clone, + <::Handler as ConnectionHandler>::OutEvent: Clone, { [swarm1, swarm2] .iter() @@ -1595,7 +1595,7 @@ mod tests { ) -> bool where TBehaviour: NetworkBehaviour, - <::Handler as ProtocolsHandler>::OutEvent: Clone + <::Handler as ConnectionHandler>::OutEvent: Clone { [swarm1, swarm2] .iter() @@ -1621,7 +1621,7 @@ mod tests { fn test_connect_disconnect_ban() { // Since the test does not try to open any substreams, we can // use the dummy protocols handler. - let handler_proto = DummyProtocolsHandler { + let handler_proto = DummyConnectionHandler { keep_alive: KeepAlive::Yes, }; @@ -1742,7 +1742,7 @@ mod tests { fn test_swarm_disconnect() { // Since the test does not try to open any substreams, we can // use the dummy protocols handler. - let handler_proto = DummyProtocolsHandler { + let handler_proto = DummyConnectionHandler { keep_alive: KeepAlive::Yes, }; @@ -1811,7 +1811,7 @@ mod tests { fn test_behaviour_disconnect_all() { // Since the test does not try to open any substreams, we can // use the dummy protocols handler. - let handler_proto = DummyProtocolsHandler { + let handler_proto = DummyConnectionHandler { keep_alive: KeepAlive::Yes, }; @@ -1883,7 +1883,7 @@ mod tests { fn test_behaviour_disconnect_one() { // Since the test does not try to open any substreams, we can // use the dummy protocols handler. - let handler_proto = DummyProtocolsHandler { + let handler_proto = DummyConnectionHandler { keep_alive: KeepAlive::Yes, }; @@ -1970,7 +1970,7 @@ mod tests { fn prop(concurrency_factor: DialConcurrencyFactor) { block_on(async { - let mut swarm = new_test_swarm::<_, ()>(DummyProtocolsHandler { + let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler { keep_alive: KeepAlive::Yes, }) .dial_concurrency_factor(concurrency_factor.0) @@ -2039,7 +2039,7 @@ mod tests { let outgoing_limit = rand::thread_rng().gen_range(1, 10); let limits = ConnectionLimits::default().with_max_pending_outgoing(Some(outgoing_limit)); - let mut network = new_test_swarm::<_, ()>(DummyProtocolsHandler { + let mut network = new_test_swarm::<_, ()>(DummyConnectionHandler { keep_alive: KeepAlive::Yes, }) .connection_limits(limits) @@ -2102,12 +2102,12 @@ mod tests { fn prop(limit: Limit) { let limit = limit.0; - let mut network1 = new_test_swarm::<_, ()>(DummyProtocolsHandler { + let mut network1 = new_test_swarm::<_, ()>(DummyConnectionHandler { keep_alive: KeepAlive::Yes, }) .connection_limits(limits(limit)) .build(); - let mut network2 = new_test_swarm::<_, ()>(DummyProtocolsHandler { + let mut network2 = new_test_swarm::<_, ()>(DummyConnectionHandler { keep_alive: KeepAlive::Yes, }) .connection_limits(limits(limit)) @@ -2216,8 +2216,8 @@ mod tests { // Checks whether dialing an address containing the wrong peer id raises an error // for the expected peer id instead of the obtained peer id. - let mut swarm1 = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); - let mut swarm2 = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); + let mut swarm1 = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); + let mut swarm2 = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); swarm1.listen_on("/memory/0".parse().unwrap()).unwrap(); @@ -2276,7 +2276,7 @@ mod tests { // // The last two can happen in any order. - let mut swarm = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); + let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); swarm.listen_on("/memory/0".parse().unwrap()).unwrap(); let local_address = @@ -2334,7 +2334,7 @@ mod tests { fn dial_self_by_id() { // Trying to dial self by passing the same `PeerId` shouldn't even be possible in the first // place. - let swarm = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); + let swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); let peer_id = *swarm.local_peer_id(); assert!(!swarm.is_connected(&peer_id)); } @@ -2345,7 +2345,7 @@ mod tests { let target = PeerId::random(); - let mut swarm = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); + let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); let mut addresses = Vec::new(); for _ in 0..3 { @@ -2399,8 +2399,8 @@ mod tests { fn aborting_pending_connection_surfaces_error() { let _ = env_logger::try_init(); - let mut dialer = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); - let mut listener = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); + let mut dialer = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); + let mut listener = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build(); let listener_peer_id = *listener.local_peer_id(); listener.listen_on(multiaddr![Memory(0u64)]).unwrap(); diff --git a/swarm/src/test.rs b/swarm/src/test.rs index 25f6b47a..fd5b98df 100644 --- a/swarm/src/test.rs +++ b/swarm/src/test.rs @@ -19,8 +19,8 @@ // DEALINGS IN THE SOFTWARE. use crate::{ - DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, - ProtocolsHandler, + ConnectionHandler, DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, + PollParameters, }; use libp2p_core::{ connection::{ConnectionId, ListenerId}, @@ -35,7 +35,7 @@ use std::task::{Context, Poll}; /// any further state. pub struct MockBehaviour where - THandler: ProtocolsHandler, + THandler: ConnectionHandler, { /// The prototype protocols handler that is cloned for every /// invocation of `new_handler`. @@ -50,7 +50,7 @@ where impl MockBehaviour where - THandler: ProtocolsHandler, + THandler: ConnectionHandler, { pub fn new(handler_proto: THandler) -> Self { MockBehaviour { @@ -63,14 +63,14 @@ where impl NetworkBehaviour for MockBehaviour where - THandler: ProtocolsHandler + Clone, + THandler: ConnectionHandler + Clone, THandler::OutEvent: Clone, TOutEvent: Send + 'static, { - type ProtocolsHandler = THandler; + type ConnectionHandler = THandler; type OutEvent = TOutEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { self.handler_proto.clone() } @@ -84,7 +84,7 @@ where &mut self, _: &mut Context, _: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { self.next_action.take().map_or(Poll::Pending, Poll::Ready) } } @@ -104,7 +104,7 @@ where pub inject_event: Vec<( PeerId, ConnectionId, - <::Handler as ProtocolsHandler>::OutEvent, + <::Handler as ConnectionHandler>::OutEvent, )>, pub inject_dial_failure: Vec>, pub inject_new_listener: Vec, @@ -211,13 +211,13 @@ where impl NetworkBehaviour for CallTraceBehaviour where TInner: NetworkBehaviour, - <::Handler as ProtocolsHandler>::OutEvent: + <::Handler as ConnectionHandler>::OutEvent: Clone, { - type ProtocolsHandler = TInner::ProtocolsHandler; + type ConnectionHandler = TInner::ConnectionHandler; type OutEvent = TInner::OutEvent; - fn new_handler(&mut self) -> Self::ProtocolsHandler { + fn new_handler(&mut self) -> Self::ConnectionHandler { self.inner.new_handler() } @@ -276,7 +276,7 @@ where p: &PeerId, c: &ConnectionId, e: &ConnectedPoint, - handler: ::Handler, + handler: ::Handler, remaining_established: usize, ) { let mut other_closed_connections = self @@ -323,7 +323,7 @@ where &mut self, p: PeerId, c: ConnectionId, - e: <::Handler as ProtocolsHandler>::OutEvent, + e: <::Handler as ConnectionHandler>::OutEvent, ) { assert!( self.inject_connection_established @@ -346,7 +346,7 @@ where fn inject_dial_failure( &mut self, p: Option, - handler: Self::ProtocolsHandler, + handler: Self::ConnectionHandler, error: &DialError, ) { self.inject_dial_failure.push(p); @@ -392,7 +392,7 @@ where &mut self, cx: &mut Context, args: &mut impl PollParameters, - ) -> Poll> { + ) -> Poll> { self.poll += 1; self.inner.poll(cx, args) }