swarm/: Rename ProtocolsHandler to ConnectionHandler (#2527)

A `ProtocolsHandler`, now `ConnectionHandler`, handels a connection, not
a protocol. Thus the name `CONNECTIONHandler` is more appropriate.

Next to the rename of `ProtocolsHandler` this commit renames the `mod
protocols_handler` to `mod handler`. Finally all combinators (e.g.
`ProtocolsHandlerSelect`) are renamed appropriately.
This commit is contained in:
Max Inden 2022-02-21 13:32:24 +01:00 committed by GitHub
parent 6511e6ba45
commit fd2be38faf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
50 changed files with 924 additions and 910 deletions

View File

@ -43,7 +43,7 @@ The main components of this repository are structured as follows:
Multiplexing protocols are (mandatory) `Transport` upgrades. Multiplexing protocols are (mandatory) `Transport` upgrades.
* `swarm/`: The implementation of `libp2p-swarm` building on `libp2p-core` * `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/`). to implement application protocols (see `protocols/`).
* `protocols/`: Implementations of application protocols based on the * `protocols/`: Implementations of application protocols based on the

View File

@ -53,7 +53,7 @@
//! //!
//! > **Note**: You can use the `apply_inbound` or `apply_outbound` methods to try upgrade a //! > **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 //! 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. //! need to use these methods.
//! //!

View File

@ -217,7 +217,7 @@ mod network {
ProtocolSupport, RequestId, RequestResponse, RequestResponseCodec, RequestResponseEvent, ProtocolSupport, RequestId, RequestResponse, RequestResponseCodec, RequestResponseEvent,
RequestResponseMessage, ResponseChannel, RequestResponseMessage, ResponseChannel,
}; };
use libp2p::swarm::{ProtocolsHandlerUpgrErr, SwarmBuilder, SwarmEvent}; use libp2p::swarm::{ConnectionHandlerUpgrErr, SwarmBuilder, SwarmEvent};
use libp2p::{NetworkBehaviour, Swarm}; use libp2p::{NetworkBehaviour, Swarm};
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::iter; use std::iter;
@ -404,7 +404,7 @@ mod network {
&mut self, &mut self,
event: SwarmEvent< event: SwarmEvent<
ComposedEvent, ComposedEvent,
EitherError<ProtocolsHandlerUpgrErr<io::Error>, io::Error>, EitherError<ConnectionHandlerUpgrErr<io::Error>, io::Error>,
>, >,
) { ) {
match event { match event {

View File

@ -37,7 +37,7 @@ use libp2p_request_response::{
RequestResponseConfig, RequestResponseEvent, RequestResponseMessage, ResponseChannel, RequestResponseConfig, RequestResponseEvent, RequestResponseMessage, ResponseChannel,
}; };
use libp2p_swarm::{ use libp2p_swarm::{
DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters,
}; };
use std::{ use std::{
collections::{HashMap, VecDeque}, collections::{HashMap, VecDeque},
@ -294,7 +294,7 @@ impl Behaviour {
} }
impl NetworkBehaviour for Behaviour { impl NetworkBehaviour for Behaviour {
type ProtocolsHandler = <RequestResponse<AutoNatCodec> as NetworkBehaviour>::ProtocolsHandler; type ConnectionHandler = <RequestResponse<AutoNatCodec> as NetworkBehaviour>::ConnectionHandler;
type OutEvent = Event; type OutEvent = Event;
fn inject_connection_established( fn inject_connection_established(
@ -347,7 +347,7 @@ impl NetworkBehaviour for Behaviour {
peer: &PeerId, peer: &PeerId,
conn: &ConnectionId, conn: &ConnectionId,
endpoint: &ConnectedPoint, endpoint: &ConnectedPoint,
handler: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, handler: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
self.inner self.inner
@ -363,7 +363,7 @@ impl NetworkBehaviour for Behaviour {
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
peer: Option<PeerId>, peer: Option<PeerId>,
handler: Self::ProtocolsHandler, handler: Self::ConnectionHandler,
error: &DialError, error: &DialError,
) { ) {
self.inner.inject_dial_failure(peer, handler, error); 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() self.inner.new_handler()
} }
@ -480,7 +480,7 @@ impl NetworkBehaviour for Behaviour {
&mut self, &mut self,
local_addr: &Multiaddr, local_addr: &Multiaddr,
send_back_addr: &Multiaddr, send_back_addr: &Multiaddr,
handler: Self::ProtocolsHandler, handler: Self::ConnectionHandler,
) { ) {
self.inner self.inner
.inject_listen_failure(local_addr, send_back_addr, handler) .inject_listen_failure(local_addr, send_back_addr, handler)
@ -501,7 +501,7 @@ impl NetworkBehaviour for Behaviour {
type Action = NetworkBehaviourAction< type Action = NetworkBehaviourAction<
<Behaviour as NetworkBehaviour>::OutEvent, <Behaviour as NetworkBehaviour>::OutEvent,
<Behaviour as NetworkBehaviour>::ProtocolsHandler, <Behaviour as NetworkBehaviour>::ConnectionHandler,
>; >;
// Trait implemented for `AsClient` as `AsServer` to handle events from the inner [`RequestResponse`] Protocol. // Trait implemented for `AsClient` as `AsServer` to handle events from the inner [`RequestResponse`] Protocol.

View File

@ -28,8 +28,8 @@ use libp2p_core::multiaddr::Protocol;
use libp2p_core::{Multiaddr, PeerId}; use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::dial_opts::{self, DialOpts}; use libp2p_swarm::dial_opts::{self, DialOpts};
use libp2p_swarm::{ use libp2p_swarm::{
DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, ConnectionHandler, ConnectionHandlerUpgrErr, DialError, IntoConnectionHandler,
PollParameters, ProtocolsHandler, ProtocolsHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
}; };
use std::collections::{HashMap, HashSet, VecDeque}; use std::collections::{HashMap, HashSet, VecDeque};
use std::task::{Context, Poll}; use std::task::{Context, Poll};
@ -62,7 +62,7 @@ pub enum UpgradeError {
#[error("Failed to dial peer.")] #[error("Failed to dial peer.")]
Dial, Dial,
#[error("Failed to establish substream: {0}.")] #[error("Failed to establish substream: {0}.")]
Handler(ProtocolsHandlerUpgrErr<void::Void>), Handler(ConnectionHandlerUpgrErr<void::Void>),
} }
pub struct Behaviour { pub struct Behaviour {
@ -83,10 +83,10 @@ impl Behaviour {
} }
impl NetworkBehaviour for Behaviour { impl NetworkBehaviour for Behaviour {
type ProtocolsHandler = handler::Prototype; type ConnectionHandler = handler::Prototype;
type OutEvent = Event; type OutEvent = Event;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
handler::Prototype::UnknownConnection handler::Prototype::UnknownConnection
} }
@ -142,7 +142,7 @@ impl NetworkBehaviour for Behaviour {
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
peer_id: Option<PeerId>, peer_id: Option<PeerId>,
handler: Self::ProtocolsHandler, handler: Self::ConnectionHandler,
_error: &DialError, _error: &DialError,
) { ) {
match handler { match handler {
@ -187,7 +187,7 @@ impl NetworkBehaviour for Behaviour {
peer_id: &PeerId, peer_id: &PeerId,
connection_id: &ConnectionId, connection_id: &ConnectionId,
connected_point: &ConnectedPoint, connected_point: &ConnectedPoint,
_handler: <<Self as NetworkBehaviour>::ProtocolsHandler as IntoProtocolsHandler>::Handler, _handler: <<Self as NetworkBehaviour>::ConnectionHandler as IntoConnectionHandler>::Handler,
_remaining_established: usize, _remaining_established: usize,
) { ) {
if !connected_point.is_relayed() { if !connected_point.is_relayed() {
@ -209,7 +209,7 @@ impl NetworkBehaviour for Behaviour {
&mut self, &mut self,
event_source: PeerId, event_source: PeerId,
connection: ConnectionId, connection: ConnectionId,
handler_event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent, handler_event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
) { ) {
match handler_event { match handler_event {
Either::Left(handler::relayed::Event::InboundConnectRequest { Either::Left(handler::relayed::Event::InboundConnectRequest {
@ -313,7 +313,7 @@ impl NetworkBehaviour for Behaviour {
&mut self, &mut self,
_cx: &mut Context<'_>, _cx: &mut Context<'_>,
poll_parameters: &mut impl PollParameters, poll_parameters: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(action) = self.queued_actions.pop_front() { if let Some(action) = self.queued_actions.pop_front() {
return Poll::Ready(action.build(poll_parameters)); return Poll::Ready(action.build(poll_parameters));
} }

View File

@ -23,9 +23,9 @@ use either::Either;
use libp2p_core::connection::ConnectionId; use libp2p_core::connection::ConnectionId;
use libp2p_core::upgrade::{self, DeniedUpgrade}; use libp2p_core::upgrade::{self, DeniedUpgrade};
use libp2p_core::{ConnectedPoint, PeerId}; use libp2p_core::{ConnectedPoint, PeerId};
use libp2p_swarm::protocols_handler::DummyProtocolsHandler; use libp2p_swarm::handler::DummyConnectionHandler;
use libp2p_swarm::protocols_handler::SendWrapper; use libp2p_swarm::handler::SendWrapper;
use libp2p_swarm::{IntoProtocolsHandler, ProtocolsHandler}; use libp2p_swarm::{ConnectionHandler, IntoConnectionHandler};
pub mod direct; pub mod direct;
pub mod relayed; pub mod relayed;
@ -43,8 +43,8 @@ pub enum Role {
Listener, Listener,
} }
impl IntoProtocolsHandler for Prototype { impl IntoConnectionHandler for Prototype {
type Handler = Either<relayed::Handler, Either<direct::Handler, DummyProtocolsHandler>>; type Handler = Either<relayed::Handler, Either<direct::Handler, DummyConnectionHandler>>;
fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
match self { match self {
@ -52,7 +52,7 @@ impl IntoProtocolsHandler for Prototype {
if endpoint.is_relayed() { if endpoint.is_relayed() {
Either::Left(relayed::Handler::new(endpoint.clone())) Either::Left(relayed::Handler::new(endpoint.clone()))
} else { } else {
Either::Right(Either::Right(DummyProtocolsHandler::default())) Either::Right(Either::Right(DummyConnectionHandler::default()))
} }
} }
Self::DirectConnection { Self::DirectConnection {
@ -68,7 +68,7 @@ impl IntoProtocolsHandler for Prototype {
} }
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
match self { match self {
Prototype::UnknownConnection => upgrade::EitherUpgrade::A(SendWrapper( Prototype::UnknownConnection => upgrade::EitherUpgrade::A(SendWrapper(
upgrade::EitherUpgrade::A(protocol::inbound::Upgrade {}), upgrade::EitherUpgrade::A(protocol::inbound::Upgrade {}),

View File

@ -18,13 +18,13 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // 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::connection::ConnectionId;
use libp2p_core::upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade}; use libp2p_core::upgrade::{DeniedUpgrade, InboundUpgrade, OutboundUpgrade};
use libp2p_swarm::{ use libp2p_swarm::{
KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
ProtocolsHandlerUpgrErr, SubstreamProtocol, NegotiatedSubstream, SubstreamProtocol,
}; };
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use void::Void; use void::Void;
@ -48,10 +48,10 @@ impl Handler {
} }
} }
impl ProtocolsHandler for Handler { impl ConnectionHandler for Handler {
type InEvent = void::Void; type InEvent = void::Void;
type OutEvent = Event; type OutEvent = Event;
type Error = ProtocolsHandlerUpgrErr<std::io::Error>; type Error = ConnectionHandlerUpgrErr<std::io::Error>;
type InboundProtocol = DeniedUpgrade; type InboundProtocol = DeniedUpgrade;
type OutboundProtocol = DeniedUpgrade; type OutboundProtocol = DeniedUpgrade;
type OutboundOpenInfo = Void; type OutboundOpenInfo = Void;
@ -80,7 +80,7 @@ impl ProtocolsHandler for Handler {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
_: Self::OutboundOpenInfo, _: Self::OutboundOpenInfo,
_: ProtocolsHandlerUpgrErr< _: ConnectionHandlerUpgrErr<
<Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error, <Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error,
>, >,
) { ) {
@ -94,7 +94,7 @@ impl ProtocolsHandler for Handler {
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -103,7 +103,7 @@ impl ProtocolsHandler for Handler {
> { > {
if !self.reported { if !self.reported {
self.reported = true; self.reported = true;
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::DirectConnectionUpgradeSucceeded { Event::DirectConnectionUpgradeSucceeded {
relayed_connection_id: self.relayed_connection_id, relayed_connection_id: self.relayed_connection_id,
}, },

View File

@ -18,7 +18,7 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // 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 crate::protocol;
use futures::future::{BoxFuture, FutureExt}; use futures::future::{BoxFuture, FutureExt};
@ -28,10 +28,10 @@ use libp2p_core::either::{EitherError, EitherOutput};
use libp2p_core::multiaddr::Multiaddr; use libp2p_core::multiaddr::Multiaddr;
use libp2p_core::upgrade::{self, DeniedUpgrade, NegotiationError, UpgradeError}; use libp2p_core::upgrade::{self, DeniedUpgrade, NegotiationError, UpgradeError};
use libp2p_core::ConnectedPoint; use libp2p_core::ConnectedPoint;
use libp2p_swarm::protocols_handler::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend};
use libp2p_swarm::{ use libp2p_swarm::{
KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
ProtocolsHandlerUpgrErr, SubstreamProtocol, NegotiatedSubstream, SubstreamProtocol,
}; };
use std::collections::VecDeque; use std::collections::VecDeque;
use std::fmt; use std::fmt;
@ -81,11 +81,11 @@ pub enum Event {
remote_addr: Multiaddr, remote_addr: Multiaddr,
}, },
InboundNegotiationFailed { InboundNegotiationFailed {
error: ProtocolsHandlerUpgrErr<void::Void>, error: ConnectionHandlerUpgrErr<void::Void>,
}, },
InboundConnectNegotiated(Vec<Multiaddr>), InboundConnectNegotiated(Vec<Multiaddr>),
OutboundNegotiationFailed { OutboundNegotiationFailed {
error: ProtocolsHandlerUpgrErr<void::Void>, error: ConnectionHandlerUpgrErr<void::Void>,
}, },
OutboundConnectNegotiated { OutboundConnectNegotiated {
remote_addrs: Vec<Multiaddr>, remote_addrs: Vec<Multiaddr>,
@ -131,17 +131,17 @@ pub struct Handler {
endpoint: ConnectedPoint, endpoint: ConnectedPoint,
/// A pending fatal error that results in the connection being closed. /// A pending fatal error that results in the connection being closed.
pending_error: Option< pending_error: Option<
ProtocolsHandlerUpgrErr< ConnectionHandlerUpgrErr<
EitherError<protocol::inbound::UpgradeError, protocol::outbound::UpgradeError>, EitherError<protocol::inbound::UpgradeError, protocol::outbound::UpgradeError>,
>, >,
>, >,
/// Queue of events to return when polled. /// Queue of events to return when polled.
queued_events: VecDeque< queued_events: VecDeque<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
<Self as ProtocolsHandler>::OutboundProtocol, <Self as ConnectionHandler>::OutboundProtocol,
<Self as ProtocolsHandler>::OutboundOpenInfo, <Self as ConnectionHandler>::OutboundOpenInfo,
<Self as ProtocolsHandler>::OutEvent, <Self as ConnectionHandler>::OutEvent,
<Self as ProtocolsHandler>::Error, <Self as ConnectionHandler>::Error,
>, >,
>, >,
/// Inbound connects, accepted by the behaviour, pending completion. /// 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 InEvent = Command;
type OutEvent = Event; type OutEvent = Event;
type Error = ProtocolsHandlerUpgrErr< type Error = ConnectionHandlerUpgrErr<
EitherError<protocol::inbound::UpgradeError, protocol::outbound::UpgradeError>, EitherError<protocol::inbound::UpgradeError, protocol::outbound::UpgradeError>,
>; >;
type InboundProtocol = upgrade::EitherUpgrade<protocol::inbound::Upgrade, DeniedUpgrade>; type InboundProtocol = upgrade::EitherUpgrade<protocol::inbound::Upgrade, DeniedUpgrade>;
@ -199,9 +199,9 @@ impl ProtocolsHandler for Handler {
EitherOutput::First(inbound_connect) => { EitherOutput::First(inbound_connect) => {
let remote_addr = match &self.endpoint { let remote_addr = match &self.endpoint {
ConnectedPoint::Dialer { address, role_override: _ } => address.clone(), ConnectedPoint::Dialer { address, role_override: _ } => address.clone(),
ConnectedPoint::Listener { ..} => unreachable!("`<Handler as ProtocolsHandler>::listen_protocol` denies all incoming substreams as a listener."), ConnectedPoint::Listener { ..} => unreachable!("`<Handler as ConnectionHandler>::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 { Event::InboundConnectRequest {
inbound_connect, inbound_connect,
remote_addr, remote_addr,
@ -224,7 +224,7 @@ impl ProtocolsHandler for Handler {
self.endpoint.is_listener(), self.endpoint.is_listener(),
"A connection dialer never initiates a connection upgrade." "A connection dialer never initiates a connection upgrade."
); );
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::OutboundConnectNegotiated { Event::OutboundConnectNegotiated {
remote_addrs: obs_addrs, remote_addrs: obs_addrs,
attempt, attempt,
@ -236,7 +236,7 @@ impl ProtocolsHandler for Handler {
match event { match event {
Command::Connect { obs_addrs, attempt } => { Command::Connect { obs_addrs, attempt } => {
self.queued_events self.queued_events
.push_back(ProtocolsHandlerEvent::OutboundSubstreamRequest { .push_back(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new( protocol: SubstreamProtocol::new(
protocol::outbound::Upgrade::new(obs_addrs), protocol::outbound::Upgrade::new(obs_addrs),
attempt, attempt,
@ -259,31 +259,31 @@ impl ProtocolsHandler for Handler {
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
_: Self::InboundOpenInfo, _: Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
match error { match error {
ProtocolsHandlerUpgrErr::Timeout => { ConnectionHandlerUpgrErr::Timeout => {
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::InboundNegotiationFailed { Event::InboundNegotiationFailed {
error: ProtocolsHandlerUpgrErr::Timeout, error: ConnectionHandlerUpgrErr::Timeout,
}, },
)); ));
} }
ProtocolsHandlerUpgrErr::Timer => { ConnectionHandlerUpgrErr::Timer => {
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::InboundNegotiationFailed { 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. // The remote merely doesn't support the DCUtR protocol.
// This is no reason to close the connection, which may // This is no reason to close the connection, which may
// successfully communicate with other protocols already. // successfully communicate with other protocols already.
self.keep_alive = KeepAlive::No; self.keep_alive = KeepAlive::No;
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::InboundNegotiationFailed { Event::InboundNegotiationFailed {
error: ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(
NegotiationError::Failed, NegotiationError::Failed,
)), )),
}, },
@ -305,25 +305,25 @@ impl ProtocolsHandler for Handler {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
_open_info: Self::OutboundOpenInfo, _open_info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
self.keep_alive = KeepAlive::No; self.keep_alive = KeepAlive::No;
match error { match error {
ProtocolsHandlerUpgrErr::Timeout => { ConnectionHandlerUpgrErr::Timeout => {
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::OutboundNegotiationFailed { 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. // The remote merely doesn't support the DCUtR protocol.
// This is no reason to close the connection, which may // This is no reason to close the connection, which may
// successfully communicate with other protocols already. // successfully communicate with other protocols already.
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::OutboundNegotiationFailed { Event::OutboundNegotiationFailed {
error: ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(
NegotiationError::Failed, NegotiationError::Failed,
)), )),
}, },
@ -346,7 +346,7 @@ impl ProtocolsHandler for Handler {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -356,7 +356,7 @@ impl ProtocolsHandler for Handler {
// Check for a pending (fatal) error. // Check for a pending (fatal) error.
if let Some(err) = self.pending_error.take() { if let Some(err) = self.pending_error.take() {
// The handler will not be polled again by the `Swarm`. // 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. // Return queued events.
@ -367,13 +367,13 @@ impl ProtocolsHandler for Handler {
while let Poll::Ready(Some(result)) = self.inbound_connects.poll_next_unpin(cx) { while let Poll::Ready(Some(result)) = self.inbound_connects.poll_next_unpin(cx) {
match result { match result {
Ok(addresses) => { Ok(addresses) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::InboundConnectNegotiated(addresses), Event::InboundConnectNegotiated(addresses),
)); ));
} }
Err(e) => { Err(e) => {
return Poll::Ready(ProtocolsHandlerEvent::Close( return Poll::Ready(ConnectionHandlerEvent::Close(
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))),
)) ))
} }
} }

View File

@ -281,10 +281,10 @@ impl Floodsub {
} }
impl NetworkBehaviour for Floodsub { impl NetworkBehaviour for Floodsub {
type ProtocolsHandler = OneShotHandler<FloodsubProtocol, FloodsubRpc, InnerMessage>; type ConnectionHandler = OneShotHandler<FloodsubProtocol, FloodsubRpc, InnerMessage>;
type OutEvent = FloodsubEvent; type OutEvent = FloodsubEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
Default::default() Default::default()
} }
@ -327,7 +327,7 @@ impl NetworkBehaviour for Floodsub {
id: &PeerId, id: &PeerId,
_: &ConnectionId, _: &ConnectionId,
_: &ConnectedPoint, _: &ConnectedPoint,
_: Self::ProtocolsHandler, _: Self::ConnectionHandler,
remaining_established: usize, remaining_established: usize,
) { ) {
if remaining_established > 0 { if remaining_established > 0 {
@ -474,7 +474,7 @@ impl NetworkBehaviour for Floodsub {
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(event) = self.events.pop_front() { if let Some(event) = self.events.pop_front() {
return Poll::Ready(event); return Poll::Ready(event);
} }

View File

@ -42,7 +42,7 @@ use libp2p_core::{
}; };
use libp2p_swarm::{ use libp2p_swarm::{
dial_opts::{self, DialOpts}, dial_opts::{self, DialOpts},
IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
}; };
use wasm_timer::Instant; use wasm_timer::Instant;
@ -3051,10 +3051,10 @@ where
C: Send + 'static + DataTransform, C: Send + 'static + DataTransform,
F: Send + 'static + TopicSubscriptionFilter, F: Send + 'static + TopicSubscriptionFilter,
{ {
type ProtocolsHandler = GossipsubHandler; type ConnectionHandler = GossipsubHandler;
type OutEvent = GossipsubEvent; type OutEvent = GossipsubEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
GossipsubHandler::new( GossipsubHandler::new(
self.config.protocol_id_prefix().clone(), self.config.protocol_id_prefix().clone(),
self.config.max_transmit_size(), self.config.max_transmit_size(),
@ -3156,7 +3156,7 @@ where
peer_id: &PeerId, peer_id: &PeerId,
connection_id: &ConnectionId, connection_id: &ConnectionId,
endpoint: &ConnectedPoint, endpoint: &ConnectedPoint,
_: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, _: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
// Remove IP from peer scoring system // Remove IP from peer scoring system
@ -3443,7 +3443,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(event) = self.events.pop_front() { if let Some(event) = self.events.pop_front() {
return Poll::Ready(event.map_in(|e: Arc<GossipsubHandlerIn>| { return Poll::Ready(event.map_in(|e: Arc<GossipsubHandlerIn>| {
// clone send event reference if others references are present // clone send event reference if others references are present

View File

@ -27,8 +27,9 @@ use futures::prelude::*;
use futures::StreamExt; use futures::StreamExt;
use instant::Instant; use instant::Instant;
use libp2p_core::upgrade::{InboundUpgrade, NegotiationError, OutboundUpgrade, UpgradeError}; use libp2p_core::upgrade::{InboundUpgrade, NegotiationError, OutboundUpgrade, UpgradeError};
use libp2p_swarm::protocols_handler::{ use libp2p_swarm::handler::{
KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
SubstreamProtocol,
}; };
use libp2p_swarm::NegotiatedSubstream; use libp2p_swarm::NegotiatedSubstream;
use log::{error, trace, warn}; use log::{error, trace, warn};
@ -123,7 +124,7 @@ pub struct GossipsubHandler {
idle_timeout: Duration, idle_timeout: Duration,
/// Collection of errors from attempting an upgrade. /// Collection of errors from attempting an upgrade.
upgrade_errors: VecDeque<ProtocolsHandlerUpgrErr<GossipsubHandlerError>>, upgrade_errors: VecDeque<ConnectionHandlerUpgrErr<GossipsubHandlerError>>,
/// Flag determining whether to maintain the connection to the peer. /// Flag determining whether to maintain the connection to the peer.
keep_alive: KeepAlive, keep_alive: KeepAlive,
@ -196,7 +197,7 @@ impl GossipsubHandler {
} }
} }
impl ProtocolsHandler for GossipsubHandler { impl ConnectionHandler for GossipsubHandler {
type InEvent = GossipsubHandlerIn; type InEvent = GossipsubHandlerIn;
type OutEvent = HandlerEvent; type OutEvent = HandlerEvent;
type Error = GossipsubHandlerError; type Error = GossipsubHandlerError;
@ -285,7 +286,7 @@ impl ProtocolsHandler for GossipsubHandler {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
_: Self::OutboundOpenInfo, _: Self::OutboundOpenInfo,
e: ProtocolsHandlerUpgrErr< e: ConnectionHandlerUpgrErr<
<Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error, <Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error,
>, >,
) { ) {
@ -302,7 +303,7 @@ impl ProtocolsHandler for GossipsubHandler {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -313,12 +314,12 @@ impl ProtocolsHandler for GossipsubHandler {
if let Some(error) = self.upgrade_errors.pop_front() { if let Some(error) = self.upgrade_errors.pop_front() {
let reported_error = match error { let reported_error = match error {
// Timeout errors get mapped to NegotiationTimeout and we close the connection. // Timeout errors get mapped to NegotiationTimeout and we close the connection.
ProtocolsHandlerUpgrErr::Timeout | ProtocolsHandlerUpgrErr::Timer => { ConnectionHandlerUpgrErr::Timeout | ConnectionHandlerUpgrErr::Timer => {
Some(GossipsubHandlerError::NegotiationTimeout) Some(GossipsubHandlerError::NegotiationTimeout)
} }
// There was an error post negotiation, close the connection. // There was an error post negotiation, close the connection.
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)) => Some(e), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)) => Some(e),
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(negotiation_error)) => { ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(negotiation_error)) => {
match negotiation_error { match negotiation_error {
NegotiationError::Failed => { NegotiationError::Failed => {
// The protocol is not supported // The protocol is not supported
@ -329,7 +330,7 @@ impl ProtocolsHandler for GossipsubHandler {
self.inbound_substream = None; self.inbound_substream = None;
self.outbound_substream = None; self.outbound_substream = None;
self.keep_alive = KeepAlive::No; self.keep_alive = KeepAlive::No;
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
HandlerEvent::PeerKind(PeerKind::NotSupported), HandlerEvent::PeerKind(PeerKind::NotSupported),
)); ));
} else { } else {
@ -345,14 +346,14 @@ impl ProtocolsHandler for GossipsubHandler {
// If there was a fatal error, close the connection. // If there was a fatal error, close the connection.
if let Some(error) = reported_error { if let Some(error) = reported_error {
return Poll::Ready(ProtocolsHandlerEvent::Close(error)); return Poll::Ready(ConnectionHandlerEvent::Close(error));
} }
} }
if !self.peer_kind_sent { if !self.peer_kind_sent {
if let Some(peer_kind) = self.peer_kind.as_ref() { if let Some(peer_kind) = self.peer_kind.as_ref() {
self.peer_kind_sent = true; self.peer_kind_sent = true;
return Poll::Ready(ProtocolsHandlerEvent::Custom(HandlerEvent::PeerKind( return Poll::Ready(ConnectionHandlerEvent::Custom(HandlerEvent::PeerKind(
peer_kind.clone(), peer_kind.clone(),
))); )));
} }
@ -360,7 +361,7 @@ impl ProtocolsHandler for GossipsubHandler {
if self.inbound_substreams_created > MAX_SUBSTREAM_CREATION { if self.inbound_substreams_created > MAX_SUBSTREAM_CREATION {
// Too many inbound substreams have been created, end the connection. // Too many inbound substreams have been created, end the connection.
return Poll::Ready(ProtocolsHandlerEvent::Close( return Poll::Ready(ConnectionHandlerEvent::Close(
GossipsubHandlerError::MaxInboundSubstreams, GossipsubHandlerError::MaxInboundSubstreams,
)); ));
} }
@ -371,14 +372,14 @@ impl ProtocolsHandler for GossipsubHandler {
&& !self.outbound_substream_establishing && !self.outbound_substream_establishing
{ {
if self.outbound_substreams_created >= MAX_SUBSTREAM_CREATION { if self.outbound_substreams_created >= MAX_SUBSTREAM_CREATION {
return Poll::Ready(ProtocolsHandlerEvent::Close( return Poll::Ready(ConnectionHandlerEvent::Close(
GossipsubHandlerError::MaxOutboundSubstreams, GossipsubHandlerError::MaxOutboundSubstreams,
)); ));
} }
let message = self.send_queue.remove(0); let message = self.send_queue.remove(0);
self.send_queue.shrink_to_fit(); self.send_queue.shrink_to_fit();
self.outbound_substream_establishing = true; self.outbound_substream_establishing = true;
return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: self.listen_protocol.clone().map_info(|()| message), protocol: self.listen_protocol.clone().map_info(|()| message),
}); });
} }
@ -398,7 +399,7 @@ impl ProtocolsHandler for GossipsubHandler {
} }
self.inbound_substream = self.inbound_substream =
Some(InboundSubstreamState::WaitingInput(substream)); Some(InboundSubstreamState::WaitingInput(substream));
return Poll::Ready(ProtocolsHandlerEvent::Custom(message)); return Poll::Ready(ConnectionHandlerEvent::Custom(message));
} }
Poll::Ready(Some(Err(error))) => { Poll::Ready(Some(Err(error))) => {
match error { match error {
@ -496,13 +497,13 @@ impl ProtocolsHandler for GossipsubHandler {
} }
Err(e) => { Err(e) => {
error!("Error sending message: {}", e); error!("Error sending message: {}", e);
return Poll::Ready(ProtocolsHandlerEvent::Close(e)); return Poll::Ready(ConnectionHandlerEvent::Close(e));
} }
} }
} }
Poll::Ready(Err(e)) => { Poll::Ready(Err(e)) => {
error!("Outbound substream error while sending output: {:?}", e); error!("Outbound substream error while sending output: {:?}", e);
return Poll::Ready(ProtocolsHandlerEvent::Close(e)); return Poll::Ready(ConnectionHandlerEvent::Close(e));
} }
Poll::Pending => { Poll::Pending => {
self.keep_alive = KeepAlive::Yes; self.keep_alive = KeepAlive::Yes;
@ -523,7 +524,9 @@ impl ProtocolsHandler for GossipsubHandler {
self.outbound_substream = self.outbound_substream =
Some(OutboundSubstreamState::WaitingOutput(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 => { Poll::Pending => {
self.keep_alive = KeepAlive::Yes; self.keep_alive = KeepAlive::Yes;
self.outbound_substream = self.outbound_substream =
@ -544,7 +547,7 @@ impl ProtocolsHandler for GossipsubHandler {
} }
Poll::Ready(Err(e)) => { Poll::Ready(Err(e)) => {
warn!("Outbound substream error while closing: {:?}", e); warn!("Outbound substream error while closing: {:?}", e);
return Poll::Ready(ProtocolsHandlerEvent::Close( return Poll::Ready(ConnectionHandlerEvent::Close(
io::Error::new( io::Error::new(
io::ErrorKind::BrokenPipe, io::ErrorKind::BrokenPipe,
"Failed to close outbound substream", "Failed to close outbound substream",

View File

@ -28,8 +28,8 @@ use libp2p_core::upgrade::{
EitherUpgrade, InboundUpgrade, OutboundUpgrade, SelectUpgrade, UpgradeError, EitherUpgrade, InboundUpgrade, OutboundUpgrade, SelectUpgrade, UpgradeError,
}; };
use libp2p_swarm::{ use libp2p_swarm::{
KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
ProtocolsHandlerUpgrErr, SubstreamProtocol, NegotiatedSubstream, SubstreamProtocol,
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{io, pin::Pin, task::Context, task::Poll, time::Duration}; 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 { pub struct IdentifyHandler {
/// Pending events to yield. /// Pending events to yield.
events: SmallVec< events: SmallVec<
[ProtocolsHandlerEvent< [ConnectionHandlerEvent<
EitherUpgrade<IdentifyProtocol, IdentifyPushProtocol<OutboundPush>>, EitherUpgrade<IdentifyProtocol, IdentifyPushProtocol<OutboundPush>>,
(), (),
IdentifyHandlerEvent, IdentifyHandlerEvent,
@ -70,7 +70,7 @@ pub enum IdentifyHandlerEvent {
/// We received a request for identification. /// We received a request for identification.
Identify(ReplySubstream<NegotiatedSubstream>), Identify(ReplySubstream<NegotiatedSubstream>),
/// Failed to identify the remote. /// Failed to identify the remote.
IdentificationError(ProtocolsHandlerUpgrErr<io::Error>), IdentificationError(ConnectionHandlerUpgrErr<io::Error>),
} }
/// Identifying information of the local node that is pushed to a remote. /// 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 InEvent = IdentifyPush;
type OutEvent = IdentifyHandlerEvent; type OutEvent = IdentifyHandlerEvent;
type Error = io::Error; type Error = io::Error;
@ -111,10 +111,10 @@ impl ProtocolsHandler for IdentifyHandler {
_: Self::InboundOpenInfo, _: Self::InboundOpenInfo,
) { ) {
match output { match output {
EitherOutput::First(substream) => self.events.push(ProtocolsHandlerEvent::Custom( EitherOutput::First(substream) => self.events.push(ConnectionHandlerEvent::Custom(
IdentifyHandlerEvent::Identify(substream), IdentifyHandlerEvent::Identify(substream),
)), )),
EitherOutput::Second(info) => self.events.push(ProtocolsHandlerEvent::Custom( EitherOutput::Second(info) => self.events.push(ConnectionHandlerEvent::Custom(
IdentifyHandlerEvent::Identified(info), IdentifyHandlerEvent::Identified(info),
)), )),
} }
@ -127,12 +127,12 @@ impl ProtocolsHandler for IdentifyHandler {
) { ) {
match output { match output {
EitherOutput::First(remote_info) => { EitherOutput::First(remote_info) => {
self.events.push(ProtocolsHandlerEvent::Custom( self.events.push(ConnectionHandlerEvent::Custom(
IdentifyHandlerEvent::Identified(remote_info), IdentifyHandlerEvent::Identified(remote_info),
)); ));
self.keep_alive = KeepAlive::No; self.keep_alive = KeepAlive::No;
} }
EitherOutput::Second(()) => self.events.push(ProtocolsHandlerEvent::Custom( EitherOutput::Second(()) => self.events.push(ConnectionHandlerEvent::Custom(
IdentifyHandlerEvent::IdentificationPushed, IdentifyHandlerEvent::IdentificationPushed,
)), )),
} }
@ -140,7 +140,7 @@ impl ProtocolsHandler for IdentifyHandler {
fn inject_event(&mut self, IdentifyPush(push): Self::InEvent) { fn inject_event(&mut self, IdentifyPush(push): Self::InEvent) {
self.events self.events
.push(ProtocolsHandlerEvent::OutboundSubstreamRequest { .push(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new( protocol: SubstreamProtocol::new(
EitherUpgrade::B(IdentifyPushProtocol::outbound(push)), EitherUpgrade::B(IdentifyPushProtocol::outbound(push)),
(), (),
@ -151,7 +151,7 @@ impl ProtocolsHandler for IdentifyHandler {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
_info: Self::OutboundOpenInfo, _info: Self::OutboundOpenInfo,
err: ProtocolsHandlerUpgrErr< err: ConnectionHandlerUpgrErr<
<Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error, <Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error,
>, >,
) { ) {
@ -160,7 +160,7 @@ impl ProtocolsHandler for IdentifyHandler {
UpgradeError::Apply(EitherError::A(ioe)) => UpgradeError::Apply(ioe), UpgradeError::Apply(EitherError::A(ioe)) => UpgradeError::Apply(ioe),
UpgradeError::Apply(EitherError::B(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), IdentifyHandlerEvent::IdentificationError(err),
)); ));
self.keep_alive = KeepAlive::No; self.keep_alive = KeepAlive::No;
@ -175,7 +175,7 @@ impl ProtocolsHandler for IdentifyHandler {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
IdentifyHandlerEvent, IdentifyHandlerEvent,
@ -191,7 +191,7 @@ impl ProtocolsHandler for IdentifyHandler {
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,
Poll::Ready(()) => { Poll::Ready(()) => {
self.next_id.reset(self.interval); self.next_id.reset(self.interval);
let ev = ProtocolsHandlerEvent::OutboundSubstreamRequest { let ev = ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new(EitherUpgrade::A(IdentifyProtocol), ()), protocol: SubstreamProtocol::new(EitherUpgrade::A(IdentifyProtocol), ()),
}; };
Poll::Ready(ev) Poll::Ready(ev)

View File

@ -29,9 +29,8 @@ use libp2p_core::{
}; };
use libp2p_swarm::{ use libp2p_swarm::{
dial_opts::{self, DialOpts}, dial_opts::{self, DialOpts},
AddressScore, DialError, IntoProtocolsHandler, NegotiatedSubstream, NetworkBehaviour, AddressScore, ConnectionHandler, ConnectionHandlerUpgrErr, DialError, IntoConnectionHandler,
NetworkBehaviourAction, NotifyHandler, PollParameters, ProtocolsHandler, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters,
ProtocolsHandlerUpgrErr,
}; };
use lru::LruCache; use lru::LruCache;
use std::{ use std::{
@ -213,10 +212,10 @@ impl Identify {
} }
impl NetworkBehaviour for Identify { impl NetworkBehaviour for Identify {
type ProtocolsHandler = IdentifyHandler; type ConnectionHandler = IdentifyHandler;
type OutEvent = IdentifyEvent; 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) IdentifyHandler::new(self.config.initial_delay, self.config.interval)
} }
@ -254,7 +253,7 @@ impl NetworkBehaviour for Identify {
peer_id: &PeerId, peer_id: &PeerId,
conn: &ConnectionId, conn: &ConnectionId,
_: &ConnectedPoint, _: &ConnectedPoint,
_: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, _: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
if remaining_established == 0 { if remaining_established == 0 {
@ -268,7 +267,7 @@ impl NetworkBehaviour for Identify {
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
peer_id: Option<PeerId>, peer_id: Option<PeerId>,
_: Self::ProtocolsHandler, _: Self::ConnectionHandler,
error: &DialError, error: &DialError,
) { ) {
if let Some(peer_id) = peer_id { if let Some(peer_id) = peer_id {
@ -302,7 +301,7 @@ impl NetworkBehaviour for Identify {
&mut self, &mut self,
peer_id: PeerId, peer_id: PeerId,
connection: ConnectionId, connection: ConnectionId,
event: <Self::ProtocolsHandler as ProtocolsHandler>::OutEvent, event: <Self::ConnectionHandler as ConnectionHandler>::OutEvent,
) { ) {
match event { match event {
IdentifyHandlerEvent::Identified(mut info) => { IdentifyHandlerEvent::Identified(mut info) => {
@ -356,7 +355,7 @@ impl NetworkBehaviour for Identify {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
params: &mut impl PollParameters, params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(event) = self.events.pop_front() { if let Some(event) = self.events.pop_front() {
return Poll::Ready(event); return Poll::Ready(event);
} }
@ -433,7 +432,7 @@ impl NetworkBehaviour for Identify {
Poll::Ready(Err(err)) => { Poll::Ready(Err(err)) => {
let event = IdentifyEvent::Error { let event = IdentifyEvent::Error {
peer_id: peer, peer_id: peer,
error: ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply( error: ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(
err, err,
)), )),
}; };
@ -486,7 +485,7 @@ pub enum IdentifyEvent {
/// The peer with whom the error originated. /// The peer with whom the error originated.
peer_id: PeerId, peer_id: PeerId,
/// The error that occurred. /// The error that occurred.
error: ProtocolsHandlerUpgrErr<io::Error>, error: ConnectionHandlerUpgrErr<io::Error>,
}, },
} }

View File

@ -1783,10 +1783,10 @@ where
for<'a> TStore: RecordStore<'a>, for<'a> TStore: RecordStore<'a>,
TStore: Send + 'static, TStore: Send + 'static,
{ {
type ProtocolsHandler = KademliaHandlerProto<QueryId>; type ConnectionHandler = KademliaHandlerProto<QueryId>;
type OutEvent = KademliaEvent; type OutEvent = KademliaEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
KademliaHandlerProto::new(KademliaHandlerConfig { KademliaHandlerProto::new(KademliaHandlerConfig {
protocol_config: self.protocol_config.clone(), protocol_config: self.protocol_config.clone(),
allow_listening: true, allow_listening: true,
@ -1916,7 +1916,7 @@ where
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
peer_id: Option<PeerId>, peer_id: Option<PeerId>,
_: Self::ProtocolsHandler, _: Self::ConnectionHandler,
error: &DialError, error: &DialError,
) { ) {
let peer_id = match peer_id { let peer_id = match peer_id {
@ -1962,7 +1962,7 @@ where
id: &PeerId, id: &PeerId,
_: &ConnectionId, _: &ConnectionId,
_: &ConnectedPoint, _: &ConnectedPoint,
_: <Self::ProtocolsHandler as libp2p_swarm::IntoProtocolsHandler>::Handler, _: <Self::ConnectionHandler as libp2p_swarm::IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
if remaining_established == 0 { if remaining_established == 0 {
@ -2243,7 +2243,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
parameters: &mut impl PollParameters, parameters: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
let now = Instant::now(); let now = Instant::now();
// Calculate the available capacity for queries triggered by background jobs. // Calculate the available capacity for queries triggered by background jobs.

View File

@ -31,8 +31,8 @@ use libp2p_core::{
ConnectedPoint, PeerId, ConnectedPoint, PeerId,
}; };
use libp2p_swarm::{ use libp2p_swarm::{
IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, KeepAlive, NegotiatedSubstream, SubstreamProtocol,
}; };
use log::trace; use log::trace;
use std::{ use std::{
@ -54,14 +54,14 @@ impl<T> KademliaHandlerProto<T> {
} }
} }
impl<T: Clone + fmt::Debug + Send + 'static> IntoProtocolsHandler for KademliaHandlerProto<T> { impl<T: Clone + fmt::Debug + Send + 'static> IntoConnectionHandler for KademliaHandlerProto<T> {
type Handler = KademliaHandler<T>; type Handler = KademliaHandler<T>;
fn into_handler(self, _: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { fn into_handler(self, _: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
KademliaHandler::new(self.config, endpoint.clone()) KademliaHandler::new(self.config, endpoint.clone())
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
if self.config.allow_listening { if self.config.allow_listening {
upgrade::EitherUpgrade::A(self.config.protocol_config.clone()) upgrade::EitherUpgrade::A(self.config.protocol_config.clone())
} else { } else {
@ -297,7 +297,7 @@ pub enum KademliaHandlerEvent<TUserData> {
#[derive(Debug)] #[derive(Debug)]
pub enum KademliaHandlerQueryErr { pub enum KademliaHandlerQueryErr {
/// Error while trying to perform the query. /// Error while trying to perform the query.
Upgrade(ProtocolsHandlerUpgrErr<io::Error>), Upgrade(ConnectionHandlerUpgrErr<io::Error>),
/// Received an answer that doesn't correspond to the request. /// Received an answer that doesn't correspond to the request.
UnexpectedMessage, UnexpectedMessage,
/// I/O error in the substream. /// I/O error in the substream.
@ -333,8 +333,8 @@ impl error::Error for KademliaHandlerQueryErr {
} }
} }
impl From<ProtocolsHandlerUpgrErr<io::Error>> for KademliaHandlerQueryErr { impl From<ConnectionHandlerUpgrErr<io::Error>> for KademliaHandlerQueryErr {
fn from(err: ProtocolsHandlerUpgrErr<io::Error>) -> Self { fn from(err: ConnectionHandlerUpgrErr<io::Error>) -> Self {
KademliaHandlerQueryErr::Upgrade(err) KademliaHandlerQueryErr::Upgrade(err)
} }
} }
@ -466,7 +466,7 @@ impl<TUserData> KademliaHandler<TUserData> {
} }
} }
impl<TUserData> ProtocolsHandler for KademliaHandler<TUserData> impl<TUserData> ConnectionHandler for KademliaHandler<TUserData>
where where
TUserData: Clone + fmt::Debug + Send + 'static, TUserData: Clone + fmt::Debug + Send + 'static,
{ {
@ -676,7 +676,7 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
(_, user_data): Self::OutboundOpenInfo, (_, user_data): Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<io::Error>, error: ConnectionHandlerUpgrErr<io::Error>,
) { ) {
// TODO: cache the fact that the remote doesn't support kademlia at all, so that we don't // TODO: cache the fact that the remote doesn't support kademlia at all, so that we don't
// continue trying // continue trying
@ -694,7 +694,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -707,7 +707,7 @@ where
if let ProtocolStatus::Confirmed = self.protocol_status { if let ProtocolStatus::Confirmed = self.protocol_status {
self.protocol_status = ProtocolStatus::Reported; self.protocol_status = ProtocolStatus::Reported;
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
KademliaHandlerEvent::ProtocolConfirmed { KademliaHandlerEvent::ProtocolConfirmed {
endpoint: self.endpoint.clone(), endpoint: self.endpoint.clone(),
}, },
@ -778,7 +778,7 @@ fn advance_substream<TUserData>(
) -> ( ) -> (
Option<SubstreamState<TUserData>>, Option<SubstreamState<TUserData>>,
Option< Option<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
KademliaProtocolConfig, KademliaProtocolConfig,
(KadRequestMsg, Option<TUserData>), (KadRequestMsg, Option<TUserData>),
KademliaHandlerEvent<TUserData>, KademliaHandlerEvent<TUserData>,
@ -789,7 +789,7 @@ fn advance_substream<TUserData>(
) { ) {
match state { match state {
SubstreamState::OutPendingOpen(msg, user_data) => { SubstreamState::OutPendingOpen(msg, user_data) => {
let ev = ProtocolsHandlerEvent::OutboundSubstreamRequest { let ev = ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new(upgrade, (msg, user_data)), protocol: SubstreamProtocol::new(upgrade, (msg, user_data)),
}; };
(None, Some(ev), false) (None, Some(ev), false)
@ -804,7 +804,7 @@ fn advance_substream<TUserData>(
), ),
Err(error) => { Err(error) => {
let event = user_data.map(|user_data| { let event = user_data.map(|user_data| {
ProtocolsHandlerEvent::Custom(KademliaHandlerEvent::QueryError { ConnectionHandlerEvent::Custom(KademliaHandlerEvent::QueryError {
error: KademliaHandlerQueryErr::Io(error), error: KademliaHandlerQueryErr::Io(error),
user_data, user_data,
}) })
@ -820,7 +820,7 @@ fn advance_substream<TUserData>(
), ),
Poll::Ready(Err(error)) => { Poll::Ready(Err(error)) => {
let event = user_data.map(|user_data| { let event = user_data.map(|user_data| {
ProtocolsHandlerEvent::Custom(KademliaHandlerEvent::QueryError { ConnectionHandlerEvent::Custom(KademliaHandlerEvent::QueryError {
error: KademliaHandlerQueryErr::Io(error), error: KademliaHandlerQueryErr::Io(error),
user_data, user_data,
}) })
@ -850,7 +850,7 @@ fn advance_substream<TUserData>(
), ),
Poll::Ready(Err(error)) => { Poll::Ready(Err(error)) => {
let event = user_data.map(|user_data| { let event = user_data.map(|user_data| {
ProtocolsHandlerEvent::Custom(KademliaHandlerEvent::QueryError { ConnectionHandlerEvent::Custom(KademliaHandlerEvent::QueryError {
error: KademliaHandlerQueryErr::Io(error), error: KademliaHandlerQueryErr::Io(error),
user_data, user_data,
}) })
@ -867,7 +867,7 @@ fn advance_substream<TUserData>(
let event = process_kad_response(msg, user_data); let event = process_kad_response(msg, user_data);
( (
Some(new_state), Some(new_state),
Some(ProtocolsHandlerEvent::Custom(event)), Some(ConnectionHandlerEvent::Custom(event)),
true, true,
) )
} }
@ -881,20 +881,20 @@ fn advance_substream<TUserData>(
error: KademliaHandlerQueryErr::Io(error), error: KademliaHandlerQueryErr::Io(error),
user_data, user_data,
}; };
(None, Some(ProtocolsHandlerEvent::Custom(event)), false) (None, Some(ConnectionHandlerEvent::Custom(event)), false)
} }
Poll::Ready(None) => { Poll::Ready(None) => {
let event = KademliaHandlerEvent::QueryError { let event = KademliaHandlerEvent::QueryError {
error: KademliaHandlerQueryErr::Io(io::ErrorKind::UnexpectedEof.into()), error: KademliaHandlerQueryErr::Io(io::ErrorKind::UnexpectedEof.into()),
user_data, user_data,
}; };
(None, Some(ProtocolsHandlerEvent::Custom(event)), false) (None, Some(ConnectionHandlerEvent::Custom(event)), false)
} }
} }
} }
SubstreamState::OutReportError(error, user_data) => { SubstreamState::OutReportError(error, user_data) => {
let event = KademliaHandlerEvent::QueryError { 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) SubstreamState::OutClosing(mut stream) => match Sink::poll_close(Pin::new(&mut stream), cx)
{ {
@ -908,7 +908,7 @@ fn advance_substream<TUserData>(
if let Ok(ev) = process_kad_request(msg, id) { if let Ok(ev) = process_kad_request(msg, id) {
( (
Some(SubstreamState::InWaitingUser(id, substream)), Some(SubstreamState::InWaitingUser(id, substream)),
Some(ProtocolsHandlerEvent::Custom(ev)), Some(ConnectionHandlerEvent::Custom(ev)),
false, false,
) )
} else { } else {

View File

@ -28,8 +28,8 @@ use if_watch::{IfEvent, IfWatcher};
use libp2p_core::connection::ListenerId; use libp2p_core::connection::ListenerId;
use libp2p_core::{Multiaddr, PeerId}; use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::{ use libp2p_swarm::{
protocols_handler::DummyProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, handler::DummyConnectionHandler, ConnectionHandler, NetworkBehaviour, NetworkBehaviourAction,
PollParameters, ProtocolsHandler, PollParameters,
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
use std::collections::hash_map::{Entry, HashMap}; use std::collections::hash_map::{Entry, HashMap};
@ -96,11 +96,11 @@ impl Mdns {
} }
impl NetworkBehaviour for Mdns { impl NetworkBehaviour for Mdns {
type ProtocolsHandler = DummyProtocolsHandler; type ConnectionHandler = DummyConnectionHandler;
type OutEvent = MdnsEvent; type OutEvent = MdnsEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
DummyProtocolsHandler::default() DummyConnectionHandler::default()
} }
fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> { fn addresses_of_peer(&mut self, peer_id: &PeerId) -> Vec<Multiaddr> {
@ -115,7 +115,7 @@ impl NetworkBehaviour for Mdns {
&mut self, &mut self,
_: PeerId, _: PeerId,
_: libp2p_core::connection::ConnectionId, _: libp2p_core::connection::ConnectionId,
ev: <Self::ProtocolsHandler as ProtocolsHandler>::OutEvent, ev: <Self::ConnectionHandler as ConnectionHandler>::OutEvent,
) { ) {
void::unreachable(ev) void::unreachable(ev)
} }
@ -132,7 +132,7 @@ impl NetworkBehaviour for Mdns {
peer: &PeerId, peer: &PeerId,
_: &libp2p_core::connection::ConnectionId, _: &libp2p_core::connection::ConnectionId,
_: &libp2p_core::ConnectedPoint, _: &libp2p_core::ConnectedPoint,
_: Self::ProtocolsHandler, _: Self::ConnectionHandler,
remaining_established: usize, remaining_established: usize,
) { ) {
if remaining_established == 0 { if remaining_established == 0 {
@ -144,7 +144,7 @@ impl NetworkBehaviour for Mdns {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
params: &mut impl PollParameters, params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, DummyProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, DummyConnectionHandler>> {
// Poll ifwatch. // Poll ifwatch.
while let Poll::Ready(event) = Pin::new(&mut self.if_watch).poll(cx) { while let Poll::Ready(event) = Pin::new(&mut self.if_watch).poll(cx) {
match event { match event {

View File

@ -24,8 +24,8 @@ use futures::prelude::*;
use futures_timer::Delay; use futures_timer::Delay;
use libp2p_core::{upgrade::NegotiationError, UpgradeError}; use libp2p_core::{upgrade::NegotiationError, UpgradeError};
use libp2p_swarm::{ use libp2p_swarm::{
KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
ProtocolsHandlerUpgrErr, SubstreamProtocol, NegotiatedSubstream, SubstreamProtocol,
}; };
use std::collections::VecDeque; use std::collections::VecDeque;
use std::{ use std::{
@ -108,7 +108,7 @@ impl Config {
/// is determined by other protocol handlers. /// is determined by other protocol handlers.
/// ///
/// If the maximum number of allowed ping failures is reached, the /// 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. /// returning an error, regardless of the keep-alive setting.
pub fn with_keep_alive(mut self, b: bool) -> Self { pub fn with_keep_alive(mut self, b: bool) -> Self {
self.keep_alive = b; self.keep_alive = b;
@ -215,7 +215,7 @@ impl Handler {
} }
} }
impl ProtocolsHandler for Handler { impl ConnectionHandler for Handler {
type InEvent = Void; type InEvent = Void;
type OutEvent = crate::Result; type OutEvent = crate::Result;
type Error = Failure; type Error = Failure;
@ -239,18 +239,18 @@ impl ProtocolsHandler for Handler {
fn inject_event(&mut self, _: Void) {} fn inject_event(&mut self, _: Void) {}
fn inject_dial_upgrade_error(&mut self, _info: (), error: ProtocolsHandlerUpgrErr<Void>) { fn inject_dial_upgrade_error(&mut self, _info: (), error: ConnectionHandlerUpgrErr<Void>) {
self.outbound = None; // Request a new substream on the next `poll`. self.outbound = None; // Request a new substream on the next `poll`.
let error = match error { let error = match error {
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => { ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(NegotiationError::Failed)) => {
debug_assert_eq!(self.state, State::Active); debug_assert_eq!(self.state, State::Active);
self.state = State::Inactive { reported: false }; self.state = State::Inactive { reported: false };
return; return;
} }
// Note: This timeout only covers protocol negotiation. // Note: This timeout only covers protocol negotiation.
ProtocolsHandlerUpgrErr::Timeout => Failure::Timeout, ConnectionHandlerUpgrErr::Timeout => Failure::Timeout,
e => Failure::Other { error: Box::new(e) }, e => Failure::Other { error: Box::new(e) },
}; };
@ -268,14 +268,14 @@ impl ProtocolsHandler for Handler {
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll<ProtocolsHandlerEvent<protocol::Ping, (), crate::Result, Self::Error>> { ) -> Poll<ConnectionHandlerEvent<protocol::Ping, (), crate::Result, Self::Error>> {
match self.state { match self.state {
State::Inactive { reported: true } => { State::Inactive { reported: true } => {
return Poll::Pending; // nothing to do on this connection return Poll::Pending; // nothing to do on this connection
} }
State::Inactive { reported: false } => { State::Inactive { reported: false } => {
self.state = State::Inactive { reported: true }; self.state = State::Inactive { reported: true };
return Poll::Ready(ProtocolsHandlerEvent::Custom(Err(Failure::Unsupported))); return Poll::Ready(ConnectionHandlerEvent::Custom(Err(Failure::Unsupported)));
} }
State::Active => {} State::Active => {}
} }
@ -291,7 +291,7 @@ impl ProtocolsHandler for Handler {
Poll::Ready(Ok(stream)) => { Poll::Ready(Ok(stream)) => {
// A ping from a remote peer has been answered, wait for the next. // A ping from a remote peer has been answered, wait for the next.
self.inbound = Some(protocol::recv_ping(stream).boxed()); 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 > 1 || self.config.max_failures.get() > 1 {
if self.failures >= self.config.max_failures.get() { if self.failures >= self.config.max_failures.get() {
log::debug!("Too many failures ({}). Closing connection.", self.failures); 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.failures = 0;
self.timer.reset(self.config.interval); self.timer.reset(self.config.interval);
self.outbound = Some(PingState::Idle(stream)); self.outbound = Some(PingState::Idle(stream));
return Poll::Ready(ProtocolsHandlerEvent::Custom(Ok(Success::Ping { return Poll::Ready(ConnectionHandlerEvent::Custom(Ok(Success::Ping {
rtt, rtt,
}))); })));
} }
@ -362,7 +362,7 @@ impl ProtocolsHandler for Handler {
self.outbound = Some(PingState::OpenStream); self.outbound = Some(PingState::OpenStream);
let protocol = SubstreamProtocol::new(protocol::Ping, ()) let protocol = SubstreamProtocol::new(protocol::Ping, ())
.with_timeout(self.config.timeout); .with_timeout(self.config.timeout);
return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol, protocol,
}); });
} }

View File

@ -103,10 +103,10 @@ impl Default for Behaviour {
} }
impl NetworkBehaviour for Behaviour { impl NetworkBehaviour for Behaviour {
type ProtocolsHandler = Handler; type ConnectionHandler = Handler;
type OutEvent = Event; type OutEvent = Event;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
Handler::new(self.config.clone()) Handler::new(self.config.clone())
} }
@ -118,7 +118,7 @@ impl NetworkBehaviour for Behaviour {
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(e) = self.events.pop_back() { if let Some(e) = self.events.pop_back() {
Poll::Ready(NetworkBehaviourAction::GenerateEvent(e)) Poll::Ready(NetworkBehaviourAction::GenerateEvent(e))
} else { } else {

View File

@ -31,7 +31,7 @@ use libp2p_core::multiaddr::Multiaddr;
use libp2p_core::PeerId; use libp2p_core::PeerId;
use libp2p_swarm::{ use libp2p_swarm::{
dial_opts::{self, DialOpts}, dial_opts::{self, DialOpts},
DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler,
PollParameters, PollParameters,
}; };
use std::collections::{hash_map::Entry, HashMap, HashSet, VecDeque}; use std::collections::{hash_map::Entry, HashMap, HashSet, VecDeque};
@ -154,10 +154,10 @@ impl Relay {
} }
impl NetworkBehaviour for Relay { impl NetworkBehaviour for Relay {
type ProtocolsHandler = RelayHandlerProto; type ConnectionHandler = RelayHandlerProto;
type OutEvent = (); type OutEvent = ();
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
RelayHandlerProto { RelayHandlerProto {
config: RelayHandlerConfig { config: RelayHandlerConfig {
connection_idle_timeout: self.config.connection_idle_timeout, connection_idle_timeout: self.config.connection_idle_timeout,
@ -301,7 +301,7 @@ impl NetworkBehaviour for Relay {
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
peer_id: Option<PeerId>, peer_id: Option<PeerId>,
_: Self::ProtocolsHandler, _: Self::ConnectionHandler,
error: &DialError, error: &DialError,
) { ) {
if let DialError::DialPeerConditionFalse( if let DialError::DialPeerConditionFalse(
@ -352,7 +352,7 @@ impl NetworkBehaviour for Relay {
peer: &PeerId, peer: &PeerId,
connection: &ConnectionId, connection: &ConnectionId,
_: &ConnectedPoint, _: &ConnectedPoint,
_: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, _: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
// Remove connection from the set of connections for the given peer. In case the set is // 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, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
poll_parameters: &mut impl PollParameters, poll_parameters: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if !self.outbox_to_listeners.is_empty() { if !self.outbox_to_listeners.is_empty() {
let relay_peer_id = self.outbox_to_listeners[0].0; let relay_peer_id = self.outbox_to_listeners[0].0;

View File

@ -29,8 +29,8 @@ use libp2p_core::connection::ConnectionId;
use libp2p_core::either::{EitherError, EitherOutput}; use libp2p_core::either::{EitherError, EitherOutput};
use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId}; use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId};
use libp2p_swarm::{ use libp2p_swarm::{
IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, KeepAlive, NegotiatedSubstream, SubstreamProtocol,
}; };
use log::warn; use log::warn;
use std::fmt; use std::fmt;
@ -46,7 +46,7 @@ pub struct RelayHandlerProto {
pub config: RelayHandlerConfig, pub config: RelayHandlerConfig,
} }
impl IntoProtocolsHandler for RelayHandlerProto { impl IntoConnectionHandler for RelayHandlerProto {
type Handler = RelayHandler; type Handler = RelayHandler;
fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
@ -57,7 +57,7 @@ impl IntoProtocolsHandler for RelayHandlerProto {
) )
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
protocol::RelayListen::new() protocol::RelayListen::new()
} }
} }
@ -118,7 +118,7 @@ pub struct RelayHandler {
keep_alive: KeepAlive, keep_alive: KeepAlive,
/// A pending fatal error that results in the connection being closed. /// A pending fatal error that results in the connection being closed.
pending_error: Option< pending_error: Option<
ProtocolsHandlerUpgrErr< ConnectionHandlerUpgrErr<
EitherError< EitherError<
protocol::RelayListenError, protocol::RelayListenError,
EitherError<protocol::OutgoingRelayReqError, protocol::OutgoingDstReqError>, EitherError<protocol::OutgoingRelayReqError, protocol::OutgoingDstReqError>,
@ -347,10 +347,10 @@ impl RelayHandler {
} }
} }
impl ProtocolsHandler for RelayHandler { impl ConnectionHandler for RelayHandler {
type InEvent = RelayHandlerIn; type InEvent = RelayHandlerIn;
type OutEvent = RelayHandlerEvent; type OutEvent = RelayHandlerEvent;
type Error = ProtocolsHandlerUpgrErr< type Error = ConnectionHandlerUpgrErr<
EitherError< EitherError<
protocol::RelayListenError, protocol::RelayListenError,
EitherError<protocol::OutgoingRelayReqError, protocol::OutgoingDstReqError>, EitherError<protocol::OutgoingRelayReqError, protocol::OutgoingDstReqError>,
@ -478,22 +478,22 @@ impl ProtocolsHandler for RelayHandler {
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
_: Self::InboundOpenInfo, _: Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<protocol::RelayListenError>, error: ConnectionHandlerUpgrErr<protocol::RelayListenError>,
) { ) {
match error { match error {
ProtocolsHandlerUpgrErr::Timeout | ProtocolsHandlerUpgrErr::Timer => {} ConnectionHandlerUpgrErr::Timeout | ConnectionHandlerUpgrErr::Timer => {}
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)) => {} )) => {}
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)), upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)),
)); ));
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::A(error)), upgrade::UpgradeError::Apply(EitherError::A(error)),
)) ))
} }
@ -503,7 +503,7 @@ impl ProtocolsHandler for RelayHandler {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
open_info: Self::OutboundOpenInfo, open_info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr< error: ConnectionHandlerUpgrErr<
EitherError<protocol::OutgoingRelayReqError, protocol::OutgoingDstReqError>, EitherError<protocol::OutgoingRelayReqError, protocol::OutgoingDstReqError>,
>, >,
) { ) {
@ -513,20 +513,20 @@ impl ProtocolsHandler for RelayHandler {
request_id, request_id,
} => { } => {
match error { match error {
ProtocolsHandlerUpgrErr::Timeout | ProtocolsHandlerUpgrErr::Timer => {} ConnectionHandlerUpgrErr::Timeout | ConnectionHandlerUpgrErr::Timer => {}
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)) => {} )) => {}
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Select( upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
), ),
)); ));
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(
EitherError::A(error), EitherError::A(error),
)) => match error { )) => match error {
protocol::OutgoingRelayReqError::Decode(_) protocol::OutgoingRelayReqError::Decode(_)
@ -536,7 +536,7 @@ impl ProtocolsHandler for RelayHandler {
| protocol::OutgoingRelayReqError::UnexpectedSrcPeerWithStatusType | protocol::OutgoingRelayReqError::UnexpectedSrcPeerWithStatusType
| protocol::OutgoingRelayReqError::UnexpectedDstPeerWithStatusType | protocol::OutgoingRelayReqError::UnexpectedDstPeerWithStatusType
| protocol::OutgoingRelayReqError::ExpectedStatusType(_) => { | protocol::OutgoingRelayReqError::ExpectedStatusType(_) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::B(EitherError::A(error))), upgrade::UpgradeError::Apply(EitherError::B(EitherError::A(error))),
)); ));
} }
@ -550,7 +550,7 @@ impl ProtocolsHandler for RelayHandler {
circuit_relay::Status::HopSrcAddrTooLong circuit_relay::Status::HopSrcAddrTooLong
| circuit_relay::Status::HopSrcMultiaddrInvalid | circuit_relay::Status::HopSrcMultiaddrInvalid
| circuit_relay::Status::MalformedMessage => { | circuit_relay::Status::MalformedMessage => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::B( upgrade::UpgradeError::Apply(EitherError::B(
EitherError::A(error), EitherError::A(error),
)), )),
@ -574,7 +574,7 @@ impl ProtocolsHandler for RelayHandler {
} }
} }
}, },
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(
EitherError::B(_), EitherError::B(_),
)) => { )) => {
unreachable!("Can not receive an OutgoingDstReqError when dialing a relay.") unreachable!("Can not receive an OutgoingDstReqError when dialing a relay.")
@ -593,28 +593,28 @@ impl ProtocolsHandler for RelayHandler {
.. ..
} => { } => {
let err_code = match error { let err_code = match error {
ProtocolsHandlerUpgrErr::Timeout | ProtocolsHandlerUpgrErr::Timer => { ConnectionHandlerUpgrErr::Timeout | ConnectionHandlerUpgrErr::Timer => {
circuit_relay::Status::HopCantOpenDstStream circuit_relay::Status::HopCantOpenDstStream
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)) => circuit_relay::Status::HopCantSpeakRelay, )) => circuit_relay::Status::HopCantSpeakRelay,
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Select( upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
), ),
)); ));
circuit_relay::Status::HopCantSpeakRelay circuit_relay::Status::HopCantSpeakRelay
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(
EitherError::A(_), EitherError::A(_),
)) => unreachable!( )) => unreachable!(
"Can not receive an OutgoingRelayReqError when dialing a destination." "Can not receive an OutgoingRelayReqError when dialing a destination."
), ),
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(
EitherError::B(error), EitherError::B(error),
)) => { )) => {
match error { match error {
@ -625,7 +625,7 @@ impl ProtocolsHandler for RelayHandler {
| protocol::OutgoingDstReqError::UnexpectedSrcPeerWithStatusType | protocol::OutgoingDstReqError::UnexpectedSrcPeerWithStatusType
| protocol::OutgoingDstReqError::UnexpectedDstPeerWithStatusType | protocol::OutgoingDstReqError::UnexpectedDstPeerWithStatusType
| protocol::OutgoingDstReqError::ExpectedStatusType(_) => { | protocol::OutgoingDstReqError::ExpectedStatusType(_) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::B(EitherError::B( upgrade::UpgradeError::Apply(EitherError::B(EitherError::B(
error, error,
))), ))),
@ -651,7 +651,7 @@ impl ProtocolsHandler for RelayHandler {
| circuit_relay::Status::HopSrcAddrTooLong | circuit_relay::Status::HopSrcAddrTooLong
| circuit_relay::Status::HopSrcMultiaddrInvalid => { | circuit_relay::Status::HopSrcMultiaddrInvalid => {
self.pending_error = self.pending_error =
Some(ProtocolsHandlerUpgrErr::Upgrade( Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::B( upgrade::UpgradeError::Apply(EitherError::B(
EitherError::B(error), EitherError::B(error),
)), )),
@ -663,7 +663,7 @@ impl ProtocolsHandler for RelayHandler {
| circuit_relay::Status::StopDstMultiaddrInvalid | circuit_relay::Status::StopDstMultiaddrInvalid
| circuit_relay::Status::MalformedMessage => { | circuit_relay::Status::MalformedMessage => {
self.pending_error = self.pending_error =
Some(ProtocolsHandlerUpgrErr::Upgrade( Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::B( upgrade::UpgradeError::Apply(EitherError::B(
EitherError::B(error), EitherError::B(error),
)), )),
@ -699,7 +699,7 @@ impl ProtocolsHandler for RelayHandler {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -709,7 +709,7 @@ impl ProtocolsHandler for RelayHandler {
// Check for a pending (fatal) error. // Check for a pending (fatal) error.
if let Some(err) = self.pending_error.take() { if let Some(err) = self.pending_error.take() {
// The handler will not be polled again by the `Swarm`. // 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. // Request the remote to act as a relay.
@ -721,7 +721,7 @@ impl ProtocolsHandler for RelayHandler {
dst_addr, dst_addr,
} = self.outgoing_relay_reqs.remove(0); } = self.outgoing_relay_reqs.remove(0);
self.outgoing_relay_reqs.shrink_to_fit(); self.outgoing_relay_reqs.shrink_to_fit();
return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new( protocol: SubstreamProtocol::new(
upgrade::EitherUpgrade::A(protocol::OutgoingRelayReq::new( upgrade::EitherUpgrade::A(protocol::OutgoingRelayReq::new(
src_peer_id, src_peer_id,
@ -746,7 +746,7 @@ impl ProtocolsHandler for RelayHandler {
incoming_relay_req, incoming_relay_req,
} = self.outgoing_dst_reqs.remove(0); } = self.outgoing_dst_reqs.remove(0);
self.outgoing_dst_reqs.shrink_to_fit(); self.outgoing_dst_reqs.shrink_to_fit();
return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new( protocol: SubstreamProtocol::new(
upgrade::EitherUpgrade::B(protocol::OutgoingDstReq::new( upgrade::EitherUpgrade::B(protocol::OutgoingDstReq::new(
src_peer_id, src_peer_id,
@ -772,7 +772,7 @@ impl ProtocolsHandler for RelayHandler {
relay_peer_id: self.remote_peer_id, relay_peer_id: self.remote_peer_id,
relay_addr: self.remote_address.clone(), relay_addr: self.remote_address.clone(),
}; };
return Poll::Ready(ProtocolsHandlerEvent::Custom(event)); return Poll::Ready(ConnectionHandlerEvent::Custom(event));
} }
Poll::Ready(Some(Err(e))) => { Poll::Ready(Some(Err(e))) => {
log::debug!("Failed to accept destination future: {:?}", e); log::debug!("Failed to accept destination future: {:?}", e);
@ -796,7 +796,7 @@ impl ProtocolsHandler for RelayHandler {
// Report the queued events. // Report the queued events.
if !self.queued_events.is_empty() { if !self.queued_events.is_empty() {
let event = self.queued_events.remove(0); 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))) = while let Poll::Ready(Some(Err(Canceled))) =

View File

@ -35,10 +35,10 @@ use futures::stream::StreamExt;
use libp2p_core::connection::{ConnectedPoint, ConnectionId}; use libp2p_core::connection::{ConnectedPoint, ConnectionId};
use libp2p_core::{Multiaddr, PeerId}; use libp2p_core::{Multiaddr, PeerId};
use libp2p_swarm::dial_opts::DialOpts; use libp2p_swarm::dial_opts::DialOpts;
use libp2p_swarm::protocols_handler::DummyProtocolsHandler; use libp2p_swarm::handler::DummyConnectionHandler;
use libp2p_swarm::{ use libp2p_swarm::{
NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, ConnectionHandlerUpgrErr, NegotiatedSubstream, NetworkBehaviour, NetworkBehaviourAction,
ProtocolsHandlerUpgrErr, NotifyHandler, PollParameters,
}; };
use std::collections::{hash_map, HashMap, VecDeque}; use std::collections::{hash_map, HashMap, VecDeque};
use std::io::{Error, IoSlice}; use std::io::{Error, IoSlice};
@ -60,7 +60,7 @@ pub enum Event {
relay_peer_id: PeerId, relay_peer_id: PeerId,
/// Indicates whether the request replaces an existing reservation. /// Indicates whether the request replaces an existing reservation.
renewal: bool, renewal: bool,
error: ProtocolsHandlerUpgrErr<outbound_hop::ReservationFailedReason>, error: ConnectionHandlerUpgrErr<outbound_hop::ReservationFailedReason>,
}, },
OutboundCircuitEstablished { OutboundCircuitEstablished {
relay_peer_id: PeerId, relay_peer_id: PeerId,
@ -68,7 +68,7 @@ pub enum Event {
}, },
OutboundCircuitReqFailed { OutboundCircuitReqFailed {
relay_peer_id: PeerId, relay_peer_id: PeerId,
error: ProtocolsHandlerUpgrErr<outbound_hop::CircuitFailedReason>, error: ConnectionHandlerUpgrErr<outbound_hop::CircuitFailedReason>,
}, },
/// An inbound circuit has been established. /// An inbound circuit has been established.
InboundCircuitEstablished { InboundCircuitEstablished {
@ -77,7 +77,7 @@ pub enum Event {
}, },
InboundCircuitReqFailed { InboundCircuitReqFailed {
relay_peer_id: PeerId, relay_peer_id: PeerId,
error: ProtocolsHandlerUpgrErr<void::Void>, error: ConnectionHandlerUpgrErr<void::Void>,
}, },
/// An inbound circuit request has been denied. /// An inbound circuit request has been denied.
InboundCircuitReqDenied { src_peer_id: PeerId }, InboundCircuitReqDenied { src_peer_id: PeerId },
@ -116,10 +116,10 @@ impl Client {
} }
impl NetworkBehaviour for Client { impl NetworkBehaviour for Client {
type ProtocolsHandler = handler::Prototype; type ConnectionHandler = handler::Prototype;
type OutEvent = Event; 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) handler::Prototype::new(self.local_peer_id, None)
} }
@ -144,7 +144,7 @@ impl NetworkBehaviour for Client {
peer_id: &PeerId, peer_id: &PeerId,
connection_id: &ConnectionId, connection_id: &ConnectionId,
endpoint: &ConnectedPoint, endpoint: &ConnectedPoint,
_handler: Either<handler::Handler, DummyProtocolsHandler>, _handler: Either<handler::Handler, DummyConnectionHandler>,
_remaining_established: usize, _remaining_established: usize,
) { ) {
if !endpoint.is_relayed() { if !endpoint.is_relayed() {
@ -231,7 +231,7 @@ impl NetworkBehaviour for Client {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
_poll_parameters: &mut impl PollParameters, _poll_parameters: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(event) = self.queued_actions.pop_front() { if let Some(event) = self.queued_actions.pop_front() {
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event)); return Poll::Ready(NetworkBehaviourAction::GenerateEvent(event));
} }

View File

@ -31,12 +31,12 @@ use instant::Instant;
use libp2p_core::either::EitherError; use libp2p_core::either::EitherError;
use libp2p_core::multiaddr::Protocol; use libp2p_core::multiaddr::Protocol;
use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId}; use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId};
use libp2p_swarm::protocols_handler::{ use libp2p_swarm::handler::{
DummyProtocolsHandler, InboundUpgradeSend, OutboundUpgradeSend, SendWrapper, DummyConnectionHandler, InboundUpgradeSend, OutboundUpgradeSend, SendWrapper,
}; };
use libp2p_swarm::{ use libp2p_swarm::{
IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, KeepAlive, NegotiatedSubstream, SubstreamProtocol,
}; };
use log::debug; use log::debug;
use std::collections::VecDeque; use std::collections::VecDeque;
@ -79,12 +79,12 @@ pub enum Event {
ReservationReqFailed { ReservationReqFailed {
/// Indicates whether the request replaces an existing reservation. /// Indicates whether the request replaces an existing reservation.
renewal: bool, renewal: bool,
error: ProtocolsHandlerUpgrErr<outbound_hop::ReservationFailedReason>, error: ConnectionHandlerUpgrErr<outbound_hop::ReservationFailedReason>,
}, },
/// An outbound circuit has been established. /// An outbound circuit has been established.
OutboundCircuitEstablished { limit: Option<protocol::Limit> }, OutboundCircuitEstablished { limit: Option<protocol::Limit> },
OutboundCircuitReqFailed { OutboundCircuitReqFailed {
error: ProtocolsHandlerUpgrErr<outbound_hop::CircuitFailedReason>, error: ConnectionHandlerUpgrErr<outbound_hop::CircuitFailedReason>,
}, },
/// An inbound circuit has been established. /// An inbound circuit has been established.
InboundCircuitEstablished { InboundCircuitEstablished {
@ -93,7 +93,7 @@ pub enum Event {
}, },
/// An inbound circuit request has failed. /// An inbound circuit request has failed.
InboundCircuitReqFailed { InboundCircuitReqFailed {
error: ProtocolsHandlerUpgrErr<void::Void>, error: ConnectionHandlerUpgrErr<void::Void>,
}, },
/// An inbound circuit request has been denied. /// An inbound circuit request has been denied.
InboundCircuitReqDenied { src_peer_id: PeerId }, InboundCircuitReqDenied { src_peer_id: PeerId },
@ -119,8 +119,8 @@ impl Prototype {
} }
} }
impl IntoProtocolsHandler for Prototype { impl IntoConnectionHandler for Prototype {
type Handler = Either<Handler, DummyProtocolsHandler>; type Handler = Either<Handler, DummyConnectionHandler>;
fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { fn into_handler(self, remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
if endpoint.is_relayed() { if endpoint.is_relayed() {
@ -133,7 +133,7 @@ impl IntoProtocolsHandler for Prototype {
} }
// Deny all substreams on relayed connection. // Deny all substreams on relayed connection.
Either::Right(DummyProtocolsHandler::default()) Either::Right(DummyConnectionHandler::default())
} else { } else {
let mut handler = Handler { let mut handler = Handler {
remote_peer_id: *remote_peer_id, remote_peer_id: *remote_peer_id,
@ -156,7 +156,7 @@ impl IntoProtocolsHandler for Prototype {
} }
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
upgrade::EitherUpgrade::A(SendWrapper(inbound_stop::Upgrade {})) upgrade::EitherUpgrade::A(SendWrapper(inbound_stop::Upgrade {}))
} }
} }
@ -167,7 +167,7 @@ pub struct Handler {
remote_addr: Multiaddr, remote_addr: Multiaddr,
/// A pending fatal error that results in the connection being closed. /// A pending fatal error that results in the connection being closed.
pending_error: Option< pending_error: Option<
ProtocolsHandlerUpgrErr< ConnectionHandlerUpgrErr<
EitherError<inbound_stop::FatalUpgradeError, outbound_hop::FatalUpgradeError>, EitherError<inbound_stop::FatalUpgradeError, outbound_hop::FatalUpgradeError>,
>, >,
>, >,
@ -176,11 +176,11 @@ pub struct Handler {
/// Queue of events to return when polled. /// Queue of events to return when polled.
queued_events: VecDeque< queued_events: VecDeque<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
<Self as ProtocolsHandler>::OutboundProtocol, <Self as ConnectionHandler>::OutboundProtocol,
<Self as ProtocolsHandler>::OutboundOpenInfo, <Self as ConnectionHandler>::OutboundOpenInfo,
<Self as ProtocolsHandler>::OutEvent, <Self as ConnectionHandler>::OutEvent,
<Self as ProtocolsHandler>::Error, <Self as ConnectionHandler>::Error,
>, >,
>, >,
@ -201,14 +201,14 @@ pub struct Handler {
/// Futures that try to send errors to the transport. /// Futures that try to send errors to the transport.
/// ///
/// We may drop errors if this handler ends up in a terminal state (by returning /// We may drop errors if this handler ends up in a terminal state (by returning
/// [`ProtocolsHandlerEvent::Close`]). /// [`ConnectionHandlerEvent::Close`]).
send_error_futs: FuturesUnordered<BoxFuture<'static, ()>>, send_error_futs: FuturesUnordered<BoxFuture<'static, ()>>,
} }
impl ProtocolsHandler for Handler { impl ConnectionHandler for Handler {
type InEvent = In; type InEvent = In;
type OutEvent = Event; type OutEvent = Event;
type Error = ProtocolsHandlerUpgrErr< type Error = ConnectionHandlerUpgrErr<
EitherError<inbound_stop::FatalUpgradeError, outbound_hop::FatalUpgradeError>, EitherError<inbound_stop::FatalUpgradeError, outbound_hop::FatalUpgradeError>,
>; >;
type InboundProtocol = inbound_stop::Upgrade; type InboundProtocol = inbound_stop::Upgrade;
@ -242,7 +242,7 @@ impl ProtocolsHandler for Handler {
relay_addr: self.remote_addr.clone(), relay_addr: self.remote_addr.clone(),
}); });
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::InboundCircuitEstablished { Event::InboundCircuitEstablished {
src_peer_id: self.remote_peer_id, src_peer_id: self.remote_peer_id,
limit, limit,
@ -285,7 +285,7 @@ impl ProtocolsHandler for Handler {
); );
self.queued_events self.queued_events
.push_back(ProtocolsHandlerEvent::Custom(event)); .push_back(ConnectionHandlerEvent::Custom(event));
} }
// Outbound circuit // Outbound circuit
@ -305,7 +305,7 @@ impl ProtocolsHandler for Handler {
))) { ))) {
Ok(()) => { Ok(()) => {
self.alive_lend_out_substreams.push(rx); self.alive_lend_out_substreams.push(rx);
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::OutboundCircuitEstablished { limit }, Event::OutboundCircuitEstablished { limit },
)); ));
} }
@ -325,7 +325,7 @@ impl ProtocolsHandler for Handler {
match event { match event {
In::Reserve { to_listener } => { In::Reserve { to_listener } => {
self.queued_events self.queued_events
.push_back(ProtocolsHandlerEvent::OutboundSubstreamRequest { .push_back(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new( protocol: SubstreamProtocol::new(
outbound_hop::Upgrade::Reserve, outbound_hop::Upgrade::Reserve,
OutboundOpenInfo::Reserve { to_listener }, OutboundOpenInfo::Reserve { to_listener },
@ -337,7 +337,7 @@ impl ProtocolsHandler for Handler {
dst_peer_id, dst_peer_id,
} => { } => {
self.queued_events self.queued_events
.push_back(ProtocolsHandlerEvent::OutboundSubstreamRequest { .push_back(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new( protocol: SubstreamProtocol::new(
outbound_hop::Upgrade::Connect { dst_peer_id }, outbound_hop::Upgrade::Connect { dst_peer_id },
OutboundOpenInfo::Connect { send_back }, OutboundOpenInfo::Connect { send_back },
@ -350,35 +350,35 @@ impl ProtocolsHandler for Handler {
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
_: Self::InboundOpenInfo, _: Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
let non_fatal_error = match error { let non_fatal_error = match error {
ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout,
ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer,
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)) => ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( )) => ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)), )),
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)), upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)),
)); ));
return; return;
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(
inbound_stop::UpgradeError::Fatal(error), inbound_stop::UpgradeError::Fatal(error),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::A(error)), upgrade::UpgradeError::Apply(EitherError::A(error)),
)); ));
return; return;
} }
}; };
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::InboundCircuitReqFailed { Event::InboundCircuitReqFailed {
error: non_fatal_error, error: non_fatal_error,
}, },
@ -388,38 +388,38 @@ impl ProtocolsHandler for Handler {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
open_info: Self::OutboundOpenInfo, open_info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
match open_info { match open_info {
OutboundOpenInfo::Reserve { mut to_listener } => { OutboundOpenInfo::Reserve { mut to_listener } => {
let non_fatal_error = match error { let non_fatal_error = match error {
ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout,
ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer,
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)) => ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( )) => ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)), )),
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Select( upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
), ),
)); ));
return; return;
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => {
match error { match error {
outbound_hop::UpgradeError::Fatal(error) => { outbound_hop::UpgradeError::Fatal(error) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::B(error)), upgrade::UpgradeError::Apply(EitherError::B(error)),
)); ));
return; return;
} }
outbound_hop::UpgradeError::ReservationFailed(error) => { outbound_hop::UpgradeError::ReservationFailed(error) => {
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(
error, error,
)) ))
} }
@ -447,7 +447,7 @@ impl ProtocolsHandler for Handler {
} }
let renewal = self.reservation.failed(); let renewal = self.reservation.failed();
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::ReservationReqFailed { Event::ReservationReqFailed {
renewal, renewal,
error: non_fatal_error, error: non_fatal_error,
@ -456,33 +456,33 @@ impl ProtocolsHandler for Handler {
} }
OutboundOpenInfo::Connect { send_back } => { OutboundOpenInfo::Connect { send_back } => {
let non_fatal_error = match error { let non_fatal_error = match error {
ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout,
ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer,
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)) => ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( )) => ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)), )),
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Select( upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
), ),
)); ));
return; return;
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => { ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => {
match error { match error {
outbound_hop::UpgradeError::Fatal(error) => { outbound_hop::UpgradeError::Fatal(error) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::B(error)), upgrade::UpgradeError::Apply(EitherError::B(error)),
)); ));
return; return;
} }
outbound_hop::UpgradeError::CircuitFailed(error) => { outbound_hop::UpgradeError::CircuitFailed(error) => {
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(
error, error,
)) ))
} }
@ -497,7 +497,7 @@ impl ProtocolsHandler for Handler {
let _ = send_back.send(Err(())); let _ = send_back.send(Err(()));
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::OutboundCircuitReqFailed { Event::OutboundCircuitReqFailed {
error: non_fatal_error, error: non_fatal_error,
}, },
@ -514,7 +514,7 @@ impl ProtocolsHandler for Handler {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -524,7 +524,7 @@ impl ProtocolsHandler for Handler {
// Check for a pending (fatal) error. // Check for a pending (fatal) error.
if let Some(err) = self.pending_error.take() { if let Some(err) = self.pending_error.take() {
// The handler will not be polled again by the `Swarm`. // 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. // Return queued events.
@ -533,7 +533,7 @@ impl ProtocolsHandler for Handler {
} }
if let Poll::Ready(Some(protocol)) = self.reservation.poll(cx) { 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. // Deny incoming circuit requests.
@ -541,12 +541,12 @@ impl ProtocolsHandler for Handler {
{ {
match result { match result {
Ok(()) => { Ok(()) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::InboundCircuitReqDenied { src_peer_id }, Event::InboundCircuitReqDenied { src_peer_id },
)) ))
} }
Err(error) => { Err(error) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::InboundCircuitReqDenyFailed { src_peer_id, error }, Event::InboundCircuitReqDenyFailed { src_peer_id, error },
)) ))
} }

View File

@ -30,10 +30,10 @@ use instant::Instant;
use libp2p_core::connection::{ConnectedPoint, ConnectionId}; use libp2p_core::connection::{ConnectedPoint, ConnectionId};
use libp2p_core::multiaddr::Protocol; use libp2p_core::multiaddr::Protocol;
use libp2p_core::PeerId; use libp2p_core::PeerId;
use libp2p_swarm::protocols_handler::DummyProtocolsHandler; use libp2p_swarm::handler::DummyConnectionHandler;
use libp2p_swarm::{ use libp2p_swarm::{
NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, PollParameters, ConnectionHandlerUpgrErr, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler,
ProtocolsHandlerUpgrErr, PollParameters,
}; };
use std::collections::{hash_map, HashMap, HashSet, VecDeque}; use std::collections::{hash_map, HashMap, HashSet, VecDeque};
use std::num::NonZeroU32; use std::num::NonZeroU32;
@ -151,7 +151,7 @@ pub enum Event {
ReservationTimedOut { src_peer_id: PeerId }, ReservationTimedOut { src_peer_id: PeerId },
CircuitReqReceiveFailed { CircuitReqReceiveFailed {
src_peer_id: PeerId, src_peer_id: PeerId,
error: ProtocolsHandlerUpgrErr<void::Void>, error: ConnectionHandlerUpgrErr<void::Void>,
}, },
/// An inbound circuit request has been denied. /// An inbound circuit request has been denied.
CircuitReqDenied { CircuitReqDenied {
@ -173,7 +173,7 @@ pub enum Event {
CircuitReqOutboundConnectFailed { CircuitReqOutboundConnectFailed {
src_peer_id: PeerId, src_peer_id: PeerId,
dst_peer_id: PeerId, dst_peer_id: PeerId,
error: ProtocolsHandlerUpgrErr<outbound_stop::CircuitFailedReason>, error: ConnectionHandlerUpgrErr<outbound_stop::CircuitFailedReason>,
}, },
/// Accepting an inbound circuit request failed. /// Accepting an inbound circuit request failed.
CircuitReqAcceptFailed { CircuitReqAcceptFailed {
@ -216,10 +216,10 @@ impl Relay {
} }
impl NetworkBehaviour for Relay { impl NetworkBehaviour for Relay {
type ProtocolsHandler = handler::Prototype; type ConnectionHandler = handler::Prototype;
type OutEvent = Event; type OutEvent = Event;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
handler::Prototype { handler::Prototype {
config: handler::Config { config: handler::Config {
reservation_duration: self.config.reservation_duration, reservation_duration: self.config.reservation_duration,
@ -234,7 +234,7 @@ impl NetworkBehaviour for Relay {
peer: &PeerId, peer: &PeerId,
connection: &ConnectionId, connection: &ConnectionId,
_: &ConnectedPoint, _: &ConnectedPoint,
_handler: Either<handler::Handler, DummyProtocolsHandler>, _handler: Either<handler::Handler, DummyConnectionHandler>,
_remaining_established: usize, _remaining_established: usize,
) { ) {
if let hash_map::Entry::Occupied(mut peer) = self.reservations.entry(*peer) { if let hash_map::Entry::Occupied(mut peer) = self.reservations.entry(*peer) {
@ -283,7 +283,7 @@ impl NetworkBehaviour for Relay {
assert!( assert!(
!endpoint.is_relayed(), !endpoint.is_relayed(),
"`DummyProtocolsHandler` handles relayed connections. It \ "`DummyConnectionHandler` handles relayed connections. It \
denies all inbound substreams." denies all inbound substreams."
); );
@ -410,7 +410,7 @@ impl NetworkBehaviour for Relay {
assert!( assert!(
!endpoint.is_relayed(), !endpoint.is_relayed(),
"`DummyProtocolsHandler` handles relayed connections. It \ "`DummyConnectionHandler` handles relayed connections. It \
denies all inbound substreams." denies all inbound substreams."
); );
@ -622,7 +622,7 @@ impl NetworkBehaviour for Relay {
&mut self, &mut self,
_cx: &mut Context<'_>, _cx: &mut Context<'_>,
poll_parameters: &mut impl PollParameters, poll_parameters: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(action) = self.queued_actions.pop_front() { if let Some(action) = self.queued_actions.pop_front() {
return Poll::Ready(action.build(poll_parameters)); return Poll::Ready(action.build(poll_parameters));
} }

View File

@ -33,11 +33,11 @@ use instant::Instant;
use libp2p_core::connection::ConnectionId; use libp2p_core::connection::ConnectionId;
use libp2p_core::either::EitherError; use libp2p_core::either::EitherError;
use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId}; use libp2p_core::{upgrade, ConnectedPoint, Multiaddr, PeerId};
use libp2p_swarm::protocols_handler::{DummyProtocolsHandler, SendWrapper}; use libp2p_swarm::handler::{DummyConnectionHandler, SendWrapper};
use libp2p_swarm::protocols_handler::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend};
use libp2p_swarm::{ use libp2p_swarm::{
IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, KeepAlive, NegotiatedSubstream, SubstreamProtocol,
}; };
use std::collections::VecDeque; use std::collections::VecDeque;
use std::fmt; use std::fmt;
@ -167,7 +167,7 @@ pub enum Event {
}, },
/// Receiving an inbound circuit request failed. /// Receiving an inbound circuit request failed.
CircuitReqReceiveFailed { CircuitReqReceiveFailed {
error: ProtocolsHandlerUpgrErr<void::Void>, error: ConnectionHandlerUpgrErr<void::Void>,
}, },
/// An inbound circuit request has been denied. /// An inbound circuit request has been denied.
CircuitReqDenied { CircuitReqDenied {
@ -209,7 +209,7 @@ pub enum Event {
src_connection_id: ConnectionId, src_connection_id: ConnectionId,
inbound_circuit_req: inbound_hop::CircuitReq, inbound_circuit_req: inbound_hop::CircuitReq,
status: Status, status: Status,
error: ProtocolsHandlerUpgrErr<outbound_stop::CircuitFailedReason>, error: ConnectionHandlerUpgrErr<outbound_stop::CircuitFailedReason>,
}, },
/// An inbound circuit has closed. /// An inbound circuit has closed.
CircuitClosed { CircuitClosed {
@ -341,13 +341,13 @@ pub struct Prototype {
pub config: Config, pub config: Config,
} }
impl IntoProtocolsHandler for Prototype { impl IntoConnectionHandler for Prototype {
type Handler = Either<Handler, DummyProtocolsHandler>; type Handler = Either<Handler, DummyConnectionHandler>;
fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler { fn into_handler(self, _remote_peer_id: &PeerId, endpoint: &ConnectedPoint) -> Self::Handler {
if endpoint.is_relayed() { if endpoint.is_relayed() {
// Deny all substreams on relayed connection. // Deny all substreams on relayed connection.
Either::Right(DummyProtocolsHandler::default()) Either::Right(DummyConnectionHandler::default())
} else { } else {
Either::Left(Handler { Either::Left(Handler {
endpoint: endpoint.clone(), endpoint: endpoint.clone(),
@ -366,7 +366,7 @@ impl IntoProtocolsHandler for Prototype {
} }
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
upgrade::EitherUpgrade::A(SendWrapper(inbound_hop::Upgrade { upgrade::EitherUpgrade::A(SendWrapper(inbound_hop::Upgrade {
reservation_duration: self.config.reservation_duration, reservation_duration: self.config.reservation_duration,
max_circuit_duration: self.config.max_circuit_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. /// connection with a peer.
pub struct Handler { pub struct Handler {
endpoint: ConnectedPoint, endpoint: ConnectedPoint,
@ -385,17 +385,17 @@ pub struct Handler {
/// Queue of events to return when polled. /// Queue of events to return when polled.
queued_events: VecDeque< queued_events: VecDeque<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
<Self as ProtocolsHandler>::OutboundProtocol, <Self as ConnectionHandler>::OutboundProtocol,
<Self as ProtocolsHandler>::OutboundOpenInfo, <Self as ConnectionHandler>::OutboundOpenInfo,
<Self as ProtocolsHandler>::OutEvent, <Self as ConnectionHandler>::OutEvent,
<Self as ProtocolsHandler>::Error, <Self as ConnectionHandler>::Error,
>, >,
>, >,
/// A pending fatal error that results in the connection being closed. /// A pending fatal error that results in the connection being closed.
pending_error: Option< pending_error: Option<
ProtocolsHandlerUpgrErr< ConnectionHandlerUpgrErr<
EitherError<inbound_hop::FatalUpgradeError, outbound_stop::FatalUpgradeError>, EitherError<inbound_hop::FatalUpgradeError, outbound_stop::FatalUpgradeError>,
>, >,
>, >,
@ -429,10 +429,10 @@ pub struct Handler {
type Futures<T> = FuturesUnordered<BoxFuture<'static, T>>; type Futures<T> = FuturesUnordered<BoxFuture<'static, T>>;
impl ProtocolsHandler for Handler { impl ConnectionHandler for Handler {
type InEvent = In; type InEvent = In;
type OutEvent = Event; type OutEvent = Event;
type Error = ProtocolsHandlerUpgrErr< type Error = ConnectionHandlerUpgrErr<
EitherError<inbound_hop::FatalUpgradeError, outbound_stop::FatalUpgradeError>, EitherError<inbound_hop::FatalUpgradeError, outbound_stop::FatalUpgradeError>,
>; >;
type InboundProtocol = inbound_hop::Upgrade; type InboundProtocol = inbound_hop::Upgrade;
@ -458,7 +458,7 @@ impl ProtocolsHandler for Handler {
) { ) {
match request { match request {
inbound_hop::Req::Reserve(inbound_reservation_req) => { inbound_hop::Req::Reserve(inbound_reservation_req) => {
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::ReservationReqReceived { Event::ReservationReqReceived {
inbound_reservation_req, inbound_reservation_req,
endpoint: self.endpoint.clone(), endpoint: self.endpoint.clone(),
@ -467,7 +467,7 @@ impl ProtocolsHandler for Handler {
)); ));
} }
inbound_hop::Req::Connect(inbound_circuit_req) => { inbound_hop::Req::Connect(inbound_circuit_req) => {
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::CircuitReqReceived { Event::CircuitReqReceived {
inbound_circuit_req, inbound_circuit_req,
endpoint: self.endpoint.clone(), endpoint: self.endpoint.clone(),
@ -493,7 +493,7 @@ impl ProtocolsHandler for Handler {
let (tx, rx) = oneshot::channel(); let (tx, rx) = oneshot::channel();
self.alive_lend_out_substreams.push(rx); self.alive_lend_out_substreams.push(rx);
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::OutboundConnectNegotiated { Event::OutboundConnectNegotiated {
circuit_id, circuit_id,
src_peer_id, src_peer_id,
@ -530,7 +530,7 @@ impl ProtocolsHandler for Handler {
src_connection_id, src_connection_id,
} => { } => {
self.queued_events self.queued_events
.push_back(ProtocolsHandlerEvent::OutboundSubstreamRequest { .push_back(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new( protocol: SubstreamProtocol::new(
outbound_stop::Upgrade { outbound_stop::Upgrade {
relay_peer_id, relay_peer_id,
@ -589,35 +589,35 @@ impl ProtocolsHandler for Handler {
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
_: Self::InboundOpenInfo, _: Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
let non_fatal_error = match error { let non_fatal_error = match error {
ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout,
ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer,
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)) => ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( )) => ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)), )),
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)), upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)),
)); ));
return; return;
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(
inbound_hop::UpgradeError::Fatal(error), inbound_hop::UpgradeError::Fatal(error),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::A(error)), upgrade::UpgradeError::Apply(EitherError::A(error)),
)); ));
return; return;
} }
}; };
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::CircuitReqReceiveFailed { Event::CircuitReqReceiveFailed {
error: non_fatal_error, error: non_fatal_error,
}, },
@ -627,36 +627,36 @@ impl ProtocolsHandler for Handler {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
open_info: Self::OutboundOpenInfo, open_info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
let (non_fatal_error, status) = match error { let (non_fatal_error, status) = match error {
ProtocolsHandlerUpgrErr::Timeout => { ConnectionHandlerUpgrErr::Timeout => {
(ProtocolsHandlerUpgrErr::Timeout, Status::ConnectionFailed) (ConnectionHandlerUpgrErr::Timeout, Status::ConnectionFailed)
} }
ProtocolsHandlerUpgrErr::Timer => { ConnectionHandlerUpgrErr::Timer => {
(ProtocolsHandlerUpgrErr::Timer, Status::ConnectionFailed) (ConnectionHandlerUpgrErr::Timer, Status::ConnectionFailed)
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::Failed, upgrade::NegotiationError::Failed,
)) => { )) => {
// The remote has previously done a reservation. Doing a reservation but not // The remote has previously done a reservation. Doing a reservation but not
// supporting the stop protocol is pointless, thus disconnecting. // 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), upgrade::UpgradeError::Select(upgrade::NegotiationError::Failed),
)); ));
return; return;
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Select(
upgrade::NegotiationError::ProtocolError(e), upgrade::NegotiationError::ProtocolError(e),
)) => { )) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)), upgrade::UpgradeError::Select(upgrade::NegotiationError::ProtocolError(e)),
)); ));
return; return;
} }
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => match error { ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)) => match error {
outbound_stop::UpgradeError::Fatal(error) => { outbound_stop::UpgradeError::Fatal(error) => {
self.pending_error = Some(ProtocolsHandlerUpgrErr::Upgrade( self.pending_error = Some(ConnectionHandlerUpgrErr::Upgrade(
upgrade::UpgradeError::Apply(EitherError::B(error)), upgrade::UpgradeError::Apply(EitherError::B(error)),
)); ));
return; return;
@ -671,7 +671,7 @@ impl ProtocolsHandler for Handler {
} }
}; };
( (
ProtocolsHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)), ConnectionHandlerUpgrErr::Upgrade(upgrade::UpgradeError::Apply(error)),
status, status,
) )
} }
@ -685,7 +685,7 @@ impl ProtocolsHandler for Handler {
src_connection_id, src_connection_id,
} = open_info; } = open_info;
self.queued_events.push_back(ProtocolsHandlerEvent::Custom( self.queued_events.push_back(ConnectionHandlerEvent::Custom(
Event::OutboundConnectNegotiationFailed { Event::OutboundConnectNegotiationFailed {
circuit_id, circuit_id,
src_peer_id, src_peer_id,
@ -705,7 +705,7 @@ impl ProtocolsHandler for Handler {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -715,7 +715,7 @@ impl ProtocolsHandler for Handler {
// Check for a pending (fatal) error. // Check for a pending (fatal) error.
if let Some(err) = self.pending_error.take() { if let Some(err) = self.pending_error.take() {
// The handler will not be polled again by the `Swarm`. // 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. // Return queued events.
@ -728,14 +728,14 @@ impl ProtocolsHandler for Handler {
{ {
match result { match result {
Ok(()) => { Ok(()) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::CircuitClosed { return Poll::Ready(ConnectionHandlerEvent::Custom(Event::CircuitClosed {
circuit_id, circuit_id,
dst_peer_id, dst_peer_id,
error: None, error: None,
})) }))
} }
Err(e) => { Err(e) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::CircuitClosed { return Poll::Ready(ConnectionHandlerEvent::Custom(Event::CircuitClosed {
circuit_id, circuit_id,
dst_peer_id, dst_peer_id,
error: Some(e), error: Some(e),
@ -751,12 +751,12 @@ impl ProtocolsHandler for Handler {
.active_reservation .active_reservation
.replace(Delay::new(self.config.reservation_duration)) .replace(Delay::new(self.config.reservation_duration))
.is_some(); .is_some();
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::ReservationReqAccepted { renewed }, Event::ReservationReqAccepted { renewed },
)); ));
} }
Err(error) => { Err(error) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::ReservationReqAcceptFailed { error }, 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) { if let Poll::Ready(Some(result)) = self.reservation_deny_futures.poll_next_unpin(cx) {
match result { match result {
Ok(()) => { Ok(()) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::ReservationReqDenied {}, Event::ReservationReqDenied {},
)) ))
} }
Err(error) => { Err(error) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::ReservationReqDenyFailed { error }, Event::ReservationReqDenyFailed { error },
)); ));
} }
@ -819,13 +819,15 @@ impl ProtocolsHandler for Handler {
self.circuits.push(circuit); self.circuits.push(circuit);
return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::CircuitReqAccepted { return Poll::Ready(ConnectionHandlerEvent::Custom(
circuit_id, Event::CircuitReqAccepted {
dst_peer_id, circuit_id,
})); dst_peer_id,
},
));
} }
Err((circuit_id, dst_peer_id, error)) => { Err((circuit_id, dst_peer_id, error)) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::CircuitReqAcceptFailed { Event::CircuitReqAcceptFailed {
circuit_id, circuit_id,
dst_peer_id, dst_peer_id,
@ -841,13 +843,13 @@ impl ProtocolsHandler for Handler {
{ {
match result { match result {
Ok(()) => { Ok(()) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(Event::CircuitReqDenied { return Poll::Ready(ConnectionHandlerEvent::Custom(Event::CircuitReqDenied {
circuit_id, circuit_id,
dst_peer_id, dst_peer_id,
})); }));
} }
Err(error) => { Err(error) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
Event::CircuitReqDenyFailed { Event::CircuitReqDenyFailed {
circuit_id, circuit_id,
dst_peer_id, dst_peer_id,
@ -868,7 +870,9 @@ impl ProtocolsHandler for Handler {
.map(|fut| fut.poll_unpin(cx)) .map(|fut| fut.poll_unpin(cx))
{ {
self.active_reservation = None; 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() if self.reservation_accept_futures.is_empty()

View File

@ -34,7 +34,7 @@ use libp2p_kad::{GetClosestPeersOk, Kademlia, KademliaEvent, QueryResult};
use libp2p_ping as ping; use libp2p_ping as ping;
use libp2p_plaintext::PlainText2Config; use libp2p_plaintext::PlainText2Config;
use libp2p_relay::v1::{new_transport_and_behaviour, Relay, RelayConfig}; use libp2p_relay::v1::{new_transport_and_behaviour, Relay, RelayConfig};
use libp2p_swarm::protocols_handler::KeepAlive; use libp2p_swarm::handler::KeepAlive;
use libp2p_swarm::{ use libp2p_swarm::{
DialError, DummyBehaviour, NetworkBehaviour, NetworkBehaviourAction, DialError, DummyBehaviour, NetworkBehaviour, NetworkBehaviourAction,
NetworkBehaviourEventProcess, PollParameters, Swarm, SwarmEvent, NetworkBehaviourEventProcess, PollParameters, Swarm, SwarmEvent,
@ -1162,7 +1162,7 @@ impl CombinedBehaviour {
&mut self, &mut self,
_: &mut Context, _: &mut Context,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<CombinedEvent, <Self as NetworkBehaviour>::ProtocolsHandler>> ) -> Poll<NetworkBehaviourAction<CombinedEvent, <Self as NetworkBehaviour>::ConnectionHandler>>
{ {
if !self.events.is_empty() { if !self.events.is_empty() {
return Poll::Ready(NetworkBehaviourAction::GenerateEvent(self.events.remove(0))); return Poll::Ready(NetworkBehaviourAction::GenerateEvent(self.events.remove(0)));

View File

@ -22,7 +22,7 @@ use crate::codec::{Cookie, ErrorCode, Namespace, NewRegistration, Registration,
use crate::handler; use crate::handler;
use crate::handler::outbound; use crate::handler::outbound;
use crate::handler::outbound::OpenInfo; use crate::handler::outbound::OpenInfo;
use crate::substream_handler::SubstreamProtocolsHandler; use crate::substream_handler::SubstreamConnectionHandler;
use futures::future::BoxFuture; use futures::future::BoxFuture;
use futures::future::FutureExt; use futures::future::FutureExt;
use futures::stream::FuturesUnordered; use futures::stream::FuturesUnordered;
@ -43,7 +43,7 @@ pub struct Behaviour {
events: VecDeque< events: VecDeque<
NetworkBehaviourAction< NetworkBehaviourAction<
Event, Event,
SubstreamProtocolsHandler<void::Void, outbound::Stream, outbound::OpenInfo>, SubstreamConnectionHandler<void::Void, outbound::Stream, outbound::OpenInfo>,
>, >,
>, >,
keypair: Keypair, keypair: Keypair,
@ -164,14 +164,14 @@ pub enum Event {
} }
impl NetworkBehaviour for Behaviour { impl NetworkBehaviour for Behaviour {
type ProtocolsHandler = type ConnectionHandler =
SubstreamProtocolsHandler<void::Void, outbound::Stream, outbound::OpenInfo>; SubstreamConnectionHandler<void::Void, outbound::Stream, outbound::OpenInfo>;
type OutEvent = Event; 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); 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<Multiaddr> { fn addresses_of_peer(&mut self, peer: &PeerId) -> Vec<Multiaddr> {
@ -215,7 +215,7 @@ impl NetworkBehaviour for Behaviour {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
poll_params: &mut impl PollParameters, poll_params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(event) = self.events.pop_front() { if let Some(event) = self.events.pop_front() {
return Poll::Ready(event); return Poll::Ready(event);
} }
@ -275,7 +275,7 @@ fn handle_outbound_event(
) -> Vec< ) -> Vec<
NetworkBehaviourAction< NetworkBehaviourAction<
Event, Event,
SubstreamProtocolsHandler<void::Void, outbound::Stream, outbound::OpenInfo>, SubstreamConnectionHandler<void::Void, outbound::Stream, outbound::OpenInfo>,
>, >,
> { > {
match event { match event {

View File

@ -20,7 +20,7 @@
use crate::codec::{Cookie, ErrorCode, Namespace, NewRegistration, Registration, Ttl}; use crate::codec::{Cookie, ErrorCode, Namespace, NewRegistration, Registration, Ttl};
use crate::handler::inbound; use crate::handler::inbound;
use crate::substream_handler::{InboundSubstreamId, SubstreamProtocolsHandler}; use crate::substream_handler::{InboundSubstreamId, SubstreamConnectionHandler};
use crate::{handler, MAX_TTL, MIN_TTL}; use crate::{handler, MAX_TTL, MIN_TTL};
use bimap::BiMap; use bimap::BiMap;
use futures::future::BoxFuture; use futures::future::BoxFuture;
@ -40,7 +40,7 @@ use void::Void;
pub struct Behaviour { pub struct Behaviour {
events: VecDeque< events: VecDeque<
NetworkBehaviourAction<Event, SubstreamProtocolsHandler<inbound::Stream, Void, ()>>, NetworkBehaviourAction<Event, SubstreamConnectionHandler<inbound::Stream, Void, ()>>,
>, >,
registrations: Registrations, registrations: Registrations,
} }
@ -109,13 +109,13 @@ pub enum Event {
} }
impl NetworkBehaviour for Behaviour { impl NetworkBehaviour for Behaviour {
type ProtocolsHandler = SubstreamProtocolsHandler<inbound::Stream, Void, ()>; type ConnectionHandler = SubstreamConnectionHandler<inbound::Stream, Void, ()>;
type OutEvent = Event; 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); 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( fn inject_event(
@ -147,7 +147,7 @@ impl NetworkBehaviour for Behaviour {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Poll::Ready(ExpiredRegistration(registration)) = self.registrations.poll(cx) { if let Poll::Ready(ExpiredRegistration(registration)) = self.registrations.poll(cx) {
return Poll::Ready(NetworkBehaviourAction::GenerateEvent( return Poll::Ready(NetworkBehaviourAction::GenerateEvent(
Event::RegistrationExpired(registration), Event::RegistrationExpired(registration),
@ -168,7 +168,7 @@ fn handle_inbound_event(
connection: ConnectionId, connection: ConnectionId,
id: InboundSubstreamId, id: InboundSubstreamId,
registrations: &mut Registrations, registrations: &mut Registrations,
) -> Vec<NetworkBehaviourAction<Event, SubstreamProtocolsHandler<inbound::Stream, Void, ()>>> { ) -> Vec<NetworkBehaviourAction<Event, SubstreamConnectionHandler<inbound::Stream, Void, ()>>> {
match event { match event {
// bad registration // bad registration
inbound::OutEvent::RegistrationRequested(registration) inbound::OutEvent::RegistrationRequested(registration)

View File

@ -18,7 +18,7 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // 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. //! 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. //! 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 futures::FutureExt;
use instant::Instant; use instant::Instant;
use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use libp2p_core::{InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use libp2p_swarm::protocols_handler::{InboundUpgradeSend, OutboundUpgradeSend}; use libp2p_swarm::handler::{InboundUpgradeSend, OutboundUpgradeSend};
use libp2p_swarm::{ use libp2p_swarm::{
KeepAlive, NegotiatedSubstream, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
ProtocolsHandlerUpgrErr, SubstreamProtocol, NegotiatedSubstream, SubstreamProtocol,
}; };
use std::collections::{HashMap, VecDeque}; use std::collections::{HashMap, VecDeque};
use std::fmt; use std::fmt;
@ -172,8 +172,8 @@ impl<C: Send + 'static> OutboundUpgrade<C> for PassthroughProtocol {
} }
} }
/// An implementation of [`ProtocolsHandler`] that delegates to individual [`SubstreamHandler`]s. /// An implementation of [`ConnectionHandler`] that delegates to individual [`SubstreamHandler`]s.
pub struct SubstreamProtocolsHandler<TInboundSubstream, TOutboundSubstream, TOutboundOpenInfo> { pub struct SubstreamConnectionHandler<TInboundSubstream, TOutboundSubstream, TOutboundOpenInfo> {
inbound_substreams: HashMap<InboundSubstreamId, TInboundSubstream>, inbound_substreams: HashMap<InboundSubstreamId, TInboundSubstream>,
outbound_substreams: HashMap<OutboundSubstreamId, TOutboundSubstream>, outbound_substreams: HashMap<OutboundSubstreamId, TOutboundSubstream>,
next_inbound_substream_id: InboundSubstreamId, next_inbound_substream_id: InboundSubstreamId,
@ -185,7 +185,7 @@ pub struct SubstreamProtocolsHandler<TInboundSubstream, TOutboundSubstream, TOut
} }
impl<TInboundSubstream, TOutboundSubstream, TOutboundOpenInfo> impl<TInboundSubstream, TOutboundSubstream, TOutboundOpenInfo>
SubstreamProtocolsHandler<TInboundSubstream, TOutboundSubstream, TOutboundOpenInfo> SubstreamConnectionHandler<TInboundSubstream, TOutboundSubstream, TOutboundOpenInfo>
{ {
pub fn new(initial_keep_alive: Duration) -> Self { pub fn new(initial_keep_alive: Duration) -> Self {
Self { Self {
@ -200,7 +200,7 @@ impl<TInboundSubstream, TOutboundSubstream, TOutboundOpenInfo>
} }
impl<TOutboundSubstream, TOutboundOpenInfo> impl<TOutboundSubstream, TOutboundOpenInfo>
SubstreamProtocolsHandler<void::Void, TOutboundSubstream, TOutboundOpenInfo> SubstreamConnectionHandler<void::Void, TOutboundSubstream, TOutboundOpenInfo>
{ {
pub fn new_outbound_only(initial_keep_alive: Duration) -> Self { pub fn new_outbound_only(initial_keep_alive: Duration) -> Self {
Self { Self {
@ -215,7 +215,7 @@ impl<TOutboundSubstream, TOutboundOpenInfo>
} }
impl<TInboundSubstream, TOutboundOpenInfo> impl<TInboundSubstream, TOutboundOpenInfo>
SubstreamProtocolsHandler<TInboundSubstream, void::Void, TOutboundOpenInfo> SubstreamConnectionHandler<TInboundSubstream, void::Void, TOutboundOpenInfo>
{ {
pub fn new_inbound_only(initial_keep_alive: Duration) -> Self { pub fn new_inbound_only(initial_keep_alive: Duration) -> Self {
Self { Self {
@ -231,7 +231,7 @@ impl<TInboundSubstream, TOutboundOpenInfo>
/// Poll all substreams within the given HashMap. /// 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<TId, TSubstream, TError, TOutEvent>( fn poll_substreams<TId, TSubstream, TError, TOutEvent>(
substreams: &mut HashMap<TId, TSubstream>, substreams: &mut HashMap<TId, TSubstream>,
cx: &mut Context<'_>, cx: &mut Context<'_>,
@ -273,7 +273,7 @@ where
Poll::Pending Poll::Pending
} }
/// Event sent from the [`libp2p_swarm::NetworkBehaviour`] to the [`SubstreamProtocolsHandler`]. /// Event sent from the [`libp2p_swarm::NetworkBehaviour`] to the [`SubstreamConnectionHandler`].
#[derive(Debug)] #[derive(Debug)]
pub enum InEvent<I, TInboundEvent, TOutboundEvent> { pub enum InEvent<I, TInboundEvent, TOutboundEvent> {
/// Open a new substream using the provided `open_info`. /// Open a new substream using the provided `open_info`.
@ -290,7 +290,7 @@ pub enum InEvent<I, TInboundEvent, TOutboundEvent> {
}, },
} }
/// Event produced by the [`SubstreamProtocolsHandler`] for the corresponding [`libp2p_swarm::NetworkBehaviour`]. /// Event produced by the [`SubstreamConnectionHandler`] for the corresponding [`libp2p_swarm::NetworkBehaviour`].
#[derive(Debug)] #[derive(Debug)]
pub enum OutEvent<TInbound, TOutbound, TInboundError, TOutboundError> { pub enum OutEvent<TInbound, TOutbound, TInboundError, TOutboundError> {
/// An inbound substream produced an event. /// An inbound substream produced an event.
@ -325,8 +325,8 @@ impl<
TOutboundError, TOutboundError,
TInboundSubstreamHandler, TInboundSubstreamHandler,
TOutboundSubstreamHandler, TOutboundSubstreamHandler,
> ProtocolsHandler > ConnectionHandler
for SubstreamProtocolsHandler< for SubstreamConnectionHandler<
TInboundSubstreamHandler, TInboundSubstreamHandler,
TOutboundSubstreamHandler, TOutboundSubstreamHandler,
TOutboundOpenInfo, TOutboundOpenInfo,
@ -421,7 +421,7 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
_: Self::OutboundOpenInfo, _: Self::OutboundOpenInfo,
_: ProtocolsHandlerUpgrErr<Void>, _: ConnectionHandlerUpgrErr<Void>,
) { ) {
// TODO: Handle upgrade errors properly // TODO: Handle upgrade errors properly
} }
@ -447,7 +447,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -455,20 +455,20 @@ where
>, >,
> { > {
if let Some(open_info) = self.new_substreams.pop_front() { 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), protocol: TOutboundSubstreamHandler::upgrade(open_info),
}); });
} }
match poll_substreams(&mut self.inbound_substreams, cx) { match poll_substreams(&mut self.inbound_substreams, cx) {
Poll::Ready(Ok((id, message))) => { Poll::Ready(Ok((id, message))) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(OutEvent::InboundEvent { return Poll::Ready(ConnectionHandlerEvent::Custom(OutEvent::InboundEvent {
id, id,
message, message,
})) }))
} }
Poll::Ready(Err((id, error))) => { Poll::Ready(Err((id, error))) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(OutEvent::InboundError { return Poll::Ready(ConnectionHandlerEvent::Custom(OutEvent::InboundError {
id, id,
error, error,
})) }))
@ -478,13 +478,13 @@ where
match poll_substreams(&mut self.outbound_substreams, cx) { match poll_substreams(&mut self.outbound_substreams, cx) {
Poll::Ready(Ok((id, message))) => { Poll::Ready(Ok((id, message))) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(OutEvent::OutboundEvent { return Poll::Ready(ConnectionHandlerEvent::Custom(OutEvent::OutboundEvent {
id, id,
message, message,
})) }))
} }
Poll::Ready(Err((id, error))) => { Poll::Ready(Err((id, error))) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(OutEvent::OutboundError { return Poll::Ready(ConnectionHandlerEvent::Custom(OutEvent::OutboundError {
id, id,
error, error,
})) }))

View File

@ -29,9 +29,7 @@ use futures::{channel::oneshot, future::BoxFuture, prelude::*, stream::FuturesUn
use instant::Instant; use instant::Instant;
use libp2p_core::upgrade::{NegotiationError, UpgradeError}; use libp2p_core::upgrade::{NegotiationError, UpgradeError};
use libp2p_swarm::{ use libp2p_swarm::{
protocols_handler::{ handler::{ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive},
KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr,
},
SubstreamProtocol, SubstreamProtocol,
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
@ -65,7 +63,7 @@ where
/// The current connection keep-alive. /// The current connection keep-alive.
keep_alive: KeepAlive, keep_alive: KeepAlive,
/// A pending fatal error that results in the connection being closed. /// A pending fatal error that results in the connection being closed.
pending_error: Option<ProtocolsHandlerUpgrErr<io::Error>>, pending_error: Option<ConnectionHandlerUpgrErr<io::Error>>,
/// Queue of events to emit in `poll()`. /// Queue of events to emit in `poll()`.
pending_events: VecDeque<RequestResponseHandlerEvent<TCodec>>, pending_events: VecDeque<RequestResponseHandlerEvent<TCodec>>,
/// Outbound upgrades waiting to be emitted as an `OutboundSubstreamRequest`. /// Outbound upgrades waiting to be emitted as an `OutboundSubstreamRequest`.
@ -192,13 +190,13 @@ impl<TCodec: RequestResponseCodec> fmt::Debug for RequestResponseHandlerEvent<TC
} }
} }
impl<TCodec> ProtocolsHandler for RequestResponseHandler<TCodec> impl<TCodec> ConnectionHandler for RequestResponseHandler<TCodec>
where where
TCodec: RequestResponseCodec + Send + Clone + 'static, TCodec: RequestResponseCodec + Send + Clone + 'static,
{ {
type InEvent = RequestProtocol<TCodec>; type InEvent = RequestProtocol<TCodec>;
type OutEvent = RequestResponseHandlerEvent<TCodec>; type OutEvent = RequestResponseHandlerEvent<TCodec>;
type Error = ProtocolsHandlerUpgrErr<io::Error>; type Error = ConnectionHandlerUpgrErr<io::Error>;
type InboundProtocol = ResponseProtocol<TCodec>; type InboundProtocol = ResponseProtocol<TCodec>;
type OutboundProtocol = RequestProtocol<TCodec>; type OutboundProtocol = RequestProtocol<TCodec>;
type OutboundOpenInfo = RequestId; type OutboundOpenInfo = RequestId;
@ -268,14 +266,14 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
info: RequestId, info: RequestId,
error: ProtocolsHandlerUpgrErr<io::Error>, error: ConnectionHandlerUpgrErr<io::Error>,
) { ) {
match error { match error {
ProtocolsHandlerUpgrErr::Timeout => { ConnectionHandlerUpgrErr::Timeout => {
self.pending_events self.pending_events
.push_back(RequestResponseHandlerEvent::OutboundTimeout(info)); .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. // The remote merely doesn't support the protocol(s) we requested.
// This is no reason to close the connection, which may // This is no reason to close the connection, which may
// successfully communicate with other protocols already. // successfully communicate with other protocols already.
@ -296,13 +294,13 @@ where
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
info: RequestId, info: RequestId,
error: ProtocolsHandlerUpgrErr<io::Error>, error: ConnectionHandlerUpgrErr<io::Error>,
) { ) {
match error { match error {
ProtocolsHandlerUpgrErr::Timeout => self ConnectionHandlerUpgrErr::Timeout => self
.pending_events .pending_events
.push_back(RequestResponseHandlerEvent::InboundTimeout(info)), .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. // The local peer merely doesn't support the protocol(s) requested.
// This is no reason to close the connection, which may // This is no reason to close the connection, which may
// successfully communicate with other protocols already. // successfully communicate with other protocols already.
@ -327,17 +325,17 @@ where
fn poll( fn poll(
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll<ProtocolsHandlerEvent<RequestProtocol<TCodec>, RequestId, Self::OutEvent, Self::Error>> ) -> Poll<ConnectionHandlerEvent<RequestProtocol<TCodec>, RequestId, Self::OutEvent, Self::Error>>
{ {
// Check for a pending (fatal) error. // Check for a pending (fatal) error.
if let Some(err) = self.pending_error.take() { if let Some(err) = self.pending_error.take() {
// The handler will not be polled again by the `Swarm`. // 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. // Drain pending events.
if let Some(event) = self.pending_events.pop_front() { 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 { } else if self.pending_events.capacity() > EMPTY_QUEUE_SHRINK_THRESHOLD {
self.pending_events.shrink_to_fit(); self.pending_events.shrink_to_fit();
} }
@ -348,7 +346,7 @@ where
Ok(((id, rq), rs_sender)) => { Ok(((id, rq), rs_sender)) => {
// We received an inbound request. // We received an inbound request.
self.keep_alive = KeepAlive::Yes; self.keep_alive = KeepAlive::Yes;
return Poll::Ready(ProtocolsHandlerEvent::Custom( return Poll::Ready(ConnectionHandlerEvent::Custom(
RequestResponseHandlerEvent::Request { RequestResponseHandlerEvent::Request {
request_id: id, request_id: id,
request: rq, request: rq,
@ -367,7 +365,7 @@ where
// Emit outbound requests. // Emit outbound requests.
if let Some(request) = self.outbound.pop_front() { if let Some(request) = self.outbound.pop_front() {
let info = request.request_id; let info = request.request_id;
return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new(request, info) protocol: SubstreamProtocol::new(request, info)
.with_timeout(self.substream_timeout), .with_timeout(self.substream_timeout),
}); });

View File

@ -67,7 +67,7 @@ use handler::{RequestProtocol, RequestResponseHandler, RequestResponseHandlerEve
use libp2p_core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId}; use libp2p_core::{connection::ConnectionId, ConnectedPoint, Multiaddr, PeerId};
use libp2p_swarm::{ use libp2p_swarm::{
dial_opts::{self, DialOpts}, dial_opts::{self, DialOpts},
DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler, DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction, NotifyHandler,
PollParameters, PollParameters,
}; };
use smallvec::SmallVec; use smallvec::SmallVec;
@ -567,10 +567,10 @@ impl<TCodec> NetworkBehaviour for RequestResponse<TCodec>
where where
TCodec: RequestResponseCodec + Send + Clone + 'static, TCodec: RequestResponseCodec + Send + Clone + 'static,
{ {
type ProtocolsHandler = RequestResponseHandler<TCodec>; type ConnectionHandler = RequestResponseHandler<TCodec>;
type OutEvent = RequestResponseEvent<TCodec::Request, TCodec::Response>; type OutEvent = RequestResponseEvent<TCodec::Request, TCodec::Response>;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
RequestResponseHandler::new( RequestResponseHandler::new(
self.inbound_protocols.clone(), self.inbound_protocols.clone(),
self.codec.clone(), self.codec.clone(),
@ -646,7 +646,7 @@ where
peer_id: &PeerId, peer_id: &PeerId,
conn: &ConnectionId, conn: &ConnectionId,
_: &ConnectedPoint, _: &ConnectedPoint,
_: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, _: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
let connections = self let connections = self
@ -691,7 +691,7 @@ where
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
peer: Option<PeerId>, peer: Option<PeerId>,
_: Self::ProtocolsHandler, _: Self::ConnectionHandler,
_: &DialError, _: &DialError,
) { ) {
if let Some(peer) = peer { if let Some(peer) = peer {
@ -872,7 +872,7 @@ where
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(ev) = self.pending_events.pop_front() { if let Some(ev) = self.pending_events.pop_front() {
return Poll::Ready(ev); return Poll::Ready(ev);
} else if self.pending_events.capacity() > EMPTY_QUEUE_SHRINK_THRESHOLD { } else if self.pending_events.capacity() > EMPTY_QUEUE_SHRINK_THRESHOLD {

View File

@ -50,9 +50,9 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream {
let net_behv_event_proc = quote! {::libp2p::swarm::NetworkBehaviourEventProcess}; let net_behv_event_proc = quote! {::libp2p::swarm::NetworkBehaviourEventProcess};
let either_ident = quote! {::libp2p::core::either::EitherOutput}; let either_ident = quote! {::libp2p::core::either::EitherOutput};
let network_behaviour_action = quote! {::libp2p::swarm::NetworkBehaviourAction}; let network_behaviour_action = quote! {::libp2p::swarm::NetworkBehaviourAction};
let into_protocols_handler = quote! {::libp2p::swarm::IntoProtocolsHandler}; let into_protocols_handler = quote! {::libp2p::swarm::IntoConnectionHandler};
let protocols_handler = quote! {::libp2p::swarm::ProtocolsHandler}; let protocols_handler = quote! {::libp2p::swarm::ConnectionHandler};
let into_proto_select_ident = quote! {::libp2p::swarm::IntoProtocolsHandlerSelect}; let into_proto_select_ident = quote! {::libp2p::swarm::IntoConnectionHandlerSelect};
let peer_id = quote! {::libp2p::core::PeerId}; let peer_id = quote! {::libp2p::core::PeerId};
let connection_id = quote! {::libp2p::core::connection::ConnectionId}; let connection_id = quote! {::libp2p::core::connection::ConnectionId};
let dial_errors = quote! {Option<&Vec<::libp2p::core::Multiaddr>>}; 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 protocols_handler_ty = {
let mut ph_ty = None; let mut ph_ty = None;
for field in data_struct.fields.iter() { for field in data_struct.fields.iter() {
@ -439,7 +439,7 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream {
continue; continue;
} }
let ty = &field.ty; 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 { match ph_ty {
Some(ev) => ph_ty = Some(quote! { #into_proto_select_ident<#ev, #field_info> }), Some(ev) => ph_ty = Some(quote! { #into_proto_select_ident<#ev, #field_info> }),
ref mut ev @ None => *ev = Some(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 impl #impl_generics #trait_to_impl for #name #ty_generics
#where_clause #where_clause
{ {
type ProtocolsHandler = #protocols_handler_ty; type ConnectionHandler = #protocols_handler_ty;
type OutEvent = #out_event; type OutEvent = #out_event;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
use #into_protocols_handler; use #into_protocols_handler;
#new_handler #new_handler
} }
@ -623,15 +623,15 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream {
#(#inject_address_change_stmts);* #(#inject_address_change_stmts);*
} }
fn inject_connection_closed(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, endpoint: &#connected_point, handlers: <Self::ProtocolsHandler as #into_protocols_handler>::Handler, remaining_established: usize) { fn inject_connection_closed(&mut self, peer_id: &#peer_id, connection_id: &#connection_id, endpoint: &#connected_point, handlers: <Self::ConnectionHandler as #into_protocols_handler>::Handler, remaining_established: usize) {
#(#inject_connection_closed_stmts);* #(#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);* #(#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);* #(#inject_listen_failure_stmts);*
} }
@ -667,17 +667,17 @@ fn build_struct(ast: &DeriveInput, data_struct: &DataStruct) -> TokenStream {
&mut self, &mut self,
peer_id: #peer_id, peer_id: #peer_id,
connection_id: #connection_id, connection_id: #connection_id,
event: <<Self::ProtocolsHandler as #into_protocols_handler>::Handler as #protocols_handler>::OutEvent event: <<Self::ConnectionHandler as #into_protocols_handler>::Handler as #protocols_handler>::OutEvent
) { ) {
match event { match event {
#(#inject_node_event_stmts),* #(#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<Self::OutEvent, Self::ProtocolsHandler>> { fn poll(&mut self, cx: &mut std::task::Context, poll_params: &mut impl #poll_parameters) -> std::task::Poll<#network_behaviour_action<Self::OutEvent, Self::ConnectionHandler>> {
use libp2p::futures::prelude::*; use libp2p::futures::prelude::*;
#(#poll_stmts)* #(#poll_stmts)*
let f: std::task::Poll<#network_behaviour_action<Self::OutEvent, Self::ProtocolsHandler>> = #poll_method; let f: std::task::Poll<#network_behaviour_action<Self::OutEvent, Self::ConnectionHandler>> = #poll_method;
f f
} }
} }

View File

@ -160,7 +160,7 @@ fn custom_polling() {
) -> std::task::Poll< ) -> std::task::Poll<
libp2p::swarm::NetworkBehaviourAction< libp2p::swarm::NetworkBehaviourAction<
<Self as NetworkBehaviour>::OutEvent, <Self as NetworkBehaviour>::OutEvent,
<Self as NetworkBehaviour>::ProtocolsHandler, <Self as NetworkBehaviour>::ConnectionHandler,
>, >,
> { > {
std::task::Poll::Pending std::task::Poll::Pending
@ -223,7 +223,7 @@ fn custom_event_and_polling() {
) -> std::task::Poll< ) -> std::task::Poll<
libp2p::swarm::NetworkBehaviourAction< libp2p::swarm::NetworkBehaviourAction<
<Self as NetworkBehaviour>::OutEvent, <Self as NetworkBehaviour>::OutEvent,
<Self as NetworkBehaviour>::ProtocolsHandler, <Self as NetworkBehaviour>::ConnectionHandler,
>, >,
> { > {
std::task::Poll::Pending std::task::Poll::Pending

View File

@ -1,5 +1,9 @@
# 0.34.0 [unreleased] # 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]. - Fold `libp2p-core`'s `Network` into `Swarm`. See [PR 2492].
- Update to `libp2p-core` `v0.32.0`. - Update to `libp2p-core` `v0.32.0`.
@ -10,6 +14,7 @@
[PR 2492]: https://github.com/libp2p/rust-libp2p/pull/2492 [PR 2492]: https://github.com/libp2p/rust-libp2p/pull/2492
[PR 2517]: https://github.com/libp2p/rust-libp2p/pull/2517 [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] # 0.33.0 [2022-01-27]

View File

@ -22,7 +22,7 @@ pub mod either;
pub mod toggle; pub mod toggle;
use crate::dial_opts::DialOpts; use crate::dial_opts::DialOpts;
use crate::protocols_handler::{IntoProtocolsHandler, ProtocolsHandler}; use crate::handler::{ConnectionHandler, IntoConnectionHandler};
use crate::{AddressRecord, AddressScore, DialError}; use crate::{AddressRecord, AddressScore, DialError};
use libp2p_core::{ use libp2p_core::{
connection::{ConnectionId, ListenerId}, connection::{ConnectionId, ListenerId},
@ -30,12 +30,12 @@ use libp2p_core::{
}; };
use std::{task::Context, task::Poll}; 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<THandler> = pub(crate) type THandlerInEvent<THandler> =
<<THandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent; <<THandler as IntoConnectionHandler>::Handler as ConnectionHandler>::InEvent;
pub(crate) type THandlerOutEvent<THandler> = pub(crate) type THandlerOutEvent<THandler> =
<<THandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent; <<THandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent;
/// A [`NetworkBehaviour`] defines the behaviour of the local node on the network. /// A [`NetworkBehaviour`] defines the behaviour of the local node on the network.
/// ///
@ -167,12 +167,12 @@ pub(crate) type THandlerOutEvent<THandler> =
/// function and will be called last within the generated [`NetworkBehaviour`] implementation. /// function and will be called last within the generated [`NetworkBehaviour`] implementation.
pub trait NetworkBehaviour: Send + 'static { pub trait NetworkBehaviour: Send + 'static {
/// Handler for all the protocols the network behaviour supports. /// 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. /// Event generated by the `NetworkBehaviour` and that the swarm will report back.
type OutEvent: Send + 'static; 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`] /// Every time an incoming connection is opened, and every time another [`NetworkBehaviour`]
/// emitted a dial request, this method is called. /// 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 /// Note that the handler is returned to the [`NetworkBehaviour`] on connection failure and
/// connection closing. /// 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 /// Addresses that this behaviour is aware of for this specific peer, and that may allow
/// reaching the peer. /// reaching the peer.
@ -221,7 +221,7 @@ pub trait NetworkBehaviour: Send + 'static {
_: &PeerId, _: &PeerId,
_: &ConnectionId, _: &ConnectionId,
_: &ConnectedPoint, _: &ConnectedPoint,
_: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, _: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
_remaining_established: usize, _remaining_established: usize,
) { ) {
} }
@ -245,14 +245,14 @@ pub trait NetworkBehaviour: Send + 'static {
&mut self, &mut self,
peer_id: PeerId, peer_id: PeerId,
connection: ConnectionId, connection: ConnectionId,
event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent, event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
); );
/// Indicates to the behaviour that the dial to a known or unknown node failed. /// Indicates to the behaviour that the dial to a known or unknown node failed.
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
_peer_id: Option<PeerId>, _peer_id: Option<PeerId>,
_handler: Self::ProtocolsHandler, _handler: Self::ConnectionHandler,
_error: &DialError, _error: &DialError,
) { ) {
} }
@ -266,7 +266,7 @@ pub trait NetworkBehaviour: Send + 'static {
&mut self, &mut self,
_local_addr: &Multiaddr, _local_addr: &Multiaddr,
_send_back_addr: &Multiaddr, _send_back_addr: &Multiaddr,
_handler: Self::ProtocolsHandler, _handler: Self::ConnectionHandler,
) { ) {
} }
@ -301,7 +301,7 @@ pub trait NetworkBehaviour: Send + 'static {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
params: &mut impl PollParameters, params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>>; ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>>;
} }
/// Parameters passed to `poll()`, that the `NetworkBehaviour` has access to. /// Parameters passed to `poll()`, that the `NetworkBehaviour` has access to.
@ -353,7 +353,7 @@ pub trait NetworkBehaviourEventProcess<TEvent> {
#[derive(Debug)] #[derive(Debug)]
pub enum NetworkBehaviourAction< pub enum NetworkBehaviourAction<
TOutEvent, TOutEvent,
THandler: IntoProtocolsHandler, THandler: IntoConnectionHandler,
TInEvent = THandlerInEvent<THandler>, TInEvent = THandlerInEvent<THandler>,
> { > {
/// Instructs the `Swarm` to return an event when it is being polled. /// 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::core::PeerId;
/// # use libp2p::plaintext::PlainText2Config; /// # use libp2p::plaintext::PlainText2Config;
/// # use libp2p::swarm::{ /// # use libp2p::swarm::{
/// # DialError, IntoProtocolsHandler, KeepAlive, NegotiatedSubstream, /// # DialError, IntoConnectionHandler, KeepAlive, NegotiatedSubstream,
/// # NetworkBehaviour, NetworkBehaviourAction, PollParameters, ProtocolsHandler, /// # NetworkBehaviour, NetworkBehaviourAction, PollParameters, ConnectionHandler,
/// # ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, Swarm, SwarmEvent, /// # ConnectionHandlerEvent, ConnectionHandlerUpgrErr, SubstreamProtocol, Swarm, SwarmEvent,
/// # }; /// # };
/// # use libp2p::swarm::dial_opts::{DialOpts, PeerCondition}; /// # use libp2p::swarm::dial_opts::{DialOpts, PeerCondition};
/// # use libp2p::yamux; /// # use libp2p::yamux;
@ -439,10 +439,10 @@ pub enum NetworkBehaviourAction<
/// } /// }
/// # /// #
/// impl NetworkBehaviour for MyBehaviour { /// impl NetworkBehaviour for MyBehaviour {
/// # type ProtocolsHandler = MyHandler; /// # type ConnectionHandler = MyHandler;
/// # type OutEvent = PreciousMessage; /// # type OutEvent = PreciousMessage;
/// # /// #
/// # fn new_handler(&mut self) -> Self::ProtocolsHandler { /// # fn new_handler(&mut self) -> Self::ConnectionHandler {
/// # MyHandler { message: None } /// # MyHandler { message: None }
/// # } /// # }
/// # /// #
@ -451,7 +451,7 @@ pub enum NetworkBehaviourAction<
/// # &mut self, /// # &mut self,
/// # _: PeerId, /// # _: PeerId,
/// # _: ConnectionId, /// # _: ConnectionId,
/// # _: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent, /// # _: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
/// # ) { /// # ) {
/// # unreachable!(); /// # unreachable!();
/// # } /// # }
@ -459,7 +459,7 @@ pub enum NetworkBehaviourAction<
/// fn inject_dial_failure( /// fn inject_dial_failure(
/// &mut self, /// &mut self,
/// _: Option<PeerId>, /// _: Option<PeerId>,
/// handler: Self::ProtocolsHandler, /// handler: Self::ConnectionHandler,
/// _: &DialError, /// _: &DialError,
/// ) { /// ) {
/// // As expected, sending the message failed. But lucky us, we got the handler back, thus /// // 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 self,
/// # _: &mut Context<'_>, /// # _: &mut Context<'_>,
/// # _: &mut impl PollParameters, /// # _: &mut impl PollParameters,
/// # ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { /// # ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
/// # if let Some(action) = self.outbox_to_swarm.pop_front() { /// # if let Some(action) = self.outbox_to_swarm.pop_front() {
/// # return Poll::Ready(action); /// # return Poll::Ready(action);
/// # } /// # }
@ -485,7 +485,7 @@ pub enum NetworkBehaviourAction<
/// # message: Option<PreciousMessage>, /// # message: Option<PreciousMessage>,
/// # } /// # }
/// # /// #
/// # impl ProtocolsHandler for MyHandler { /// # impl ConnectionHandler for MyHandler {
/// # type InEvent = Void; /// # type InEvent = Void;
/// # type OutEvent = Void; /// # type OutEvent = Void;
/// # type Error = Void; /// # type Error = Void;
@ -519,7 +519,7 @@ pub enum NetworkBehaviourAction<
/// # fn inject_dial_upgrade_error( /// # fn inject_dial_upgrade_error(
/// # &mut self, /// # &mut self,
/// # _: Self::OutboundOpenInfo, /// # _: Self::OutboundOpenInfo,
/// # _: ProtocolsHandlerUpgrErr<Void>, /// # _: ConnectionHandlerUpgrErr<Void>,
/// # ) { /// # ) {
/// # } /// # }
/// # /// #
@ -531,7 +531,7 @@ pub enum NetworkBehaviourAction<
/// # &mut self, /// # &mut self,
/// # _: &mut Context<'_>, /// # _: &mut Context<'_>,
/// # ) -> Poll< /// # ) -> Poll<
/// # ProtocolsHandlerEvent< /// # ConnectionHandlerEvent<
/// # Self::OutboundProtocol, /// # Self::OutboundProtocol,
/// # Self::OutboundOpenInfo, /// # Self::OutboundOpenInfo,
/// # Self::OutEvent, /// # Self::OutEvent,
@ -550,19 +550,19 @@ pub enum NetworkBehaviourAction<
/// connection with a peer. /// connection with a peer.
/// ///
/// If the `Swarm` is connected to the peer, the message is delivered to the /// 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. /// 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 /// Typically the connection ID given is the same as the one passed to
/// [`NetworkBehaviour::inject_event`], i.e. whenever the behaviour wishes to /// [`NetworkBehaviour::inject_event`], i.e. whenever the behaviour wishes to
/// respond to a request on the same connection (and possibly the same /// 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 /// 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. /// at any time and thus the event may not reach a handler.
NotifyHandler { NotifyHandler {
/// The peer for whom a `ProtocolsHandler` should be notified. /// The peer for whom a [`ConnectionHandler`] should be notified.
peer_id: PeerId, peer_id: PeerId,
/// The options w.r.t. which connection handler to notify of the event. /// The options w.r.t. which connection handler to notify of the event.
handler: NotifyHandler, handler: NotifyHandler,
@ -591,11 +591,11 @@ pub enum NetworkBehaviourAction<
/// ///
/// Note: Closing a connection via /// Note: Closing a connection via
/// [`NetworkBehaviourAction::CloseConnection`] does not inform the /// [`NetworkBehaviourAction::CloseConnection`] does not inform the
/// corresponding [`ProtocolsHandler`]. /// corresponding [`ConnectionHandler`].
/// Closing a connection via a [`ProtocolsHandler`] can be done /// Closing a connection via a [`ConnectionHandler`] can be done
/// either in a collaborative manner across [`ProtocolsHandler`]s /// either in a collaborative manner across [`ConnectionHandler`]s
/// with [`ProtocolsHandler::connection_keep_alive`] or directly with /// with [`ConnectionHandler::connection_keep_alive`] or directly with
/// [`ProtocolsHandlerEvent::Close`](crate::ProtocolsHandlerEvent::Close). /// [`ConnectionHandlerEvent::Close`](crate::ConnectionHandlerEvent::Close).
CloseConnection { CloseConnection {
/// The peer to disconnect. /// The peer to disconnect.
peer_id: PeerId, peer_id: PeerId,
@ -604,7 +604,7 @@ pub enum NetworkBehaviourAction<
}, },
} }
impl<TOutEvent, THandler: IntoProtocolsHandler, TInEventOld> impl<TOutEvent, THandler: IntoConnectionHandler, TInEventOld>
NetworkBehaviourAction<TOutEvent, THandler, TInEventOld> NetworkBehaviourAction<TOutEvent, THandler, TInEventOld>
{ {
/// Map the handler event. /// Map the handler event.
@ -640,7 +640,7 @@ impl<TOutEvent, THandler: IntoProtocolsHandler, TInEventOld>
} }
} }
impl<TOutEvent, THandler: IntoProtocolsHandler> NetworkBehaviourAction<TOutEvent, THandler> { impl<TOutEvent, THandler: IntoConnectionHandler> NetworkBehaviourAction<TOutEvent, THandler> {
/// Map the event the swarm will return. /// Map the event the swarm will return.
pub fn map_out<E>(self, f: impl FnOnce(TOutEvent) -> E) -> NetworkBehaviourAction<E, THandler> { pub fn map_out<E>(self, f: impl FnOnce(TOutEvent) -> E) -> NetworkBehaviourAction<E, THandler> {
match self { match self {
@ -673,8 +673,8 @@ impl<TOutEvent, THandler: IntoProtocolsHandler> NetworkBehaviourAction<TOutEvent
impl<TInEvent, TOutEvent, THandlerOld> NetworkBehaviourAction<TOutEvent, THandlerOld> impl<TInEvent, TOutEvent, THandlerOld> NetworkBehaviourAction<TOutEvent, THandlerOld>
where where
THandlerOld: IntoProtocolsHandler, THandlerOld: IntoConnectionHandler,
<THandlerOld as IntoProtocolsHandler>::Handler: ProtocolsHandler<InEvent = TInEvent>, <THandlerOld as IntoConnectionHandler>::Handler: ConnectionHandler<InEvent = TInEvent>,
{ {
/// Map the handler. /// Map the handler.
pub fn map_handler<THandlerNew>( pub fn map_handler<THandlerNew>(
@ -682,8 +682,8 @@ where
f: impl FnOnce(THandlerOld) -> THandlerNew, f: impl FnOnce(THandlerOld) -> THandlerNew,
) -> NetworkBehaviourAction<TOutEvent, THandlerNew> ) -> NetworkBehaviourAction<TOutEvent, THandlerNew>
where where
THandlerNew: IntoProtocolsHandler, THandlerNew: IntoConnectionHandler,
<THandlerNew as IntoProtocolsHandler>::Handler: ProtocolsHandler<InEvent = TInEvent>, <THandlerNew as IntoConnectionHandler>::Handler: ConnectionHandler<InEvent = TInEvent>,
{ {
match self { match self {
NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(e), NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(e),
@ -716,8 +716,8 @@ where
impl<TInEventOld, TOutEvent, THandlerOld> NetworkBehaviourAction<TOutEvent, THandlerOld> impl<TInEventOld, TOutEvent, THandlerOld> NetworkBehaviourAction<TOutEvent, THandlerOld>
where where
THandlerOld: IntoProtocolsHandler, THandlerOld: IntoConnectionHandler,
<THandlerOld as IntoProtocolsHandler>::Handler: ProtocolsHandler<InEvent = TInEventOld>, <THandlerOld as IntoConnectionHandler>::Handler: ConnectionHandler<InEvent = TInEventOld>,
{ {
/// Map the handler and handler event. /// Map the handler and handler event.
pub fn map_handler_and_in<THandlerNew, TInEventNew>( pub fn map_handler_and_in<THandlerNew, TInEventNew>(
@ -726,8 +726,8 @@ where
f_in_event: impl FnOnce(TInEventOld) -> TInEventNew, f_in_event: impl FnOnce(TInEventOld) -> TInEventNew,
) -> NetworkBehaviourAction<TOutEvent, THandlerNew> ) -> NetworkBehaviourAction<TOutEvent, THandlerNew>
where where
THandlerNew: IntoProtocolsHandler, THandlerNew: IntoConnectionHandler,
<THandlerNew as IntoProtocolsHandler>::Handler: ProtocolsHandler<InEvent = TInEventNew>, <THandlerNew as IntoConnectionHandler>::Handler: ConnectionHandler<InEvent = TInEventNew>,
{ {
match self { match self {
NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(e), NetworkBehaviourAction::GenerateEvent(e) => NetworkBehaviourAction::GenerateEvent(e),

View File

@ -18,7 +18,7 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocols_handler::{either::IntoEitherHandler, IntoProtocolsHandler, ProtocolsHandler}; use crate::handler::{either::IntoEitherHandler, ConnectionHandler, IntoConnectionHandler};
use crate::{ use crate::{
DialError, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, DialError, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess,
PollParameters, PollParameters,
@ -36,10 +36,10 @@ where
L: NetworkBehaviour, L: NetworkBehaviour,
R: NetworkBehaviour, R: NetworkBehaviour,
{ {
type ProtocolsHandler = IntoEitherHandler<L::ProtocolsHandler, R::ProtocolsHandler>; type ConnectionHandler = IntoEitherHandler<L::ConnectionHandler, R::ConnectionHandler>;
type OutEvent = Either<L::OutEvent, R::OutEvent>; type OutEvent = Either<L::OutEvent, R::OutEvent>;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
match self { match self {
Either::Left(a) => IntoEitherHandler::Left(a.new_handler()), Either::Left(a) => IntoEitherHandler::Left(a.new_handler()),
Either::Right(b) => IntoEitherHandler::Right(b.new_handler()), Either::Right(b) => IntoEitherHandler::Right(b.new_handler()),
@ -84,7 +84,7 @@ where
peer_id: &PeerId, peer_id: &PeerId,
connection: &ConnectionId, connection: &ConnectionId,
endpoint: &ConnectedPoint, endpoint: &ConnectedPoint,
handler: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, handler: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
match (self, handler) { match (self, handler) {
@ -124,7 +124,7 @@ where
&mut self, &mut self,
peer_id: PeerId, peer_id: PeerId,
connection: ConnectionId, connection: ConnectionId,
event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent, event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
) { ) {
match (self, event) { match (self, event) {
(Either::Left(behaviour), Either::Left(event)) => { (Either::Left(behaviour), Either::Left(event)) => {
@ -140,7 +140,7 @@ where
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
peer_id: Option<PeerId>, peer_id: Option<PeerId>,
handler: Self::ProtocolsHandler, handler: Self::ConnectionHandler,
error: &DialError, error: &DialError,
) { ) {
match (self, handler) { match (self, handler) {
@ -158,7 +158,7 @@ where
&mut self, &mut self,
local_addr: &Multiaddr, local_addr: &Multiaddr,
send_back_addr: &Multiaddr, send_back_addr: &Multiaddr,
handler: Self::ProtocolsHandler, handler: Self::ConnectionHandler,
) { ) {
match (self, handler) { match (self, handler) {
(Either::Left(behaviour), IntoEitherHandler::Left(handler)) => { (Either::Left(behaviour), IntoEitherHandler::Left(handler)) => {
@ -224,7 +224,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
params: &mut impl PollParameters, params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
let event = match self { let event = match self {
Either::Left(behaviour) => futures::ready!(behaviour.poll(cx, params)) Either::Left(behaviour) => futures::ready!(behaviour.poll(cx, params))
.map_out(|e| Either::Left(e)) .map_out(|e| Either::Left(e))

View File

@ -18,9 +18,9 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocols_handler::{ use crate::handler::{
IntoProtocolsHandler, KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, KeepAlive, SubstreamProtocol,
}; };
use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper};
use crate::{ use crate::{
@ -70,10 +70,10 @@ impl<TBehaviour> NetworkBehaviour for Toggle<TBehaviour>
where where
TBehaviour: NetworkBehaviour, TBehaviour: NetworkBehaviour,
{ {
type ProtocolsHandler = ToggleIntoProtoHandler<TBehaviour::ProtocolsHandler>; type ConnectionHandler = ToggleIntoProtoHandler<TBehaviour::ConnectionHandler>;
type OutEvent = TBehaviour::OutEvent; type OutEvent = TBehaviour::OutEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
ToggleIntoProtoHandler { ToggleIntoProtoHandler {
inner: self.inner.as_mut().map(|i| i.new_handler()), inner: self.inner.as_mut().map(|i| i.new_handler()),
} }
@ -110,7 +110,7 @@ where
peer_id: &PeerId, peer_id: &PeerId,
connection: &ConnectionId, connection: &ConnectionId,
endpoint: &ConnectedPoint, endpoint: &ConnectedPoint,
handler: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, handler: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
if let Some(inner) = self.inner.as_mut() { if let Some(inner) = self.inner.as_mut() {
@ -142,7 +142,7 @@ where
&mut self, &mut self,
peer_id: PeerId, peer_id: PeerId,
connection: ConnectionId, connection: ConnectionId,
event: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent, event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
) { ) {
if let Some(inner) = self.inner.as_mut() { if let Some(inner) = self.inner.as_mut() {
inner.inject_event(peer_id, connection, event); inner.inject_event(peer_id, connection, event);
@ -152,7 +152,7 @@ where
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
peer_id: Option<PeerId>, peer_id: Option<PeerId>,
handler: Self::ProtocolsHandler, handler: Self::ConnectionHandler,
error: &DialError, error: &DialError,
) { ) {
if let Some(inner) = self.inner.as_mut() { if let Some(inner) = self.inner.as_mut() {
@ -166,7 +166,7 @@ where
&mut self, &mut self,
local_addr: &Multiaddr, local_addr: &Multiaddr,
send_back_addr: &Multiaddr, send_back_addr: &Multiaddr,
handler: Self::ProtocolsHandler, handler: Self::ConnectionHandler,
) { ) {
if let Some(inner) = self.inner.as_mut() { if let Some(inner) = self.inner.as_mut() {
if let Some(handler) = handler.inner { if let Some(handler) = handler.inner {
@ -221,7 +221,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
params: &mut impl PollParameters, params: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
if let Some(inner) = self.inner.as_mut() { if let Some(inner) = self.inner.as_mut() {
inner inner
.poll(cx, params) .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<TInner> { pub struct ToggleIntoProtoHandler<TInner> {
inner: Option<TInner>, inner: Option<TInner>,
} }
impl<TInner> IntoProtocolsHandler for ToggleIntoProtoHandler<TInner> impl<TInner> IntoConnectionHandler for ToggleIntoProtoHandler<TInner>
where where
TInner: IntoProtocolsHandler, TInner: IntoConnectionHandler,
{ {
type Handler = ToggleProtoHandler<TInner::Handler>; type Handler = ToggleProtoHandler<TInner::Handler>;
@ -266,7 +266,7 @@ where
} }
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
if let Some(inner) = self.inner.as_ref() { if let Some(inner) = self.inner.as_ref() {
EitherUpgrade::A(SendWrapper(inner.inbound_protocol())) EitherUpgrade::A(SendWrapper(inner.inbound_protocol()))
} else { } 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<TInner> { pub struct ToggleProtoHandler<TInner> {
inner: Option<TInner>, inner: Option<TInner>,
} }
impl<TInner> ProtocolsHandler for ToggleProtoHandler<TInner> impl<TInner> ConnectionHandler for ToggleProtoHandler<TInner>
where where
TInner: ProtocolsHandler, TInner: ConnectionHandler,
{ {
type InEvent = TInner::InEvent; type InEvent = TInner::InEvent;
type OutEvent = TInner::OutEvent; type OutEvent = TInner::OutEvent;
@ -354,7 +354,7 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
info: Self::OutboundOpenInfo, info: Self::OutboundOpenInfo,
err: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, err: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
self.inner self.inner
.as_mut() .as_mut()
@ -365,7 +365,7 @@ where
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
info: Self::InboundOpenInfo, info: Self::InboundOpenInfo,
err: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, err: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
let (inner, info) = match (self.inner.as_mut(), info) { let (inner, info) = match (self.inner.as_mut(), info) {
(Some(inner), Either::Left(info)) => (inner, info), (Some(inner), Either::Left(info)) => (inner, info),
@ -382,10 +382,10 @@ where
}; };
let err = match err { let err = match err {
ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout,
ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer,
ProtocolsHandlerUpgrErr::Upgrade(err) => { ConnectionHandlerUpgrErr::Upgrade(err) => {
ProtocolsHandlerUpgrErr::Upgrade(err.map_err(|err| match err { ConnectionHandlerUpgrErr::Upgrade(err.map_err(|err| match err {
EitherError::A(e) => e, EitherError::A(e) => e,
EitherError::B(v) => void::unreachable(v), EitherError::B(v) => void::unreachable(v),
})) }))
@ -406,7 +406,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -424,7 +424,7 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::protocols_handler::DummyProtocolsHandler; use crate::handler::DummyConnectionHandler;
/// A disabled [`ToggleProtoHandler`] can receive listen upgrade errors in /// A disabled [`ToggleProtoHandler`] can receive listen upgrade errors in
/// the following two cases: /// the following two cases:
@ -432,18 +432,18 @@ mod tests {
/// 1. Protocol negotiation on an incoming stream failed with no protocol /// 1. Protocol negotiation on an incoming stream failed with no protocol
/// being agreed on. /// being agreed on.
/// ///
/// 2. When combining [`ProtocolsHandler`] implementations a single /// 2. When combining [`ConnectionHandler`] implementations a single
/// [`ProtocolsHandler`] might be notified of an inbound upgrade error /// [`ConnectionHandler`] might be notified of an inbound upgrade error
/// unrelated to its own upgrade logic. For example when nesting a /// unrelated to its own upgrade logic. For example when nesting a
/// [`ToggleProtoHandler`] in 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. /// the former might receive an inbound upgrade error even when disabled.
/// ///
/// [`ToggleProtoHandler`] should ignore the error in both of these cases. /// [`ToggleProtoHandler`] should ignore the error in both of these cases.
#[test] #[test]
fn ignore_listen_upgrade_error_when_disabled() { fn ignore_listen_upgrade_error_when_disabled() {
let mut handler = ToggleProtoHandler::<DummyProtocolsHandler> { inner: None }; let mut handler = ToggleProtoHandler::<DummyConnectionHandler> { inner: None };
handler.inject_listen_upgrade_error(Either::Right(()), ProtocolsHandlerUpgrErr::Timeout); handler.inject_listen_upgrade_error(Either::Right(()), ConnectionHandlerUpgrErr::Timeout);
} }
} }

View File

@ -34,7 +34,7 @@ pub use pool::{ConnectionCounters, ConnectionLimits};
pub use pool::{EstablishedConnection, PendingConnection}; pub use pool::{EstablishedConnection, PendingConnection};
pub use substream::{Close, Substream, SubstreamEndpoint}; pub use substream::{Close, Substream, SubstreamEndpoint};
use crate::protocols_handler::ProtocolsHandler; use crate::handler::ConnectionHandler;
use handler_wrapper::HandlerWrapper; use handler_wrapper::HandlerWrapper;
use libp2p_core::connection::ConnectedPoint; use libp2p_core::connection::ConnectedPoint;
use libp2p_core::multiaddr::Multiaddr; use libp2p_core::multiaddr::Multiaddr;
@ -56,16 +56,16 @@ pub struct Connected {
/// Event generated by a [`Connection`]. /// Event generated by a [`Connection`].
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Event<T> { pub enum Event<T> {
/// Event generated by the [`ProtocolsHandler`]. /// Event generated by the [`ConnectionHandler`].
Handler(T), Handler(T),
/// Address of the remote has changed. /// Address of the remote has changed.
AddressChange(Multiaddr), 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<THandler> pub struct Connection<THandler>
where where
THandler: ProtocolsHandler, THandler: ConnectionHandler,
{ {
/// Node that handles the muxing. /// Node that handles the muxing.
muxing: substream::Muxing<StreamMuxerBox, handler_wrapper::OutboundOpenInfo<THandler>>, muxing: substream::Muxing<StreamMuxerBox, handler_wrapper::OutboundOpenInfo<THandler>>,
@ -75,7 +75,7 @@ where
impl<THandler> fmt::Debug for Connection<THandler> impl<THandler> fmt::Debug for Connection<THandler>
where where
THandler: ProtocolsHandler + fmt::Debug, THandler: ConnectionHandler + fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Connection") f.debug_struct("Connection")
@ -85,11 +85,11 @@ where
} }
} }
impl<THandler> Unpin for Connection<THandler> where THandler: ProtocolsHandler {} impl<THandler> Unpin for Connection<THandler> where THandler: ConnectionHandler {}
impl<THandler> Connection<THandler> impl<THandler> Connection<THandler>
where where
THandler: ProtocolsHandler, THandler: ConnectionHandler,
{ {
/// Builds a new `Connection` from the given substream multiplexer /// Builds a new `Connection` from the given substream multiplexer
/// and connection handler. /// and connection handler.

View File

@ -19,8 +19,8 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::connection::{Substream, SubstreamEndpoint}; use crate::connection::{Substream, SubstreamEndpoint};
use crate::protocols_handler::{ use crate::handler::{
KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
}; };
use crate::upgrade::SendWrapper; use crate::upgrade::SendWrapper;
@ -35,16 +35,16 @@ use libp2p_core::{
}; };
use std::{error, fmt, pin::Pin, task::Context, task::Poll, time::Duration}; 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 /// - Enforced substream upgrade timeouts
/// - Driving substream upgrades /// - Driving substream upgrades
/// - Handling connection timeout /// - Handling connection timeout
// TODO: add a caching system for protocols that are supported or not // TODO: add a caching system for protocols that are supported or not
pub struct HandlerWrapper<TProtoHandler> pub struct HandlerWrapper<TProtoHandler>
where where
TProtoHandler: ProtocolsHandler, TProtoHandler: ConnectionHandler,
{ {
/// The underlying handler. /// The underlying handler.
handler: TProtoHandler, handler: TProtoHandler,
@ -79,7 +79,7 @@ where
substream_upgrade_protocol_override: Option<upgrade::Version>, substream_upgrade_protocol_override: Option<upgrade::Version>,
} }
impl<TProtoHandler: ProtocolsHandler> std::fmt::Debug for HandlerWrapper<TProtoHandler> { impl<TProtoHandler: ConnectionHandler> std::fmt::Debug for HandlerWrapper<TProtoHandler> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HandlerWrapper") f.debug_struct("HandlerWrapper")
.field("negotiating_in", &self.negotiating_in) .field("negotiating_in", &self.negotiating_in)
@ -94,7 +94,7 @@ impl<TProtoHandler: ProtocolsHandler> std::fmt::Debug for HandlerWrapper<TProtoH
} }
} }
impl<TProtoHandler: ProtocolsHandler> HandlerWrapper<TProtoHandler> { impl<TProtoHandler: ConnectionHandler> HandlerWrapper<TProtoHandler> {
pub(crate) fn new( pub(crate) fn new(
handler: TProtoHandler, handler: TProtoHandler,
substream_upgrade_protocol_override: Option<upgrade::Version>, substream_upgrade_protocol_override: Option<upgrade::Version>,
@ -129,7 +129,7 @@ where
{ {
type Output = ( type Output = (
UserData, UserData,
Result<UpgradeOutput, ProtocolsHandlerUpgrErr<TUpgradeError>>, Result<UpgradeOutput, ConnectionHandlerUpgrErr<TUpgradeError>>,
); );
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
@ -139,7 +139,7 @@ where
self.user_data self.user_data
.take() .take()
.expect("Future not to be polled again once ready."), .expect("Future not to be polled again once ready."),
Err(ProtocolsHandlerUpgrErr::Timeout), Err(ConnectionHandlerUpgrErr::Timeout),
)) ))
} }
@ -157,7 +157,7 @@ where
self.user_data self.user_data
.take() .take()
.expect("Future not to be polled again once ready."), .expect("Future not to be polled again once ready."),
Err(ProtocolsHandlerUpgrErr::Upgrade(err)), Err(ConnectionHandlerUpgrErr::Upgrade(err)),
)), )),
Poll::Pending => Poll::Pending, Poll::Pending => Poll::Pending,
} }
@ -167,8 +167,8 @@ where
/// The options for a planned connection & handler shutdown. /// The options for a planned connection & handler shutdown.
/// ///
/// A shutdown is planned anew based on the the return value of /// A shutdown is planned anew based on the the return value of
/// [`ProtocolsHandler::connection_keep_alive`] of the underlying handler /// [`ConnectionHandler::connection_keep_alive`] of the underlying handler
/// after every invocation of [`ProtocolsHandler::poll`]. /// after every invocation of [`ConnectionHandler::poll`].
/// ///
/// A planned shutdown is always postponed for as long as there are ingoing /// 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" /// or outgoing substreams being negotiated, i.e. it is a graceful, "idle"
@ -226,13 +226,13 @@ where
pub type OutboundOpenInfo<TProtoHandler> = ( pub type OutboundOpenInfo<TProtoHandler> = (
u64, u64,
<TProtoHandler as ProtocolsHandler>::OutboundOpenInfo, <TProtoHandler as ConnectionHandler>::OutboundOpenInfo,
Duration, Duration,
); );
impl<TProtoHandler> HandlerWrapper<TProtoHandler> impl<TProtoHandler> HandlerWrapper<TProtoHandler>
where where
TProtoHandler: ProtocolsHandler, TProtoHandler: ConnectionHandler,
{ {
pub fn inject_substream( pub fn inject_substream(
&mut self, &mut self,
@ -350,10 +350,10 @@ where
}; };
match poll_result { match poll_result {
Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => { Poll::Ready(ConnectionHandlerEvent::Custom(event)) => {
return Poll::Ready(Ok(Event::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 id = self.unique_dial_upgrade_id;
let timeout = *protocol.timeout(); let timeout = *protocol.timeout();
self.unique_dial_upgrade_id += 1; self.unique_dial_upgrade_id += 1;
@ -361,7 +361,7 @@ where
self.queued_dial_upgrades.push((id, SendWrapper(upgrade))); self.queued_dial_upgrades.push((id, SendWrapper(upgrade)));
return Poll::Ready(Ok(Event::OutboundSubstreamRequest((id, info, timeout)))); 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 => (), Poll::Pending => (),
}; };

View File

@ -26,7 +26,7 @@ use crate::{
PendingInboundConnectionError, PendingOutboundConnectionError, PendingInboundConnectionError, PendingOutboundConnectionError,
}, },
transport::{Transport, TransportError}, transport::{Transport, TransportError},
ConnectedPoint, Executor, IntoProtocolsHandler, Multiaddr, PeerId, ProtocolsHandler, ConnectedPoint, ConnectionHandler, Executor, IntoConnectionHandler, Multiaddr, PeerId,
}; };
use concurrent_dial::ConcurrentDial; use concurrent_dial::ConcurrentDial;
use fnv::FnvHashMap; use fnv::FnvHashMap;
@ -54,7 +54,7 @@ mod concurrent_dial;
mod task; mod task;
/// A connection `Pool` manages a set of connections for each peer. /// A connection `Pool` manages a set of connections for each peer.
pub struct Pool<THandler: IntoProtocolsHandler, TTrans> pub struct Pool<THandler: IntoConnectionHandler, TTrans>
where where
TTrans: Transport, TTrans: Transport,
{ {
@ -68,7 +68,7 @@ where
PeerId, PeerId,
FnvHashMap< FnvHashMap<
ConnectionId, ConnectionId,
EstablishedConnectionInfo<<THandler::Handler as ProtocolsHandler>::InEvent>, EstablishedConnectionInfo<<THandler::Handler as ConnectionHandler>::InEvent>,
>, >,
>, >,
@ -146,7 +146,7 @@ struct PendingConnectionInfo<THandler> {
abort_notifier: Option<oneshot::Sender<Void>>, abort_notifier: Option<oneshot::Sender<Void>>,
} }
impl<THandler: IntoProtocolsHandler, TTrans: Transport> fmt::Debug for Pool<THandler, TTrans> { impl<THandler: IntoConnectionHandler, TTrans: Transport> fmt::Debug for Pool<THandler, TTrans> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.debug_struct("Pool") f.debug_struct("Pool")
.field("counters", &self.counters) .field("counters", &self.counters)
@ -155,13 +155,13 @@ impl<THandler: IntoProtocolsHandler, TTrans: Transport> fmt::Debug for Pool<THan
} }
/// Event that can happen on the `Pool`. /// Event that can happen on the `Pool`.
pub enum PoolEvent<'a, THandler: IntoProtocolsHandler, TTrans> pub enum PoolEvent<'a, THandler: IntoConnectionHandler, TTrans>
where where
TTrans: Transport, TTrans: Transport,
{ {
/// A new connection has been established. /// A new connection has been established.
ConnectionEstablished { ConnectionEstablished {
connection: EstablishedConnection<'a, <THandler::Handler as ProtocolsHandler>::InEvent>, connection: EstablishedConnection<'a, <THandler::Handler as ConnectionHandler>::InEvent>,
/// List of other connections to the same peer. /// List of other connections to the same peer.
/// ///
/// Note: Does not include the connection reported through this event. /// Note: Does not include the connection reported through this event.
@ -189,7 +189,7 @@ where
connected: Connected, connected: Connected,
/// The error that occurred, if any. If `None`, the connection /// The error that occurred, if any. If `None`, the connection
/// was closed by the local peer. /// was closed by the local peer.
error: Option<ConnectionError<<THandler::Handler as ProtocolsHandler>::Error>>, error: Option<ConnectionError<<THandler::Handler as ConnectionHandler>::Error>>,
/// A reference to the pool that used to manage the connection. /// A reference to the pool that used to manage the connection.
pool: &'a mut Pool<THandler, TTrans>, pool: &'a mut Pool<THandler, TTrans>,
/// The remaining established connections to the same peer. /// 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 where
TTrans: Transport, TTrans: Transport,
TTrans::Error: fmt::Debug, TTrans::Error: fmt::Debug,
@ -311,7 +311,7 @@ where
impl<THandler, TTrans> Pool<THandler, TTrans> impl<THandler, TTrans> Pool<THandler, TTrans>
where where
THandler: IntoProtocolsHandler, THandler: IntoConnectionHandler,
TTrans: Transport, TTrans: Transport,
{ {
/// Creates a new empty `Pool`. /// Creates a new empty `Pool`.
@ -465,7 +465,7 @@ where
impl<THandler, TTrans> Pool<THandler, TTrans> impl<THandler, TTrans> Pool<THandler, TTrans>
where where
THandler: IntoProtocolsHandler, THandler: IntoConnectionHandler,
TTrans: Transport + 'static, TTrans: Transport + 'static,
TTrans::Output: Send + 'static, TTrans::Output: Send + 'static,
TTrans::Error: Send + 'static, TTrans::Error: Send + 'static,
@ -582,9 +582,9 @@ where
pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll<PoolEvent<'a, THandler, TTrans>> pub fn poll<'a>(&'a mut self, cx: &mut Context<'_>) -> Poll<PoolEvent<'a, THandler, TTrans>>
where where
TTrans: Transport<Output = (PeerId, StreamMuxerBox)>, TTrans: Transport<Output = (PeerId, StreamMuxerBox)>,
THandler: IntoProtocolsHandler + 'static, THandler: IntoConnectionHandler + 'static,
THandler::Handler: ProtocolsHandler + Send, THandler::Handler: ConnectionHandler + Send,
<THandler::Handler as ProtocolsHandler>::OutboundOpenInfo: Send, <THandler::Handler as ConnectionHandler>::OutboundOpenInfo: Send,
{ {
// Poll for events of established connections. // Poll for events of established connections.
// //
@ -896,17 +896,17 @@ where
} }
/// A connection in a [`Pool`]. /// A connection in a [`Pool`].
pub enum PoolConnection<'a, THandler: IntoProtocolsHandler> { pub enum PoolConnection<'a, THandler: IntoConnectionHandler> {
Pending(PendingConnection<'a, THandler>), Pending(PendingConnection<'a, THandler>),
Established(EstablishedConnection<'a, THandlerInEvent<THandler>>), Established(EstablishedConnection<'a, THandlerInEvent<THandler>>),
} }
/// A pending connection in a pool. /// 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<THandler>>, entry: hash_map::OccupiedEntry<'a, ConnectionId, PendingConnectionInfo<THandler>>,
} }
impl<THandler: IntoProtocolsHandler> PendingConnection<'_, THandler> { impl<THandler: IntoConnectionHandler> PendingConnection<'_, THandler> {
/// Aborts the connection attempt, closing the connection. /// Aborts the connection attempt, closing the connection.
pub fn abort(mut self) { pub fn abort(mut self) {
if let Some(notifier) = self.entry.get_mut().abort_notifier.take() { if let Some(notifier) = self.entry.get_mut().abort_notifier.take() {

View File

@ -27,7 +27,7 @@ use crate::{
self, ConnectionError, PendingInboundConnectionError, PendingOutboundConnectionError, self, ConnectionError, PendingInboundConnectionError, PendingOutboundConnectionError,
}, },
transport::{Transport, TransportError}, transport::{Transport, TransportError},
Multiaddr, PeerId, ProtocolsHandler, ConnectionHandler, Multiaddr, PeerId,
}; };
use futures::{ use futures::{
channel::{mpsc, oneshot}, channel::{mpsc, oneshot},
@ -72,7 +72,7 @@ where
} }
#[derive(Debug)] #[derive(Debug)]
pub enum EstablishedConnectionEvent<THandler: ProtocolsHandler> { pub enum EstablishedConnectionEvent<THandler: ConnectionHandler> {
/// A node we are connected to has changed its address. /// A node we are connected to has changed its address.
AddressChange { AddressChange {
id: ConnectionId, id: ConnectionId,
@ -183,7 +183,7 @@ pub async fn new_for_established_connection<THandler>(
mut command_receiver: mpsc::Receiver<Command<THandler::InEvent>>, mut command_receiver: mpsc::Receiver<Command<THandler::InEvent>>,
mut events: mpsc::Sender<EstablishedConnectionEvent<THandler>>, mut events: mpsc::Sender<EstablishedConnectionEvent<THandler>>,
) where ) where
THandler: ProtocolsHandler, THandler: ConnectionHandler,
{ {
loop { loop {
match futures::future::select( match futures::future::select(

View File

@ -18,24 +18,25 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // 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. //! and handles one or more specific protocols on the connection.
//! //!
//! Protocols are negotiated and used on individual substreams of the connection. //! Protocols are negotiated and used on individual substreams of the connection. Thus a
//! Thus a `ProtocolsHandler` defines the inbound and outbound upgrades to apply //! [`ConnectionHandler`] defines the inbound and outbound upgrades to apply when creating a new
//! when creating a new inbound or outbound substream, respectively, and is notified //! inbound or outbound substream, respectively, and is notified by a [`Swarm`](crate::Swarm) when
//! by a `Swarm` when these upgrades have been successfully applied, including the //! these upgrades have been successfully applied, including the final output of the upgrade. A
//! final output of the upgrade. A `ProtocolsHandler` can then continue communicating //! [`ConnectionHandler`] can then continue communicating with the peer over the substream using the
//! with the peer over the substream using the negotiated protocol(s). //! 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, //! in order to build a new handler supporting the combined set of protocols,
//! with methods being dispatched to the appropriate handler according to the //! with methods being dispatched to the appropriate handler according to the
//! used protocol(s) determined by the associated types of the handlers. //! 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 //! > 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; mod dummy;
pub mod either; pub mod either;
@ -51,11 +52,11 @@ use instant::Instant;
use libp2p_core::{upgrade::UpgradeError, ConnectedPoint, Multiaddr, PeerId}; use libp2p_core::{upgrade::UpgradeError, ConnectedPoint, Multiaddr, PeerId};
use std::{cmp::Ordering, error, fmt, task::Context, task::Poll, time::Duration}; 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_in::MapInEvent;
pub use map_out::MapOutEvent; pub use map_out::MapOutEvent;
pub use one_shot::{OneShotHandler, OneShotHandlerConfig}; 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. /// 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: /// 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, /// 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 /// 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. /// is called with the final output of the upgrade.
/// ///
/// 2. Listening by accepting a new inbound substream. When a new inbound substream /// 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 /// to obtain an instance of [`libp2p_core::upgrade::InboundUpgrade`] that is used to
/// negotiate the protocol(s). Upon success, /// 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. /// output of the upgrade.
/// ///
/// # Connection Keep-Alive /// # Connection Keep-Alive
/// ///
/// A `ProtocolsHandler` can influence the lifetime of the underlying connection /// A [`ConnectionHandler`] can influence the lifetime of the underlying connection
/// through [`ProtocolsHandler::connection_keep_alive`]. That is, the protocol /// through [`ConnectionHandler::connection_keep_alive`]. That is, the protocol
/// implemented by the handler can include conditions for terminating the connection. /// implemented by the handler can include conditions for terminating the connection.
/// The lifetime of successfully negotiated substreams is fully controlled by the handler. /// 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. /// 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 /// 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. /// 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. /// Custom event that can be received from the outside.
type InEvent: fmt::Debug + Send + 'static; type InEvent: fmt::Debug + Send + 'static;
/// Custom event that can be produced by the handler and that will be returned to the outside. /// Custom event that can be produced by the handler and that will be returned to the outside.
type OutEvent: fmt::Debug + Send + 'static; 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; type Error: error::Error + fmt::Debug + Send + 'static;
/// The inbound upgrade for the protocol(s) used by the handler. /// The inbound upgrade for the protocol(s) used by the handler.
type InboundProtocol: InboundUpgradeSend; type InboundProtocol: InboundUpgradeSend;
@ -124,7 +125,7 @@ pub trait ProtocolsHandler: Send + 'static {
/// Injects the output of a successful upgrade on a new outbound substream. /// Injects the output of a successful upgrade on a new outbound substream.
/// ///
/// The second argument is the information that was previously passed to /// The second argument is the information that was previously passed to
/// [`ProtocolsHandlerEvent::OutboundSubstreamRequest`]. /// [`ConnectionHandlerEvent::OutboundSubstreamRequest`].
fn inject_fully_negotiated_outbound( fn inject_fully_negotiated_outbound(
&mut self, &mut self,
protocol: <Self::OutboundProtocol as OutboundUpgradeSend>::Output, protocol: <Self::OutboundProtocol as OutboundUpgradeSend>::Output,
@ -141,22 +142,22 @@ pub trait ProtocolsHandler: Send + 'static {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
info: Self::OutboundOpenInfo, info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
); );
/// Indicates to the handler that upgrading an inbound substream to the given protocol has failed. /// Indicates to the handler that upgrading an inbound substream to the given protocol has failed.
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
_: Self::InboundOpenInfo, _: Self::InboundOpenInfo,
_: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, _: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
} }
/// Returns until when the connection should be kept alive. /// Returns until when the connection should be kept alive.
/// ///
/// This method is called by the `Swarm` after each invocation of /// This method is called by the `Swarm` after each invocation of
/// [`ProtocolsHandler::poll`] to determine if the connection and the associated /// [`ConnectionHandler::poll`] to determine if the connection and the associated
/// `ProtocolsHandler`s should be kept alive as far as this handler is concerned /// [`ConnectionHandler`]s should be kept alive as far as this handler is concerned
/// and if so, for how long. /// and if so, for how long.
/// ///
/// Returning [`KeepAlive::No`] indicates that the connection should be /// 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. /// be kept alive until the next call to this method.
/// ///
/// > **Note**: The connection is always closed and the handler destroyed /// > **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 /// > connection may be closed for reasons outside of the control
/// > of the handler. /// > of the handler.
fn connection_keep_alive(&self) -> KeepAlive; fn connection_keep_alive(&self) -> KeepAlive;
@ -179,7 +180,7 @@ pub trait ProtocolsHandler: Send + 'static {
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -205,25 +206,25 @@ pub trait ProtocolsHandler: Send + 'static {
MapOutEvent::new(self, map) 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. /// `other` by delegating methods calls appropriately.
/// ///
/// > **Note**: The largest `KeepAlive` returned by the two handlers takes precedence, /// > **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. /// > handler.
fn select<TProto2>(self, other: TProto2) -> ProtocolsHandlerSelect<Self, TProto2> fn select<TProto2>(self, other: TProto2) -> ConnectionHandlerSelect<Self, TProto2>
where where
Self: Sized, Self: Sized,
{ {
ProtocolsHandlerSelect::new(self, other) ConnectionHandlerSelect::new(self, other)
} }
} }
/// Configuration of inbound or outbound substream protocol(s) /// 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`] /// The inbound substream protocol(s) are defined by [`ConnectionHandler::listen_protocol`]
/// and the outbound substream protocol(s) by [`ProtocolsHandlerEvent::OutboundSubstreamRequest`]. /// and the outbound substream protocol(s) by [`ConnectionHandlerEvent::OutboundSubstreamRequest`].
#[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SubstreamProtocol<TUpgrade, TInfo> { pub struct SubstreamProtocol<TUpgrade, TInfo> {
upgrade: TUpgrade, upgrade: TUpgrade,
@ -297,7 +298,7 @@ impl<TUpgrade, TInfo> SubstreamProtocol<TUpgrade, TInfo> {
/// Event produced by a handler. /// Event produced by a handler.
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr> { pub enum ConnectionHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr> {
/// Request a new outbound substream to be opened with the remote. /// Request a new outbound substream to be opened with the remote.
OutboundSubstreamRequest { OutboundSubstreamRequest {
/// The protocol(s) to apply on the substream. /// The protocol(s) to apply on the substream.
@ -306,12 +307,12 @@ pub enum ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, T
/// Close the connection for the given reason. /// Close the connection for the given reason.
/// ///
/// Note this will affect all [`ProtocolsHandler`]s handling this /// Note this will affect all [`ConnectionHandler`]s handling this
/// connection, in other words it will close the connection for all /// connection, in other words it will close the connection for all
/// [`ProtocolsHandler`]s. To signal that one has no more need for the /// [`ConnectionHandler`]s. To signal that one has no more need for the
/// connection, while allowing other [`ProtocolsHandler`]s to continue using /// connection, while allowing other [`ConnectionHandler`]s to continue using
/// the connection, return [`KeepAlive::No`] in /// the connection, return [`KeepAlive::No`] in
/// [`ProtocolsHandler::connection_keep_alive`]. /// [`ConnectionHandler::connection_keep_alive`].
Close(TErr), Close(TErr),
/// Other event. /// Other event.
@ -320,25 +321,25 @@ pub enum ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, T
/// Event produced by a handler. /// Event produced by a handler.
impl<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr> impl<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr> ConnectionHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
{ {
/// If this is an `OutboundSubstreamRequest`, maps the `info` member from a /// If this is an `OutboundSubstreamRequest`, maps the `info` member from a
/// `TOutboundOpenInfo` to something else. /// `TOutboundOpenInfo` to something else.
pub fn map_outbound_open_info<F, I>( pub fn map_outbound_open_info<F, I>(
self, self,
map: F, map: F,
) -> ProtocolsHandlerEvent<TConnectionUpgrade, I, TCustom, TErr> ) -> ConnectionHandlerEvent<TConnectionUpgrade, I, TCustom, TErr>
where where
F: FnOnce(TOutboundOpenInfo) -> I, F: FnOnce(TOutboundOpenInfo) -> I,
{ {
match self { match self {
ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => {
ProtocolsHandlerEvent::OutboundSubstreamRequest { ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: protocol.map_info(map), protocol: protocol.map_info(map),
} }
} }
ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val), ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(val),
ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val), ConnectionHandlerEvent::Close(val) => ConnectionHandlerEvent::Close(val),
} }
} }
@ -347,18 +348,18 @@ impl<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
pub fn map_protocol<F, I>( pub fn map_protocol<F, I>(
self, self,
map: F, map: F,
) -> ProtocolsHandlerEvent<I, TOutboundOpenInfo, TCustom, TErr> ) -> ConnectionHandlerEvent<I, TOutboundOpenInfo, TCustom, TErr>
where where
F: FnOnce(TConnectionUpgrade) -> I, F: FnOnce(TConnectionUpgrade) -> I,
{ {
match self { match self {
ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => {
ProtocolsHandlerEvent::OutboundSubstreamRequest { ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: protocol.map_upgrade(map), protocol: protocol.map_upgrade(map),
} }
} }
ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val), ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(val),
ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val), ConnectionHandlerEvent::Close(val) => ConnectionHandlerEvent::Close(val),
} }
} }
@ -366,16 +367,16 @@ impl<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
pub fn map_custom<F, I>( pub fn map_custom<F, I>(
self, self,
map: F, map: F,
) -> ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, I, TErr> ) -> ConnectionHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, I, TErr>
where where
F: FnOnce(TCustom) -> I, F: FnOnce(TCustom) -> I,
{ {
match self { match self {
ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => {
ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }
} }
ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(map(val)), ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(map(val)),
ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(val), ConnectionHandlerEvent::Close(val) => ConnectionHandlerEvent::Close(val),
} }
} }
@ -383,23 +384,23 @@ impl<TConnectionUpgrade, TOutboundOpenInfo, TCustom, TErr>
pub fn map_close<F, I>( pub fn map_close<F, I>(
self, self,
map: F, map: F,
) -> ProtocolsHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, I> ) -> ConnectionHandlerEvent<TConnectionUpgrade, TOutboundOpenInfo, TCustom, I>
where where
F: FnOnce(TErr) -> I, F: FnOnce(TErr) -> I,
{ {
match self { match self {
ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => {
ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }
} }
ProtocolsHandlerEvent::Custom(val) => ProtocolsHandlerEvent::Custom(val), ConnectionHandlerEvent::Custom(val) => ConnectionHandlerEvent::Custom(val),
ProtocolsHandlerEvent::Close(val) => ProtocolsHandlerEvent::Close(map(val)), ConnectionHandlerEvent::Close(val) => ConnectionHandlerEvent::Close(map(val)),
} }
} }
} }
/// Error that can happen on an outbound substream opening attempt. /// Error that can happen on an outbound substream opening attempt.
#[derive(Debug)] #[derive(Debug)]
pub enum ProtocolsHandlerUpgrErr<TUpgrErr> { pub enum ConnectionHandlerUpgrErr<TUpgrErr> {
/// The opening attempt timed out before the negotiation was fully completed. /// The opening attempt timed out before the negotiation was fully completed.
Timeout, Timeout,
/// There was an error in the timer used. /// There was an error in the timer used.
@ -408,54 +409,54 @@ pub enum ProtocolsHandlerUpgrErr<TUpgrErr> {
Upgrade(UpgradeError<TUpgrErr>), Upgrade(UpgradeError<TUpgrErr>),
} }
impl<TUpgrErr> ProtocolsHandlerUpgrErr<TUpgrErr> { impl<TUpgrErr> ConnectionHandlerUpgrErr<TUpgrErr> {
/// Map the inner [`UpgradeError`] type. /// Map the inner [`UpgradeError`] type.
pub fn map_upgrade_err<F, E>(self, f: F) -> ProtocolsHandlerUpgrErr<E> pub fn map_upgrade_err<F, E>(self, f: F) -> ConnectionHandlerUpgrErr<E>
where where
F: FnOnce(UpgradeError<TUpgrErr>) -> UpgradeError<E>, F: FnOnce(UpgradeError<TUpgrErr>) -> UpgradeError<E>,
{ {
match self { match self {
ProtocolsHandlerUpgrErr::Timeout => ProtocolsHandlerUpgrErr::Timeout, ConnectionHandlerUpgrErr::Timeout => ConnectionHandlerUpgrErr::Timeout,
ProtocolsHandlerUpgrErr::Timer => ProtocolsHandlerUpgrErr::Timer, ConnectionHandlerUpgrErr::Timer => ConnectionHandlerUpgrErr::Timer,
ProtocolsHandlerUpgrErr::Upgrade(e) => ProtocolsHandlerUpgrErr::Upgrade(f(e)), ConnectionHandlerUpgrErr::Upgrade(e) => ConnectionHandlerUpgrErr::Upgrade(f(e)),
} }
} }
} }
impl<TUpgrErr> fmt::Display for ProtocolsHandlerUpgrErr<TUpgrErr> impl<TUpgrErr> fmt::Display for ConnectionHandlerUpgrErr<TUpgrErr>
where where
TUpgrErr: fmt::Display, TUpgrErr: fmt::Display,
{ {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
ProtocolsHandlerUpgrErr::Timeout => { ConnectionHandlerUpgrErr::Timeout => {
write!(f, "Timeout error while opening a substream") write!(f, "Timeout error while opening a substream")
} }
ProtocolsHandlerUpgrErr::Timer => { ConnectionHandlerUpgrErr::Timer => {
write!(f, "Timer error while opening a substream") write!(f, "Timer error while opening a substream")
} }
ProtocolsHandlerUpgrErr::Upgrade(err) => write!(f, "{}", err), ConnectionHandlerUpgrErr::Upgrade(err) => write!(f, "{}", err),
} }
} }
} }
impl<TUpgrErr> error::Error for ProtocolsHandlerUpgrErr<TUpgrErr> impl<TUpgrErr> error::Error for ConnectionHandlerUpgrErr<TUpgrErr>
where where
TUpgrErr: error::Error + 'static, TUpgrErr: error::Error + 'static,
{ {
fn source(&self) -> Option<&(dyn error::Error + 'static)> { fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self { match self {
ProtocolsHandlerUpgrErr::Timeout => None, ConnectionHandlerUpgrErr::Timeout => None,
ProtocolsHandlerUpgrErr::Timer => None, ConnectionHandlerUpgrErr::Timer => None,
ProtocolsHandlerUpgrErr::Upgrade(err) => Some(err), ConnectionHandlerUpgrErr::Upgrade(err) => Some(err),
} }
} }
} }
/// Prototype for a `ProtocolsHandler`. /// Prototype for a [`ConnectionHandler`].
pub trait IntoProtocolsHandler: Send + 'static { pub trait IntoConnectionHandler: Send + 'static {
/// The protocols handler. /// The protocols handler.
type Handler: ProtocolsHandler; type Handler: ConnectionHandler;
/// Builds the protocols handler. /// Builds the protocols handler.
/// ///
@ -467,21 +468,21 @@ pub trait IntoProtocolsHandler: Send + 'static {
) -> Self::Handler; ) -> Self::Handler;
/// Return the handler's inbound protocol. /// Return the handler's inbound protocol.
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol; fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::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. /// other one together.
fn select<TProto2>(self, other: TProto2) -> IntoProtocolsHandlerSelect<Self, TProto2> fn select<TProto2>(self, other: TProto2) -> IntoConnectionHandlerSelect<Self, TProto2>
where where
Self: Sized, Self: Sized,
{ {
IntoProtocolsHandlerSelect::new(self, other) IntoConnectionHandlerSelect::new(self, other)
} }
} }
impl<T> IntoProtocolsHandler for T impl<T> IntoConnectionHandler for T
where where
T: ProtocolsHandler, T: ConnectionHandler,
{ {
type Handler = Self; type Handler = Self;
@ -489,7 +490,7 @@ where
self self
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
self.listen_protocol().into_upgrade().0 self.listen_protocol().into_upgrade().0
} }
} }

View File

@ -18,8 +18,9 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocols_handler::{ use crate::handler::{
KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
SubstreamProtocol,
}; };
use crate::NegotiatedSubstream; use crate::NegotiatedSubstream;
use libp2p_core::{ use libp2p_core::{
@ -29,21 +30,21 @@ use libp2p_core::{
use std::task::{Context, Poll}; use std::task::{Context, Poll};
use void::Void; use void::Void;
/// Implementation of `ProtocolsHandler` that doesn't handle anything. /// Implementation of [`ConnectionHandler`] that doesn't handle anything.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct DummyProtocolsHandler { pub struct DummyConnectionHandler {
pub keep_alive: KeepAlive, pub keep_alive: KeepAlive,
} }
impl Default for DummyProtocolsHandler { impl Default for DummyConnectionHandler {
fn default() -> Self { fn default() -> Self {
DummyProtocolsHandler { DummyConnectionHandler {
keep_alive: KeepAlive::No, keep_alive: KeepAlive::No,
} }
} }
} }
impl ProtocolsHandler for DummyProtocolsHandler { impl ConnectionHandler for DummyConnectionHandler {
type InEvent = Void; type InEvent = Void;
type OutEvent = Void; type OutEvent = Void;
type Error = Void; type Error = Void;
@ -81,7 +82,7 @@ impl ProtocolsHandler for DummyProtocolsHandler {
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
_: Self::OutboundOpenInfo, _: Self::OutboundOpenInfo,
_: ProtocolsHandlerUpgrErr< _: ConnectionHandlerUpgrErr<
<Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error, <Self::OutboundProtocol as OutboundUpgrade<NegotiatedSubstream>>::Error,
>, >,
) { ) {
@ -90,7 +91,7 @@ impl ProtocolsHandler for DummyProtocolsHandler {
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
_: Self::InboundOpenInfo, _: Self::InboundOpenInfo,
_: ProtocolsHandlerUpgrErr< _: ConnectionHandlerUpgrErr<
<Self::InboundProtocol as InboundUpgrade<NegotiatedSubstream>>::Error, <Self::InboundProtocol as InboundUpgrade<NegotiatedSubstream>>::Error,
>, >,
) { ) {
@ -104,7 +105,7 @@ impl ProtocolsHandler for DummyProtocolsHandler {
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,

View File

@ -18,9 +18,9 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocols_handler::{ use crate::handler::{
IntoProtocolsHandler, KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, KeepAlive, SubstreamProtocol,
}; };
use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper};
use either::Either; use either::Either;
@ -34,12 +34,12 @@ pub enum IntoEitherHandler<L, R> {
Right(R), Right(R),
} }
/// Implementation of a [`IntoProtocolsHandler`] that represents either of two [`IntoProtocolsHandler`] /// Implementation of a [`IntoConnectionHandler`] that represents either of two [`IntoConnectionHandler`]
/// implementations. /// implementations.
impl<L, R> IntoProtocolsHandler for IntoEitherHandler<L, R> impl<L, R> IntoConnectionHandler for IntoEitherHandler<L, R>
where where
L: IntoProtocolsHandler, L: IntoConnectionHandler,
R: IntoProtocolsHandler, R: IntoConnectionHandler,
{ {
type Handler = Either<L::Handler, R::Handler>; type Handler = Either<L::Handler, R::Handler>;
@ -52,7 +52,7 @@ where
} }
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
match self { match self {
IntoEitherHandler::Left(into_handler) => { IntoEitherHandler::Left(into_handler) => {
EitherUpgrade::A(SendWrapper(into_handler.inbound_protocol())) 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. /// implementations.
impl<L, R> ProtocolsHandler for Either<L, R> impl<L, R> ConnectionHandler for Either<L, R>
where where
L: ProtocolsHandler, L: ConnectionHandler,
R: ProtocolsHandler, R: ConnectionHandler,
{ {
type InEvent = Either<L::InEvent, R::InEvent>; type InEvent = Either<L::InEvent, R::InEvent>;
type OutEvent = Either<L::OutEvent, R::OutEvent>; type OutEvent = Either<L::OutEvent, R::OutEvent>;
@ -144,59 +144,59 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
info: Self::OutboundOpenInfo, info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
match error { match error {
ProtocolsHandlerUpgrErr::Timer => match (self, info) { ConnectionHandlerUpgrErr::Timer => match (self, info) {
(Either::Left(handler), Either::Left(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)) => { (Either::Right(handler), Either::Right(info)) => {
handler.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer); handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer);
} }
_ => unreachable!(), _ => unreachable!(),
}, },
ProtocolsHandlerUpgrErr::Timeout => match (self, info) { ConnectionHandlerUpgrErr::Timeout => match (self, info) {
(Either::Left(handler), Either::Left(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)) => { (Either::Right(handler), Either::Right(info)) => {
handler.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout); handler.inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout);
} }
_ => unreachable!(), _ => unreachable!(),
}, },
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => match (self, info) { ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => match (self, info) {
(Either::Left(handler), Either::Left(info)) => { (Either::Left(handler), Either::Left(info)) => {
handler.inject_dial_upgrade_error( handler.inject_dial_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)),
); );
} }
(Either::Right(handler), Either::Right(info)) => { (Either::Right(handler), Either::Right(info)) => {
handler.inject_dial_upgrade_error( handler.inject_dial_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)),
); );
} }
_ => unreachable!(), _ => unreachable!(),
}, },
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => {
match (self, info) { match (self, info) {
(Either::Left(handler), Either::Left(info)) => { (Either::Left(handler), Either::Left(info)) => {
handler.inject_dial_upgrade_error( handler.inject_dial_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)),
); );
} }
_ => unreachable!(), _ => unreachable!(),
} }
} }
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => {
match (self, info) { match (self, info) {
(Either::Right(handler), Either::Right(info)) => { (Either::Right(handler), Either::Right(info)) => {
handler.inject_dial_upgrade_error( handler.inject_dial_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)),
); );
} }
_ => unreachable!(), _ => unreachable!(),
@ -208,59 +208,59 @@ where
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
info: Self::InboundOpenInfo, info: Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
match error { match error {
ProtocolsHandlerUpgrErr::Timer => match (self, info) { ConnectionHandlerUpgrErr::Timer => match (self, info) {
(Either::Left(handler), Either::Left(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)) => { (Either::Right(handler), Either::Right(info)) => {
handler.inject_listen_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer); handler.inject_listen_upgrade_error(info, ConnectionHandlerUpgrErr::Timer);
} }
_ => unreachable!(), _ => unreachable!(),
}, },
ProtocolsHandlerUpgrErr::Timeout => match (self, info) { ConnectionHandlerUpgrErr::Timeout => match (self, info) {
(Either::Left(handler), Either::Left(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)) => { (Either::Right(handler), Either::Right(info)) => {
handler.inject_listen_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout); handler.inject_listen_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout);
} }
_ => unreachable!(), _ => unreachable!(),
}, },
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => match (self, info) { ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)) => match (self, info) {
(Either::Left(handler), Either::Left(info)) => { (Either::Left(handler), Either::Left(info)) => {
handler.inject_listen_upgrade_error( handler.inject_listen_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)),
); );
} }
(Either::Right(handler), Either::Right(info)) => { (Either::Right(handler), Either::Right(info)) => {
handler.inject_listen_upgrade_error( handler.inject_listen_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(error)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(error)),
); );
} }
_ => unreachable!(), _ => unreachable!(),
}, },
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => { ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(e))) => {
match (self, info) { match (self, info) {
(Either::Left(handler), Either::Left(info)) => { (Either::Left(handler), Either::Left(info)) => {
handler.inject_listen_upgrade_error( handler.inject_listen_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)),
); );
} }
_ => unreachable!(), _ => unreachable!(),
} }
} }
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => { ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(e))) => {
match (self, info) { match (self, info) {
(Either::Right(handler), Either::Right(info)) => { (Either::Right(handler), Either::Right(info)) => {
handler.inject_listen_upgrade_error( handler.inject_listen_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)),
); );
} }
_ => unreachable!(), _ => unreachable!(),
@ -280,7 +280,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,

View File

@ -18,8 +18,9 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocols_handler::{ use crate::handler::{
KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
SubstreamProtocol,
}; };
use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend}; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend};
use libp2p_core::Multiaddr; use libp2p_core::Multiaddr;
@ -43,9 +44,9 @@ impl<TProtoHandler, TMap, TNewIn> MapInEvent<TProtoHandler, TNewIn, TMap> {
} }
} }
impl<TProtoHandler, TMap, TNewIn> ProtocolsHandler for MapInEvent<TProtoHandler, TNewIn, TMap> impl<TProtoHandler, TMap, TNewIn> ConnectionHandler for MapInEvent<TProtoHandler, TNewIn, TMap>
where where
TProtoHandler: ProtocolsHandler, TProtoHandler: ConnectionHandler,
TMap: Fn(TNewIn) -> Option<TProtoHandler::InEvent>, TMap: Fn(TNewIn) -> Option<TProtoHandler::InEvent>,
TNewIn: Debug + Send + 'static, TNewIn: Debug + Send + 'static,
TMap: Send + 'static, TMap: Send + 'static,
@ -91,7 +92,7 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
info: Self::OutboundOpenInfo, info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
self.inner.inject_dial_upgrade_error(info, error) self.inner.inject_dial_upgrade_error(info, error)
} }
@ -99,7 +100,7 @@ where
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
info: Self::InboundOpenInfo, info: Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
self.inner.inject_listen_upgrade_error(info, error) self.inner.inject_listen_upgrade_error(info, error)
} }
@ -112,7 +113,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,

View File

@ -18,8 +18,9 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocols_handler::{ use crate::handler::{
KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
SubstreamProtocol,
}; };
use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend}; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend};
use libp2p_core::Multiaddr; use libp2p_core::Multiaddr;
@ -39,9 +40,9 @@ impl<TProtoHandler, TMap> MapOutEvent<TProtoHandler, TMap> {
} }
} }
impl<TProtoHandler, TMap, TNewOut> ProtocolsHandler for MapOutEvent<TProtoHandler, TMap> impl<TProtoHandler, TMap, TNewOut> ConnectionHandler for MapOutEvent<TProtoHandler, TMap>
where where
TProtoHandler: ProtocolsHandler, TProtoHandler: ConnectionHandler,
TMap: FnMut(TProtoHandler::OutEvent) -> TNewOut, TMap: FnMut(TProtoHandler::OutEvent) -> TNewOut,
TNewOut: Debug + Send + 'static, TNewOut: Debug + Send + 'static,
TMap: Send + 'static, TMap: Send + 'static,
@ -85,7 +86,7 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
info: Self::OutboundOpenInfo, info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
self.inner.inject_dial_upgrade_error(info, error) self.inner.inject_dial_upgrade_error(info, error)
} }
@ -93,7 +94,7 @@ where
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
info: Self::InboundOpenInfo, info: Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
self.inner.inject_listen_upgrade_error(info, error) self.inner.inject_listen_upgrade_error(info, error)
} }
@ -106,7 +107,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -114,10 +115,10 @@ where
>, >,
> { > {
self.inner.poll(cx).map(|ev| match ev { self.inner.poll(cx).map(|ev| match ev {
ProtocolsHandlerEvent::Custom(ev) => ProtocolsHandlerEvent::Custom((self.map)(ev)), ConnectionHandlerEvent::Custom(ev) => ConnectionHandlerEvent::Custom((self.map)(ev)),
ProtocolsHandlerEvent::Close(err) => ProtocolsHandlerEvent::Close(err), ConnectionHandlerEvent::Close(err) => ConnectionHandlerEvent::Close(err),
ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } => { ConnectionHandlerEvent::OutboundSubstreamRequest { protocol } => {
ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol } ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }
} }
}) })
} }

View File

@ -18,12 +18,12 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // 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. //! indexed by some key.
use crate::protocols_handler::{ use crate::handler::{
IntoProtocolsHandler, KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, KeepAlive, SubstreamProtocol,
}; };
use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, UpgradeInfoSend}; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, UpgradeInfoSend};
use crate::NegotiatedSubstream; use crate::NegotiatedSubstream;
@ -42,7 +42,7 @@ use std::{
time::Duration, time::Duration,
}; };
/// A [`ProtocolsHandler`] for multiple `ProtocolsHandler`s of the same type. /// A [`ConnectionHandler`] for multiple [`ConnectionHandler`]s of the same type.
#[derive(Clone)] #[derive(Clone)]
pub struct MultiHandler<K, H> { pub struct MultiHandler<K, H> {
handlers: HashMap<K, H>, handlers: HashMap<K, H>,
@ -63,7 +63,7 @@ where
impl<K, H> MultiHandler<K, H> impl<K, H> MultiHandler<K, H>
where where
K: Hash + Eq, K: Hash + Eq,
H: ProtocolsHandler, H: ConnectionHandler,
{ {
/// Create and populate a `MultiHandler` from the given handler iterator. /// Create and populate a `MultiHandler` from the given handler iterator.
/// ///
@ -84,20 +84,20 @@ where
} }
} }
impl<K, H> ProtocolsHandler for MultiHandler<K, H> impl<K, H> ConnectionHandler for MultiHandler<K, H>
where where
K: Clone + Debug + Hash + Eq + Send + 'static, K: Clone + Debug + Hash + Eq + Send + 'static,
H: ProtocolsHandler, H: ConnectionHandler,
H::InboundProtocol: InboundUpgradeSend, H::InboundProtocol: InboundUpgradeSend,
H::OutboundProtocol: OutboundUpgradeSend, H::OutboundProtocol: OutboundUpgradeSend,
{ {
type InEvent = (K, <H as ProtocolsHandler>::InEvent); type InEvent = (K, <H as ConnectionHandler>::InEvent);
type OutEvent = (K, <H as ProtocolsHandler>::OutEvent); type OutEvent = (K, <H as ConnectionHandler>::OutEvent);
type Error = <H as ProtocolsHandler>::Error; type Error = <H as ConnectionHandler>::Error;
type InboundProtocol = Upgrade<K, <H as ProtocolsHandler>::InboundProtocol>; type InboundProtocol = Upgrade<K, <H as ConnectionHandler>::InboundProtocol>;
type OutboundProtocol = <H as ProtocolsHandler>::OutboundProtocol; type OutboundProtocol = <H as ConnectionHandler>::OutboundProtocol;
type InboundOpenInfo = Info<K, <H as ProtocolsHandler>::InboundOpenInfo>; type InboundOpenInfo = Info<K, <H as ConnectionHandler>::InboundOpenInfo>;
type OutboundOpenInfo = (K, <H as ProtocolsHandler>::OutboundOpenInfo); type OutboundOpenInfo = (K, <H as ConnectionHandler>::OutboundOpenInfo);
fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> { fn listen_protocol(&self) -> SubstreamProtocol<Self::InboundProtocol, Self::InboundOpenInfo> {
let (upgrade, info, timeout) = self let (upgrade, info, timeout) = self
@ -164,7 +164,7 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
(key, arg): Self::OutboundOpenInfo, (key, arg): Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
if let Some(h) = self.handlers.get_mut(&key) { if let Some(h) = self.handlers.get_mut(&key) {
h.inject_dial_upgrade_error(arg, error) h.inject_dial_upgrade_error(arg, error)
@ -176,36 +176,36 @@ where
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
mut info: Self::InboundOpenInfo, mut info: Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
match error { match error {
ProtocolsHandlerUpgrErr::Timer => { ConnectionHandlerUpgrErr::Timer => {
for (k, h) in &mut self.handlers { for (k, h) in &mut self.handlers {
if let Some(i) = info.take(k) { 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 { for (k, h) in &mut self.handlers {
if let Some(i) = info.take(k) { 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 { for (k, h) in &mut self.handlers {
if let Some(i) = info.take(k) { if let Some(i) = info.take(k) {
h.inject_listen_upgrade_error( h.inject_listen_upgrade_error(
i, i,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(
NegotiationError::Failed, NegotiationError::Failed,
)), )),
) )
} }
} }
} }
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(
NegotiationError::ProtocolError(e), NegotiationError::ProtocolError(e),
)) => match e { )) => match e {
ProtocolError::IoError(e) => { ProtocolError::IoError(e) => {
@ -216,7 +216,7 @@ where
)); ));
h.inject_listen_upgrade_error( h.inject_listen_upgrade_error(
i, i,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)),
) )
} }
} }
@ -227,7 +227,7 @@ where
let e = NegotiationError::ProtocolError(ProtocolError::InvalidMessage); let e = NegotiationError::ProtocolError(ProtocolError::InvalidMessage);
h.inject_listen_upgrade_error( h.inject_listen_upgrade_error(
i, i,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)),
) )
} }
} }
@ -238,7 +238,7 @@ where
let e = NegotiationError::ProtocolError(ProtocolError::InvalidProtocol); let e = NegotiationError::ProtocolError(ProtocolError::InvalidProtocol);
h.inject_listen_upgrade_error( h.inject_listen_upgrade_error(
i, i,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e)),
) )
} }
} }
@ -250,18 +250,18 @@ where
NegotiationError::ProtocolError(ProtocolError::TooManyProtocols); NegotiationError::ProtocolError(ProtocolError::TooManyProtocols);
h.inject_listen_upgrade_error( h.inject_listen_upgrade_error(
i, 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(h) = self.handlers.get_mut(&k) {
if let Some(i) = info.take(&k) { if let Some(i) = info.take(&k) {
h.inject_listen_upgrade_error( h.inject_listen_upgrade_error(
i, i,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)),
) )
} }
} }
@ -281,7 +281,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -319,7 +319,7 @@ where
} }
} }
/// A [`IntoProtocolsHandler`] for multiple other `IntoProtocolsHandler`s. /// A [`IntoConnectionHandler`] for multiple other `IntoConnectionHandler`s.
#[derive(Clone)] #[derive(Clone)]
pub struct IntoMultiHandler<K, H> { pub struct IntoMultiHandler<K, H> {
handlers: HashMap<K, H>, handlers: HashMap<K, H>,
@ -340,7 +340,7 @@ where
impl<K, H> IntoMultiHandler<K, H> impl<K, H> IntoMultiHandler<K, H>
where where
K: Hash + Eq, K: Hash + Eq,
H: IntoProtocolsHandler, H: IntoConnectionHandler,
{ {
/// Create and populate an `IntoMultiHandler` from the given iterator. /// Create and populate an `IntoMultiHandler` from the given iterator.
/// ///
@ -357,10 +357,10 @@ where
} }
} }
impl<K, H> IntoProtocolsHandler for IntoMultiHandler<K, H> impl<K, H> IntoConnectionHandler for IntoMultiHandler<K, H>
where where
K: Debug + Clone + Eq + Hash + Send + 'static, K: Debug + Clone + Eq + Hash + Send + 'static,
H: IntoProtocolsHandler, H: IntoConnectionHandler,
{ {
type Handler = MultiHandler<K, H::Handler>; type Handler = MultiHandler<K, H::Handler>;
@ -374,7 +374,7 @@ where
} }
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
Upgrade { Upgrade {
upgrades: self upgrades: self
.handlers .handlers
@ -414,7 +414,7 @@ impl<K: Eq, I> Info<K, I> {
} }
} }
/// Inbound and outbound upgrade for all `ProtocolsHandler`s. /// Inbound and outbound upgrade for all [`ConnectionHandler`]s.
#[derive(Clone)] #[derive(Clone)]
pub struct Upgrade<K, H> { pub struct Upgrade<K, H> {
upgrades: Vec<(K, H)>, upgrades: Vec<(K, H)>,

View File

@ -18,15 +18,16 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocols_handler::{ use crate::handler::{
KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerUpgrErr, SubstreamProtocol, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive,
SubstreamProtocol,
}; };
use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend}; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend};
use instant::Instant; use instant::Instant;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{error, fmt::Debug, task::Context, task::Poll, time::Duration}; 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 // TODO: Debug
pub struct OneShotHandler<TInbound, TOutbound, TEvent> pub struct OneShotHandler<TInbound, TOutbound, TEvent>
where where
@ -35,7 +36,7 @@ where
/// The upgrade for inbound substreams. /// The upgrade for inbound substreams.
listen_protocol: SubstreamProtocol<TInbound, ()>, listen_protocol: SubstreamProtocol<TInbound, ()>,
/// If `Some`, something bad happened and we should shut down the handler with an error. /// If `Some`, something bad happened and we should shut down the handler with an error.
pending_error: Option<ProtocolsHandlerUpgrErr<<TOutbound as OutboundUpgradeSend>::Error>>, pending_error: Option<ConnectionHandlerUpgrErr<<TOutbound as OutboundUpgradeSend>::Error>>,
/// Queue of events to produce in `poll()`. /// Queue of events to produce in `poll()`.
events_out: SmallVec<[TEvent; 4]>, events_out: SmallVec<[TEvent; 4]>,
/// Queue of outbound substreams to open. /// Queue of outbound substreams to open.
@ -109,7 +110,7 @@ where
} }
} }
impl<TInbound, TOutbound, TEvent> ProtocolsHandler for OneShotHandler<TInbound, TOutbound, TEvent> impl<TInbound, TOutbound, TEvent> ConnectionHandler for OneShotHandler<TInbound, TOutbound, TEvent>
where where
TInbound: InboundUpgradeSend + Send + 'static, TInbound: InboundUpgradeSend + Send + 'static,
TOutbound: Debug + OutboundUpgradeSend, TOutbound: Debug + OutboundUpgradeSend,
@ -121,7 +122,7 @@ where
{ {
type InEvent = TOutbound; type InEvent = TOutbound;
type OutEvent = TEvent; type OutEvent = TEvent;
type Error = ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>; type Error = ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>;
type InboundProtocol = TInbound; type InboundProtocol = TInbound;
type OutboundProtocol = TOutbound; type OutboundProtocol = TOutbound;
type OutboundOpenInfo = (); type OutboundOpenInfo = ();
@ -160,7 +161,7 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
_info: Self::OutboundOpenInfo, _info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
if self.pending_error.is_none() { if self.pending_error.is_none() {
self.pending_error = Some(error); self.pending_error = Some(error);
@ -175,7 +176,7 @@ where
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -183,11 +184,11 @@ where
>, >,
> { > {
if let Some(err) = self.pending_error.take() { 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() { 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 { } else {
self.events_out.shrink_to_fit(); self.events_out.shrink_to_fit();
} }
@ -196,7 +197,7 @@ where
if self.dial_negotiated < self.config.max_dial_negotiated { if self.dial_negotiated < self.config.max_dial_negotiated {
self.dial_negotiated += 1; self.dial_negotiated += 1;
let upgrade = self.dial_queue.remove(0); let upgrade = self.dial_queue.remove(0);
return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: SubstreamProtocol::new(upgrade, ()) protocol: SubstreamProtocol::new(upgrade, ())
.with_timeout(self.config.outbound_substream_timeout), .with_timeout(self.config.outbound_substream_timeout),
}); });

View File

@ -18,9 +18,9 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::protocols_handler::{ use crate::handler::{
IntoProtocolsHandler, KeepAlive, ProtocolsHandler, ProtocolsHandlerEvent, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, KeepAlive, SubstreamProtocol,
}; };
use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper}; use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper};
@ -31,19 +31,19 @@ use libp2p_core::{
}; };
use std::{cmp, task::Context, task::Poll}; 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)] #[derive(Debug, Clone)]
pub struct IntoProtocolsHandlerSelect<TProto1, TProto2> { pub struct IntoConnectionHandlerSelect<TProto1, TProto2> {
/// The first protocol. /// The first protocol.
proto1: TProto1, proto1: TProto1,
/// The second protocol. /// The second protocol.
proto2: TProto2, proto2: TProto2,
} }
impl<TProto1, TProto2> IntoProtocolsHandlerSelect<TProto1, TProto2> { impl<TProto1, TProto2> IntoConnectionHandlerSelect<TProto1, TProto2> {
/// Builds a `IntoProtocolsHandlerSelect`. /// Builds a `IntoConnectionHandlerSelect`.
pub(crate) fn new(proto1: TProto1, proto2: TProto2) -> Self { pub(crate) fn new(proto1: TProto1, proto2: TProto2) -> Self {
IntoProtocolsHandlerSelect { proto1, proto2 } IntoConnectionHandlerSelect { proto1, proto2 }
} }
pub fn into_inner(self) -> (TProto1, TProto2) { pub fn into_inner(self) -> (TProto1, TProto2) {
@ -51,25 +51,25 @@ impl<TProto1, TProto2> IntoProtocolsHandlerSelect<TProto1, TProto2> {
} }
} }
impl<TProto1, TProto2> IntoProtocolsHandler for IntoProtocolsHandlerSelect<TProto1, TProto2> impl<TProto1, TProto2> IntoConnectionHandler for IntoConnectionHandlerSelect<TProto1, TProto2>
where where
TProto1: IntoProtocolsHandler, TProto1: IntoConnectionHandler,
TProto2: IntoProtocolsHandler, TProto2: IntoConnectionHandler,
{ {
type Handler = ProtocolsHandlerSelect<TProto1::Handler, TProto2::Handler>; type Handler = ConnectionHandlerSelect<TProto1::Handler, TProto2::Handler>;
fn into_handler( fn into_handler(
self, self,
remote_peer_id: &PeerId, remote_peer_id: &PeerId,
connected_point: &ConnectedPoint, connected_point: &ConnectedPoint,
) -> Self::Handler { ) -> Self::Handler {
ProtocolsHandlerSelect { ConnectionHandlerSelect {
proto1: self.proto1.into_handler(remote_peer_id, connected_point), proto1: self.proto1.into_handler(remote_peer_id, connected_point),
proto2: self.proto2.into_handler(remote_peer_id, connected_point), proto2: self.proto2.into_handler(remote_peer_id, connected_point),
} }
} }
fn inbound_protocol(&self) -> <Self::Handler as ProtocolsHandler>::InboundProtocol { fn inbound_protocol(&self) -> <Self::Handler as ConnectionHandler>::InboundProtocol {
SelectUpgrade::new( SelectUpgrade::new(
SendWrapper(self.proto1.inbound_protocol()), SendWrapper(self.proto1.inbound_protocol()),
SendWrapper(self.proto2.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)] #[derive(Debug, Clone)]
pub struct ProtocolsHandlerSelect<TProto1, TProto2> { pub struct ConnectionHandlerSelect<TProto1, TProto2> {
/// The first protocol. /// The first protocol.
proto1: TProto1, proto1: TProto1,
/// The second protocol. /// The second protocol.
proto2: TProto2, proto2: TProto2,
} }
impl<TProto1, TProto2> ProtocolsHandlerSelect<TProto1, TProto2> { impl<TProto1, TProto2> ConnectionHandlerSelect<TProto1, TProto2> {
/// Builds a `ProtocolsHandlerSelect`. /// Builds a [`ConnectionHandlerSelect`].
pub(crate) fn new(proto1: TProto1, proto2: TProto2) -> Self { pub(crate) fn new(proto1: TProto1, proto2: TProto2) -> Self {
ProtocolsHandlerSelect { proto1, proto2 } ConnectionHandlerSelect { proto1, proto2 }
} }
pub fn into_inner(self) -> (TProto1, TProto2) { pub fn into_inner(self) -> (TProto1, TProto2) {
@ -97,17 +97,17 @@ impl<TProto1, TProto2> ProtocolsHandlerSelect<TProto1, TProto2> {
} }
} }
impl<TProto1, TProto2> ProtocolsHandler for ProtocolsHandlerSelect<TProto1, TProto2> impl<TProto1, TProto2> ConnectionHandler for ConnectionHandlerSelect<TProto1, TProto2>
where where
TProto1: ProtocolsHandler, TProto1: ConnectionHandler,
TProto2: ProtocolsHandler, TProto2: ConnectionHandler,
{ {
type InEvent = EitherOutput<TProto1::InEvent, TProto2::InEvent>; type InEvent = EitherOutput<TProto1::InEvent, TProto2::InEvent>;
type OutEvent = EitherOutput<TProto1::OutEvent, TProto2::OutEvent>; type OutEvent = EitherOutput<TProto1::OutEvent, TProto2::OutEvent>;
type Error = EitherError<TProto1::Error, TProto2::Error>; type Error = EitherError<TProto1::Error, TProto2::Error>;
type InboundProtocol = SelectUpgrade< type InboundProtocol = SelectUpgrade<
SendWrapper<<TProto1 as ProtocolsHandler>::InboundProtocol>, SendWrapper<<TProto1 as ConnectionHandler>::InboundProtocol>,
SendWrapper<<TProto2 as ProtocolsHandler>::InboundProtocol>, SendWrapper<<TProto2 as ConnectionHandler>::InboundProtocol>,
>; >;
type OutboundProtocol = EitherUpgrade< type OutboundProtocol = EitherUpgrade<
SendWrapper<TProto1::OutboundProtocol>, SendWrapper<TProto1::OutboundProtocol>,
@ -177,58 +177,58 @@ where
fn inject_dial_upgrade_error( fn inject_dial_upgrade_error(
&mut self, &mut self,
info: Self::OutboundOpenInfo, info: Self::OutboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::OutboundProtocol as OutboundUpgradeSend>::Error>,
) { ) {
match (info, error) { match (info, error) {
(EitherOutput::First(info), ProtocolsHandlerUpgrErr::Timer) => self (EitherOutput::First(info), ConnectionHandlerUpgrErr::Timer) => self
.proto1 .proto1
.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer), .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer),
(EitherOutput::First(info), ProtocolsHandlerUpgrErr::Timeout) => self (EitherOutput::First(info), ConnectionHandlerUpgrErr::Timeout) => self
.proto1 .proto1
.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout), .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout),
( (
EitherOutput::First(info), EitherOutput::First(info),
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)),
) => self.proto1.inject_dial_upgrade_error( ) => self.proto1.inject_dial_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)),
), ),
( (
EitherOutput::First(info), EitherOutput::First(info),
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(err))), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::A(err))),
) => self.proto1.inject_dial_upgrade_error( ) => self.proto1.inject_dial_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)),
), ),
( (
EitherOutput::First(_), 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"); 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 .proto2
.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timeout), .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timeout),
(EitherOutput::Second(info), ProtocolsHandlerUpgrErr::Timer) => self (EitherOutput::Second(info), ConnectionHandlerUpgrErr::Timer) => self
.proto2 .proto2
.inject_dial_upgrade_error(info, ProtocolsHandlerUpgrErr::Timer), .inject_dial_upgrade_error(info, ConnectionHandlerUpgrErr::Timer),
( (
EitherOutput::Second(info), EitherOutput::Second(info),
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)),
) => self.proto2.inject_dial_upgrade_error( ) => self.proto2.inject_dial_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(err)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(err)),
), ),
( (
EitherOutput::Second(info), EitherOutput::Second(info),
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(err))), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(EitherError::B(err))),
) => self.proto2.inject_dial_upgrade_error( ) => self.proto2.inject_dial_upgrade_error(
info, info,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(err)),
), ),
( (
EitherOutput::Second(_), 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"); panic!("Wrong API usage; the upgrade error doesn't match the outbound open info");
} }
@ -238,36 +238,36 @@ where
fn inject_listen_upgrade_error( fn inject_listen_upgrade_error(
&mut self, &mut self,
(i1, i2): Self::InboundOpenInfo, (i1, i2): Self::InboundOpenInfo,
error: ProtocolsHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>, error: ConnectionHandlerUpgrErr<<Self::InboundProtocol as InboundUpgradeSend>::Error>,
) { ) {
match error { match error {
ProtocolsHandlerUpgrErr::Timer => { ConnectionHandlerUpgrErr::Timer => {
self.proto1 self.proto1
.inject_listen_upgrade_error(i1, ProtocolsHandlerUpgrErr::Timer); .inject_listen_upgrade_error(i1, ConnectionHandlerUpgrErr::Timer);
self.proto2 self.proto2
.inject_listen_upgrade_error(i2, ProtocolsHandlerUpgrErr::Timer) .inject_listen_upgrade_error(i2, ConnectionHandlerUpgrErr::Timer)
} }
ProtocolsHandlerUpgrErr::Timeout => { ConnectionHandlerUpgrErr::Timeout => {
self.proto1 self.proto1
.inject_listen_upgrade_error(i1, ProtocolsHandlerUpgrErr::Timeout); .inject_listen_upgrade_error(i1, ConnectionHandlerUpgrErr::Timeout);
self.proto2 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( self.proto1.inject_listen_upgrade_error(
i1, i1,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(
NegotiationError::Failed, NegotiationError::Failed,
)), )),
); );
self.proto2.inject_listen_upgrade_error( self.proto2.inject_listen_upgrade_error(
i2, i2,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(
NegotiationError::Failed, NegotiationError::Failed,
)), )),
); );
} }
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select( ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(
NegotiationError::ProtocolError(e), NegotiationError::ProtocolError(e),
)) => { )) => {
let (e1, e2); let (e1, e2);
@ -293,23 +293,23 @@ where
} }
self.proto1.inject_listen_upgrade_error( self.proto1.inject_listen_upgrade_error(
i1, i1,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Select(e1)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Select(e1)),
); );
self.proto2.inject_listen_upgrade_error( self.proto2.inject_listen_upgrade_error(
i2, 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( self.proto1.inject_listen_upgrade_error(
i1, 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( self.proto2.inject_listen_upgrade_error(
i2, i2,
ProtocolsHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)), ConnectionHandlerUpgrErr::Upgrade(UpgradeError::Apply(e)),
) )
} }
} }
@ -326,7 +326,7 @@ where
&mut self, &mut self,
cx: &mut Context<'_>, cx: &mut Context<'_>,
) -> Poll< ) -> Poll<
ProtocolsHandlerEvent< ConnectionHandlerEvent<
Self::OutboundProtocol, Self::OutboundProtocol,
Self::OutboundOpenInfo, Self::OutboundOpenInfo,
Self::OutEvent, Self::OutEvent,
@ -334,14 +334,14 @@ where
>, >,
> { > {
match self.proto1.poll(cx) { match self.proto1.poll(cx) {
Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => { Poll::Ready(ConnectionHandlerEvent::Custom(event)) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(EitherOutput::First(event))); return Poll::Ready(ConnectionHandlerEvent::Custom(EitherOutput::First(event)));
} }
Poll::Ready(ProtocolsHandlerEvent::Close(event)) => { Poll::Ready(ConnectionHandlerEvent::Close(event)) => {
return Poll::Ready(ProtocolsHandlerEvent::Close(EitherError::A(event))); return Poll::Ready(ConnectionHandlerEvent::Close(EitherError::A(event)));
} }
Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }) => { Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }) => {
return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: protocol protocol: protocol
.map_upgrade(|u| EitherUpgrade::A(SendWrapper(u))) .map_upgrade(|u| EitherUpgrade::A(SendWrapper(u)))
.map_info(EitherOutput::First), .map_info(EitherOutput::First),
@ -351,14 +351,14 @@ where
}; };
match self.proto2.poll(cx) { match self.proto2.poll(cx) {
Poll::Ready(ProtocolsHandlerEvent::Custom(event)) => { Poll::Ready(ConnectionHandlerEvent::Custom(event)) => {
return Poll::Ready(ProtocolsHandlerEvent::Custom(EitherOutput::Second(event))); return Poll::Ready(ConnectionHandlerEvent::Custom(EitherOutput::Second(event)));
} }
Poll::Ready(ProtocolsHandlerEvent::Close(event)) => { Poll::Ready(ConnectionHandlerEvent::Close(event)) => {
return Poll::Ready(ProtocolsHandlerEvent::Close(EitherError::B(event))); return Poll::Ready(ConnectionHandlerEvent::Close(EitherError::B(event)));
} }
Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { protocol }) => { Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest { protocol }) => {
return Poll::Ready(ProtocolsHandlerEvent::OutboundSubstreamRequest { return Poll::Ready(ConnectionHandlerEvent::OutboundSubstreamRequest {
protocol: protocol protocol: protocol
.map_upgrade(|u| EitherUpgrade::B(SendWrapper(u))) .map_upgrade(|u| EitherUpgrade::B(SendWrapper(u)))
.map_info(EitherOutput::Second), .map_info(EitherOutput::Second),

View File

@ -48,7 +48,7 @@
//! //!
//! # Protocols Handler //! # 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 //! remote should behave: how to handle incoming substreams, which protocols
//! are supported, when to open a new outbound substream, etc. //! are supported, when to open a new outbound substream, etc.
//! //!
@ -61,7 +61,7 @@ mod upgrade;
pub mod behaviour; pub mod behaviour;
pub mod dial_opts; pub mod dial_opts;
pub mod protocols_handler; pub mod handler;
pub use behaviour::{ pub use behaviour::{
CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess, CloseConnection, NetworkBehaviour, NetworkBehaviourAction, NetworkBehaviourEventProcess,
@ -71,10 +71,10 @@ pub use connection::{
ConnectionCounters, ConnectionError, ConnectionLimit, ConnectionLimits, PendingConnectionError, ConnectionCounters, ConnectionError, ConnectionLimit, ConnectionLimits, PendingConnectionError,
PendingInboundConnectionError, PendingOutboundConnectionError, PendingInboundConnectionError, PendingOutboundConnectionError,
}; };
pub use protocols_handler::{ pub use handler::{
IntoProtocolsHandler, IntoProtocolsHandlerSelect, KeepAlive, OneShotHandler, ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerSelect, ConnectionHandlerUpgrErr,
OneShotHandlerConfig, ProtocolsHandler, ProtocolsHandlerEvent, ProtocolsHandlerSelect, IntoConnectionHandler, IntoConnectionHandlerSelect, KeepAlive, OneShotHandler,
ProtocolsHandlerUpgrErr, SubstreamProtocol, OneShotHandlerConfig, SubstreamProtocol,
}; };
pub use registry::{AddAddressResult, AddressRecord, AddressScore}; pub use registry::{AddAddressResult, AddressRecord, AddressScore};
@ -115,22 +115,22 @@ pub type NegotiatedSubstream = Negotiated<Substream<StreamMuxerBox>>;
/// Event generated by the [`NetworkBehaviour`] that the swarm will report back. /// Event generated by the [`NetworkBehaviour`] that the swarm will report back.
type TBehaviourOutEvent<TBehaviour> = <TBehaviour as NetworkBehaviour>::OutEvent; type TBehaviourOutEvent<TBehaviour> = <TBehaviour as NetworkBehaviour>::OutEvent;
/// [`ProtocolsHandler`] of the [`NetworkBehaviour`] for all the protocols the [`NetworkBehaviour`] /// [`ConnectionHandler`] of the [`NetworkBehaviour`] for all the protocols the [`NetworkBehaviour`]
/// supports. /// supports.
type THandler<TBehaviour> = <TBehaviour as NetworkBehaviour>::ProtocolsHandler; type THandler<TBehaviour> = <TBehaviour as NetworkBehaviour>::ConnectionHandler;
/// Custom event that can be received by the [`ProtocolsHandler`] of the /// Custom event that can be received by the [`ConnectionHandler`] of the
/// [`NetworkBehaviour`]. /// [`NetworkBehaviour`].
type THandlerInEvent<TBehaviour> = type THandlerInEvent<TBehaviour> =
<<THandler<TBehaviour> as IntoProtocolsHandler>::Handler as ProtocolsHandler>::InEvent; <<THandler<TBehaviour> 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<TBehaviour> = type THandlerOutEvent<TBehaviour> =
<<THandler<TBehaviour> as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent; <<THandler<TBehaviour> 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<TBehaviour> = type THandlerErr<TBehaviour> =
<<THandler<TBehaviour> as IntoProtocolsHandler>::Handler as ProtocolsHandler>::Error; <<THandler<TBehaviour> as IntoConnectionHandler>::Handler as ConnectionHandler>::Error;
/// Event generated by the `Swarm`. /// Event generated by the `Swarm`.
#[derive(Debug)] #[derive(Debug)]
@ -370,7 +370,7 @@ where
fn dial_with_handler( fn dial_with_handler(
&mut self, &mut self,
swarm_dial_opts: DialOpts, swarm_dial_opts: DialOpts,
handler: <TBehaviour as NetworkBehaviour>::ProtocolsHandler, handler: <TBehaviour as NetworkBehaviour>::ConnectionHandler,
) -> Result<(), DialError> { ) -> Result<(), DialError> {
let (peer_id, addresses, dial_concurrency_factor_override, role_override) = let (peer_id, addresses, dial_concurrency_factor_override, role_override) =
match swarm_dial_opts.0 { match swarm_dial_opts.0 {
@ -604,11 +604,11 @@ where
/// Returns `Ok(())` if there was one or more established connections to the peer. /// Returns `Ok(())` if there was one or more established connections to the peer.
/// ///
/// Note: Closing a connection via [`Swarm::disconnect_peer_id`] does /// Note: Closing a connection via [`Swarm::disconnect_peer_id`] does
/// not inform the corresponding [`ProtocolsHandler`]. /// not inform the corresponding [`ConnectionHandler`].
/// Closing a connection via a [`ProtocolsHandler`] can be done either in a /// Closing a connection via a [`ConnectionHandler`] can be done either in a
/// collaborative manner across [`ProtocolsHandler`]s /// collaborative manner across [`ConnectionHandler`]s
/// with [`ProtocolsHandler::connection_keep_alive`] or directly with /// with [`ConnectionHandler::connection_keep_alive`] or directly with
/// [`ProtocolsHandlerEvent::Close`]. /// [`ConnectionHandlerEvent::Close`].
pub fn disconnect_peer_id(&mut self, peer_id: PeerId) -> Result<(), ()> { pub fn disconnect_peer_id(&mut self, peer_id: PeerId) -> Result<(), ()> {
let was_connected = self.pool.is_connected(peer_id); let was_connected = self.pool.is_connected(peer_id);
self.pool.disconnect(peer_id); self.pool.disconnect(peer_id);
@ -1120,8 +1120,8 @@ where
TTrans: Transport, TTrans: Transport,
TTrans::Error: Send + 'static, TTrans::Error: Send + 'static,
TBehaviour: NetworkBehaviour, TBehaviour: NetworkBehaviour,
THandler: IntoProtocolsHandler, THandler: IntoConnectionHandler,
THandler::Handler: ProtocolsHandler< THandler::Handler: ConnectionHandler<
InEvent = THandlerInEvent<TBehaviour>, InEvent = THandlerInEvent<TBehaviour>,
OutEvent = THandlerOutEvent<TBehaviour>, OutEvent = THandlerOutEvent<TBehaviour>,
>, >,
@ -1253,7 +1253,7 @@ where
} }
/// Configures the number of events from the [`NetworkBehaviour`] in /// 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 /// the [`Swarm`] has to wait. An individual buffer with this number of
/// events exists for each individual connection. /// events exists for each individual connection.
/// ///
@ -1266,14 +1266,14 @@ where
self 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 /// 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 /// that the [`NetworkBehaviour`] has yet to process. This buffer is
/// shared between all instances of [`ProtocolsHandler`]. Each instance of /// shared between all instances of [`ConnectionHandler`]. Each instance of
/// [`ProtocolsHandler`] is guaranteed one slot in this buffer, meaning /// [`ConnectionHandler`] is guaranteed one slot in this buffer, meaning
/// that delivering an event for the first time is guaranteed to be /// that delivering an event for the first time is guaranteed to be
/// instantaneous. Any extra event delivery, however, must wait for that /// instantaneous. Any extra event delivery, however, must wait for that
/// first event to be delivered or for an "extra slot" to be available. /// 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 /// The ideal value depends on the executor used, the CPU speed, the
/// average number of connections, and the volume of events. If this value /// 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 /// than necessary. Increasing this value increases the overall memory
/// usage, and more importantly the latency between the moment when an /// usage, and more importantly the latency between the moment when an
/// event is emitted and the moment when it is received by the /// event is emitted and the moment when it is received by the
@ -1478,11 +1478,11 @@ impl Default for DummyBehaviour {
} }
impl NetworkBehaviour for DummyBehaviour { impl NetworkBehaviour for DummyBehaviour {
type ProtocolsHandler = protocols_handler::DummyProtocolsHandler; type ConnectionHandler = handler::DummyConnectionHandler;
type OutEvent = void::Void; type OutEvent = void::Void;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
protocols_handler::DummyProtocolsHandler { handler::DummyConnectionHandler {
keep_alive: self.keep_alive, keep_alive: self.keep_alive,
} }
} }
@ -1491,7 +1491,7 @@ impl NetworkBehaviour for DummyBehaviour {
&mut self, &mut self,
_: PeerId, _: PeerId,
_: ConnectionId, _: ConnectionId,
event: <Self::ProtocolsHandler as ProtocolsHandler>::OutEvent, event: <Self::ConnectionHandler as ConnectionHandler>::OutEvent,
) { ) {
void::unreachable(event) void::unreachable(event)
} }
@ -1500,7 +1500,7 @@ impl NetworkBehaviour for DummyBehaviour {
&mut self, &mut self,
_: &mut Context<'_>, _: &mut Context<'_>,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
Poll::Pending Poll::Pending
} }
} }
@ -1530,7 +1530,7 @@ impl NetworkInfo {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::protocols_handler::DummyProtocolsHandler; use crate::handler::DummyConnectionHandler;
use crate::test::{CallTraceBehaviour, MockBehaviour}; use crate::test::{CallTraceBehaviour, MockBehaviour};
use futures::executor::block_on; use futures::executor::block_on;
use futures::future::poll_fn; use futures::future::poll_fn;
@ -1557,7 +1557,7 @@ mod tests {
handler_proto: T, handler_proto: T,
) -> SwarmBuilder<CallTraceBehaviour<MockBehaviour<T, O>>> ) -> SwarmBuilder<CallTraceBehaviour<MockBehaviour<T, O>>>
where where
T: ProtocolsHandler + Clone, T: ConnectionHandler + Clone,
T::OutEvent: Clone, T::OutEvent: Clone,
O: Send + 'static, O: Send + 'static,
{ {
@ -1581,7 +1581,7 @@ mod tests {
) -> bool ) -> bool
where where
TBehaviour: NetworkBehaviour, TBehaviour: NetworkBehaviour,
<<TBehaviour::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent: Clone, <<TBehaviour::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent: Clone,
{ {
[swarm1, swarm2] [swarm1, swarm2]
.iter() .iter()
@ -1595,7 +1595,7 @@ mod tests {
) -> bool ) -> bool
where where
TBehaviour: NetworkBehaviour, TBehaviour: NetworkBehaviour,
<<TBehaviour::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent: Clone <<TBehaviour::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent: Clone
{ {
[swarm1, swarm2] [swarm1, swarm2]
.iter() .iter()
@ -1621,7 +1621,7 @@ mod tests {
fn test_connect_disconnect_ban() { fn test_connect_disconnect_ban() {
// Since the test does not try to open any substreams, we can // Since the test does not try to open any substreams, we can
// use the dummy protocols handler. // use the dummy protocols handler.
let handler_proto = DummyProtocolsHandler { let handler_proto = DummyConnectionHandler {
keep_alive: KeepAlive::Yes, keep_alive: KeepAlive::Yes,
}; };
@ -1742,7 +1742,7 @@ mod tests {
fn test_swarm_disconnect() { fn test_swarm_disconnect() {
// Since the test does not try to open any substreams, we can // Since the test does not try to open any substreams, we can
// use the dummy protocols handler. // use the dummy protocols handler.
let handler_proto = DummyProtocolsHandler { let handler_proto = DummyConnectionHandler {
keep_alive: KeepAlive::Yes, keep_alive: KeepAlive::Yes,
}; };
@ -1811,7 +1811,7 @@ mod tests {
fn test_behaviour_disconnect_all() { fn test_behaviour_disconnect_all() {
// Since the test does not try to open any substreams, we can // Since the test does not try to open any substreams, we can
// use the dummy protocols handler. // use the dummy protocols handler.
let handler_proto = DummyProtocolsHandler { let handler_proto = DummyConnectionHandler {
keep_alive: KeepAlive::Yes, keep_alive: KeepAlive::Yes,
}; };
@ -1883,7 +1883,7 @@ mod tests {
fn test_behaviour_disconnect_one() { fn test_behaviour_disconnect_one() {
// Since the test does not try to open any substreams, we can // Since the test does not try to open any substreams, we can
// use the dummy protocols handler. // use the dummy protocols handler.
let handler_proto = DummyProtocolsHandler { let handler_proto = DummyConnectionHandler {
keep_alive: KeepAlive::Yes, keep_alive: KeepAlive::Yes,
}; };
@ -1970,7 +1970,7 @@ mod tests {
fn prop(concurrency_factor: DialConcurrencyFactor) { fn prop(concurrency_factor: DialConcurrencyFactor) {
block_on(async { block_on(async {
let mut swarm = new_test_swarm::<_, ()>(DummyProtocolsHandler { let mut swarm = new_test_swarm::<_, ()>(DummyConnectionHandler {
keep_alive: KeepAlive::Yes, keep_alive: KeepAlive::Yes,
}) })
.dial_concurrency_factor(concurrency_factor.0) .dial_concurrency_factor(concurrency_factor.0)
@ -2039,7 +2039,7 @@ mod tests {
let outgoing_limit = rand::thread_rng().gen_range(1, 10); let outgoing_limit = rand::thread_rng().gen_range(1, 10);
let limits = ConnectionLimits::default().with_max_pending_outgoing(Some(outgoing_limit)); 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, keep_alive: KeepAlive::Yes,
}) })
.connection_limits(limits) .connection_limits(limits)
@ -2102,12 +2102,12 @@ mod tests {
fn prop(limit: Limit) { fn prop(limit: Limit) {
let limit = limit.0; let limit = limit.0;
let mut network1 = new_test_swarm::<_, ()>(DummyProtocolsHandler { let mut network1 = new_test_swarm::<_, ()>(DummyConnectionHandler {
keep_alive: KeepAlive::Yes, keep_alive: KeepAlive::Yes,
}) })
.connection_limits(limits(limit)) .connection_limits(limits(limit))
.build(); .build();
let mut network2 = new_test_swarm::<_, ()>(DummyProtocolsHandler { let mut network2 = new_test_swarm::<_, ()>(DummyConnectionHandler {
keep_alive: KeepAlive::Yes, keep_alive: KeepAlive::Yes,
}) })
.connection_limits(limits(limit)) .connection_limits(limits(limit))
@ -2216,8 +2216,8 @@ mod tests {
// Checks whether dialing an address containing the wrong peer id raises an error // Checks whether dialing an address containing the wrong peer id raises an error
// for the expected peer id instead of the obtained peer id. // for the expected peer id instead of the obtained peer id.
let mut swarm1 = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); let mut swarm1 = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let mut swarm2 = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); let mut swarm2 = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
swarm1.listen_on("/memory/0".parse().unwrap()).unwrap(); swarm1.listen_on("/memory/0".parse().unwrap()).unwrap();
@ -2276,7 +2276,7 @@ mod tests {
// //
// The last two can happen in any order. // 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(); swarm.listen_on("/memory/0".parse().unwrap()).unwrap();
let local_address = let local_address =
@ -2334,7 +2334,7 @@ mod tests {
fn dial_self_by_id() { fn dial_self_by_id() {
// Trying to dial self by passing the same `PeerId` shouldn't even be possible in the first // Trying to dial self by passing the same `PeerId` shouldn't even be possible in the first
// place. // place.
let swarm = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); let swarm = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let peer_id = *swarm.local_peer_id(); let peer_id = *swarm.local_peer_id();
assert!(!swarm.is_connected(&peer_id)); assert!(!swarm.is_connected(&peer_id));
} }
@ -2345,7 +2345,7 @@ mod tests {
let target = PeerId::random(); 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(); let mut addresses = Vec::new();
for _ in 0..3 { for _ in 0..3 {
@ -2399,8 +2399,8 @@ mod tests {
fn aborting_pending_connection_surfaces_error() { fn aborting_pending_connection_surfaces_error() {
let _ = env_logger::try_init(); let _ = env_logger::try_init();
let mut dialer = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); let mut dialer = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let mut listener = new_test_swarm::<_, ()>(DummyProtocolsHandler::default()).build(); let mut listener = new_test_swarm::<_, ()>(DummyConnectionHandler::default()).build();
let listener_peer_id = *listener.local_peer_id(); let listener_peer_id = *listener.local_peer_id();
listener.listen_on(multiaddr![Memory(0u64)]).unwrap(); listener.listen_on(multiaddr![Memory(0u64)]).unwrap();

View File

@ -19,8 +19,8 @@
// DEALINGS IN THE SOFTWARE. // DEALINGS IN THE SOFTWARE.
use crate::{ use crate::{
DialError, IntoProtocolsHandler, NetworkBehaviour, NetworkBehaviourAction, PollParameters, ConnectionHandler, DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction,
ProtocolsHandler, PollParameters,
}; };
use libp2p_core::{ use libp2p_core::{
connection::{ConnectionId, ListenerId}, connection::{ConnectionId, ListenerId},
@ -35,7 +35,7 @@ use std::task::{Context, Poll};
/// any further state. /// any further state.
pub struct MockBehaviour<THandler, TOutEvent> pub struct MockBehaviour<THandler, TOutEvent>
where where
THandler: ProtocolsHandler, THandler: ConnectionHandler,
{ {
/// The prototype protocols handler that is cloned for every /// The prototype protocols handler that is cloned for every
/// invocation of `new_handler`. /// invocation of `new_handler`.
@ -50,7 +50,7 @@ where
impl<THandler, TOutEvent> MockBehaviour<THandler, TOutEvent> impl<THandler, TOutEvent> MockBehaviour<THandler, TOutEvent>
where where
THandler: ProtocolsHandler, THandler: ConnectionHandler,
{ {
pub fn new(handler_proto: THandler) -> Self { pub fn new(handler_proto: THandler) -> Self {
MockBehaviour { MockBehaviour {
@ -63,14 +63,14 @@ where
impl<THandler, TOutEvent> NetworkBehaviour for MockBehaviour<THandler, TOutEvent> impl<THandler, TOutEvent> NetworkBehaviour for MockBehaviour<THandler, TOutEvent>
where where
THandler: ProtocolsHandler + Clone, THandler: ConnectionHandler + Clone,
THandler::OutEvent: Clone, THandler::OutEvent: Clone,
TOutEvent: Send + 'static, TOutEvent: Send + 'static,
{ {
type ProtocolsHandler = THandler; type ConnectionHandler = THandler;
type OutEvent = TOutEvent; type OutEvent = TOutEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
self.handler_proto.clone() self.handler_proto.clone()
} }
@ -84,7 +84,7 @@ where
&mut self, &mut self,
_: &mut Context, _: &mut Context,
_: &mut impl PollParameters, _: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
self.next_action.take().map_or(Poll::Pending, Poll::Ready) self.next_action.take().map_or(Poll::Pending, Poll::Ready)
} }
} }
@ -104,7 +104,7 @@ where
pub inject_event: Vec<( pub inject_event: Vec<(
PeerId, PeerId,
ConnectionId, ConnectionId,
<<TInner::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent, <<TInner::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
)>, )>,
pub inject_dial_failure: Vec<Option<PeerId>>, pub inject_dial_failure: Vec<Option<PeerId>>,
pub inject_new_listener: Vec<ListenerId>, pub inject_new_listener: Vec<ListenerId>,
@ -211,13 +211,13 @@ where
impl<TInner> NetworkBehaviour for CallTraceBehaviour<TInner> impl<TInner> NetworkBehaviour for CallTraceBehaviour<TInner>
where where
TInner: NetworkBehaviour, TInner: NetworkBehaviour,
<<TInner::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent: <<TInner::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent:
Clone, Clone,
{ {
type ProtocolsHandler = TInner::ProtocolsHandler; type ConnectionHandler = TInner::ConnectionHandler;
type OutEvent = TInner::OutEvent; type OutEvent = TInner::OutEvent;
fn new_handler(&mut self) -> Self::ProtocolsHandler { fn new_handler(&mut self) -> Self::ConnectionHandler {
self.inner.new_handler() self.inner.new_handler()
} }
@ -276,7 +276,7 @@ where
p: &PeerId, p: &PeerId,
c: &ConnectionId, c: &ConnectionId,
e: &ConnectedPoint, e: &ConnectedPoint,
handler: <Self::ProtocolsHandler as IntoProtocolsHandler>::Handler, handler: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize, remaining_established: usize,
) { ) {
let mut other_closed_connections = self let mut other_closed_connections = self
@ -323,7 +323,7 @@ where
&mut self, &mut self,
p: PeerId, p: PeerId,
c: ConnectionId, c: ConnectionId,
e: <<Self::ProtocolsHandler as IntoProtocolsHandler>::Handler as ProtocolsHandler>::OutEvent, e: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
) { ) {
assert!( assert!(
self.inject_connection_established self.inject_connection_established
@ -346,7 +346,7 @@ where
fn inject_dial_failure( fn inject_dial_failure(
&mut self, &mut self,
p: Option<PeerId>, p: Option<PeerId>,
handler: Self::ProtocolsHandler, handler: Self::ConnectionHandler,
error: &DialError, error: &DialError,
) { ) {
self.inject_dial_failure.push(p); self.inject_dial_failure.push(p);
@ -392,7 +392,7 @@ where
&mut self, &mut self,
cx: &mut Context, cx: &mut Context,
args: &mut impl PollParameters, args: &mut impl PollParameters,
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ProtocolsHandler>> { ) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
self.poll += 1; self.poll += 1;
self.inner.poll(cx, args) self.inner.poll(cx, args)
} }