swarm/behaviour: Replace inject_* with on_event (#3011)

This commit is contained in:
João Oliveira
2022-11-17 09:28:40 +00:00
committed by GitHub
parent a714864885
commit 3df3c88f3d
38 changed files with 2482 additions and 1652 deletions

View File

@ -153,39 +153,90 @@ pub trait NetworkBehaviour: 'static {
vec![]
}
/// Informs the behaviour about an event from the [`Swarm`](crate::Swarm).
fn on_swarm_event(&mut self, _event: FromSwarm<Self::ConnectionHandler>) {}
/// Informs the behaviour about an event generated by the [`ConnectionHandler`] dedicated to the
/// peer identified by `peer_id`. for the behaviour.
///
/// The [`PeerId`] is guaranteed to be in a connected state. In other words,
/// [`FromSwarm::ConnectionEstablished`] has previously been received with this [`PeerId`].
fn on_connection_handler_event(
&mut self,
_peer_id: PeerId,
_connection_id: ConnectionId,
_event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as
ConnectionHandler>::OutEvent,
) {
}
/// Informs the behaviour about a newly established connection to a peer.
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::ConnectionEstablished` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_connection_established(
&mut self,
_peer_id: &PeerId,
_connection_id: &ConnectionId,
_endpoint: &ConnectedPoint,
_failed_addresses: Option<&Vec<Multiaddr>>,
_other_established: usize,
peer_id: &PeerId,
connection_id: &ConnectionId,
endpoint: &ConnectedPoint,
failed_addresses: Option<&Vec<Multiaddr>>,
other_established: usize,
) {
self.on_swarm_event(FromSwarm::ConnectionEstablished(ConnectionEstablished {
peer_id: *peer_id,
connection_id: *connection_id,
endpoint,
failed_addresses: failed_addresses
.map(|v| v.as_slice())
.unwrap_or_else(|| &[]),
other_established,
}));
}
/// Informs the behaviour about a closed connection to a peer.
///
/// A call to this method is always paired with an earlier call to
/// [`NetworkBehaviour::inject_connection_established`] with the same peer ID, connection ID and endpoint.
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::ConnectionClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_connection_closed(
&mut self,
_: &PeerId,
_: &ConnectionId,
_: &ConnectedPoint,
_: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
_remaining_established: usize,
peer_id: &PeerId,
connection_id: &ConnectionId,
endpoint: &ConnectedPoint,
handler: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize,
) {
self.on_swarm_event(FromSwarm::ConnectionClosed(ConnectionClosed {
peer_id: *peer_id,
connection_id: *connection_id,
endpoint,
handler,
remaining_established,
}));
}
/// Informs the behaviour that the [`ConnectedPoint`] of an existing connection has changed.
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::AddressChange` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_address_change(
&mut self,
_: &PeerId,
_: &ConnectionId,
_old: &ConnectedPoint,
_new: &ConnectedPoint,
peer_id: &PeerId,
connection_id: &ConnectionId,
old: &ConnectedPoint,
new: &ConnectedPoint,
) {
self.on_swarm_event(FromSwarm::AddressChange(AddressChange {
peer_id: *peer_id,
connection_id: *connection_id,
old,
new,
}));
}
/// Informs the behaviour about an event generated by the handler dedicated to the peer identified by `peer_id`.
@ -193,20 +244,35 @@ pub trait NetworkBehaviour: 'static {
///
/// The `peer_id` is guaranteed to be in a connected state. In other words,
/// [`NetworkBehaviour::inject_connection_established`] has previously been called with this `PeerId`.
#[deprecated(
since = "0.40.2",
note = "Implement `NetworkBehaviour::on_connection_handler_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_event(
&mut self,
peer_id: PeerId,
connection: ConnectionId,
event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
);
) {
self.on_connection_handler_event(peer_id, connection, event);
}
/// Indicates to the behaviour that the dial to a known or unknown node failed.
#[deprecated(
since = "0.40.2",
note = "Handle `InEvent::DialFailure` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_dial_failure(
&mut self,
_peer_id: Option<PeerId>,
_handler: Self::ConnectionHandler,
_error: &DialError,
peer_id: Option<PeerId>,
handler: Self::ConnectionHandler,
error: &DialError,
) {
self.on_swarm_event(FromSwarm::DialFailure(DialFailure {
peer_id,
handler,
error,
}));
}
/// Indicates to the behaviour that an error happened on an incoming connection during its
@ -214,36 +280,98 @@ pub trait NetworkBehaviour: 'static {
///
/// This can include, for example, an error during the handshake of the encryption layer, or the
/// connection unexpectedly closed.
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::ListenFailure` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_listen_failure(
&mut self,
_local_addr: &Multiaddr,
_send_back_addr: &Multiaddr,
_handler: Self::ConnectionHandler,
local_addr: &Multiaddr,
send_back_addr: &Multiaddr,
handler: Self::ConnectionHandler,
) {
self.on_swarm_event(FromSwarm::ListenFailure(ListenFailure {
local_addr,
send_back_addr,
handler,
}));
}
/// Indicates to the behaviour that a new listener was created.
fn inject_new_listener(&mut self, _id: ListenerId) {}
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::NewListener` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_new_listener(&mut self, id: ListenerId) {
self.on_swarm_event(FromSwarm::NewListener(NewListener { listener_id: id }));
}
/// Indicates to the behaviour that we have started listening on a new multiaddr.
fn inject_new_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) {}
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::NewListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) {
self.on_swarm_event(FromSwarm::NewListenAddr(NewListenAddr {
listener_id: id,
addr,
}));
}
/// Indicates to the behaviour that a multiaddr we were listening on has expired,
/// which means that we are no longer listening in it.
fn inject_expired_listen_addr(&mut self, _id: ListenerId, _addr: &Multiaddr) {}
/// which means that we are no longer listening on it.
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::ExpiredListenAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) {
self.on_swarm_event(FromSwarm::ExpiredListenAddr(ExpiredListenAddr {
listener_id: id,
addr,
}));
}
/// A listener experienced an error.
fn inject_listener_error(&mut self, _id: ListenerId, _err: &(dyn std::error::Error + 'static)) {
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::ListenerError` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) {
self.on_swarm_event(FromSwarm::ListenerError(ListenerError {
listener_id: id,
err,
}));
}
/// A listener closed.
fn inject_listener_closed(&mut self, _id: ListenerId, _reason: Result<(), &std::io::Error>) {}
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::ListenerClosed` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) {
self.on_swarm_event(FromSwarm::ListenerClosed(ListenerClosed {
listener_id: id,
reason,
}));
}
/// Indicates to the behaviour that we have discovered a new external address for us.
fn inject_new_external_addr(&mut self, _addr: &Multiaddr) {}
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::NewExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_new_external_addr(&mut self, addr: &Multiaddr) {
self.on_swarm_event(FromSwarm::NewExternalAddr(NewExternalAddr { addr }));
}
/// Indicates to the behaviour that an external address was removed.
fn inject_expired_external_addr(&mut self, _addr: &Multiaddr) {}
#[deprecated(
since = "0.40.2",
note = "Handle `FromSwarm::ExpiredExternalAddr` in `NetworkBehaviour::on_swarm_event` instead. The default implementation of this `inject_*` method delegates to it."
)]
fn inject_expired_external_addr(&mut self, addr: &Multiaddr) {
self.on_swarm_event(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }));
}
/// Polls for things that swarm should do.
///
@ -722,3 +850,364 @@ impl Default for CloseConnection {
CloseConnection::All
}
}
/// Enumeration with the list of the possible events
/// to pass to [`on_swarm_event`](NetworkBehaviour::on_swarm_event).
pub enum FromSwarm<'a, Handler: IntoConnectionHandler> {
/// Informs the behaviour about a newly established connection to a peer.
ConnectionEstablished(ConnectionEstablished<'a>),
/// Informs the behaviour about a closed connection to a peer.
///
/// This event is always paired with an earlier
/// [`FromSwarm::ConnectionEstablished`] with the same peer ID, connection ID
/// and endpoint.
ConnectionClosed(ConnectionClosed<'a, Handler>),
/// Informs the behaviour that the [`ConnectedPoint`] of an existing
/// connection has changed.
AddressChange(AddressChange<'a>),
/// Informs the behaviour that the dial to a known
/// or unknown node failed.
DialFailure(DialFailure<'a, Handler>),
/// Informs the behaviour that an error
/// happened on an incoming connection during its initial handshake.
///
/// This can include, for example, an error during the handshake of the encryption layer, or the
/// connection unexpectedly closed.
ListenFailure(ListenFailure<'a, Handler>),
/// Informs the behaviour that a new listener was created.
NewListener(NewListener),
/// Informs the behaviour that we have started listening on a new multiaddr.
NewListenAddr(NewListenAddr<'a>),
/// Informs the behaviour that a multiaddr
/// we were listening on has expired,
/// which means that we are no longer listening on it.
ExpiredListenAddr(ExpiredListenAddr<'a>),
/// Informs the behaviour that a listener experienced an error.
ListenerError(ListenerError<'a>),
/// Informs the behaviour that a listener closed.
ListenerClosed(ListenerClosed<'a>),
/// Informs the behaviour that we have discovered a new external address for us.
NewExternalAddr(NewExternalAddr<'a>),
/// Informs the behaviour that an external address was removed.
ExpiredExternalAddr(ExpiredExternalAddr<'a>),
}
/// [`FromSwarm`] variant that informs the behaviour about a newly established connection to a peer.
#[derive(Clone, Copy)]
pub struct ConnectionEstablished<'a> {
pub peer_id: PeerId,
pub connection_id: ConnectionId,
pub endpoint: &'a ConnectedPoint,
pub failed_addresses: &'a [Multiaddr],
pub other_established: usize,
}
/// [`FromSwarm`] variant that informs the behaviour about a closed connection to a peer.
///
/// This event is always paired with an earlier
/// [`FromSwarm::ConnectionEstablished`] with the same peer ID, connection ID
/// and endpoint.
pub struct ConnectionClosed<'a, Handler: IntoConnectionHandler> {
pub peer_id: PeerId,
pub connection_id: ConnectionId,
pub endpoint: &'a ConnectedPoint,
pub handler: <Handler as IntoConnectionHandler>::Handler,
pub remaining_established: usize,
}
/// [`FromSwarm`] variant that informs the behaviour that the [`ConnectedPoint`] of an existing
/// connection has changed.
#[derive(Clone, Copy)]
pub struct AddressChange<'a> {
pub peer_id: PeerId,
pub connection_id: ConnectionId,
pub old: &'a ConnectedPoint,
pub new: &'a ConnectedPoint,
}
/// [`FromSwarm`] variant that informs the behaviour that the dial to a known
/// or unknown node failed.
#[derive(Clone, Copy)]
pub struct DialFailure<'a, Handler> {
pub peer_id: Option<PeerId>,
pub handler: Handler,
pub error: &'a DialError,
}
/// [`FromSwarm`] variant that informs the behaviour that an error
/// happened on an incoming connection during its initial handshake.
///
/// This can include, for example, an error during the handshake of the encryption layer, or the
/// connection unexpectedly closed.
#[derive(Clone, Copy)]
pub struct ListenFailure<'a, Handler> {
pub local_addr: &'a Multiaddr,
pub send_back_addr: &'a Multiaddr,
pub handler: Handler,
}
/// [`FromSwarm`] variant that informs the behaviour that a new listener was created.
#[derive(Clone, Copy)]
pub struct NewListener {
pub listener_id: ListenerId,
}
/// [`FromSwarm`] variant that informs the behaviour
/// that we have started listening on a new multiaddr.
#[derive(Clone, Copy)]
pub struct NewListenAddr<'a> {
pub listener_id: ListenerId,
pub addr: &'a Multiaddr,
}
/// [`FromSwarm`] variant that informs the behaviour that a multiaddr
/// we were listening on has expired,
/// which means that we are no longer listening on it.
#[derive(Clone, Copy)]
pub struct ExpiredListenAddr<'a> {
pub listener_id: ListenerId,
pub addr: &'a Multiaddr,
}
/// [`FromSwarm`] variant that informs the behaviour that a listener experienced an error.
#[derive(Clone, Copy)]
pub struct ListenerError<'a> {
pub listener_id: ListenerId,
pub err: &'a (dyn std::error::Error + 'static),
}
/// [`FromSwarm`] variant that informs the behaviour that a listener closed.
#[derive(Clone, Copy)]
pub struct ListenerClosed<'a> {
pub listener_id: ListenerId,
pub reason: Result<(), &'a std::io::Error>,
}
/// [`FromSwarm`] variant that informs the behaviour
/// that we have discovered a new external address for us.
#[derive(Clone, Copy)]
pub struct NewExternalAddr<'a> {
pub addr: &'a Multiaddr,
}
/// [`FromSwarm`] variant that informs the behaviour that an external address was removed.
#[derive(Clone, Copy)]
pub struct ExpiredExternalAddr<'a> {
pub addr: &'a Multiaddr,
}
impl<'a, Handler: IntoConnectionHandler> FromSwarm<'a, Handler> {
fn map_handler<NewHandler>(
self,
map_into_handler: impl FnOnce(Handler) -> NewHandler,
map_handler: impl FnOnce(
<Handler as IntoConnectionHandler>::Handler,
) -> <NewHandler as IntoConnectionHandler>::Handler,
) -> FromSwarm<'a, NewHandler>
where
NewHandler: IntoConnectionHandler,
{
self.maybe_map_handler(|h| Some(map_into_handler(h)), |h| Some(map_handler(h)))
.expect("To return Some as all closures return Some.")
}
fn maybe_map_handler<NewHandler>(
self,
map_into_handler: impl FnOnce(Handler) -> Option<NewHandler>,
map_handler: impl FnOnce(
<Handler as IntoConnectionHandler>::Handler,
) -> Option<<NewHandler as IntoConnectionHandler>::Handler>,
) -> Option<FromSwarm<'a, NewHandler>>
where
NewHandler: IntoConnectionHandler,
{
match self {
FromSwarm::ConnectionClosed(ConnectionClosed {
peer_id,
connection_id,
endpoint,
handler,
remaining_established,
}) => Some(FromSwarm::ConnectionClosed(ConnectionClosed {
peer_id,
connection_id,
endpoint,
handler: map_handler(handler)?,
remaining_established,
})),
FromSwarm::ConnectionEstablished(ConnectionEstablished {
peer_id,
connection_id,
endpoint,
failed_addresses,
other_established,
}) => Some(FromSwarm::ConnectionEstablished(ConnectionEstablished {
peer_id,
connection_id,
endpoint,
failed_addresses,
other_established,
})),
FromSwarm::AddressChange(AddressChange {
peer_id,
connection_id,
old,
new,
}) => Some(FromSwarm::AddressChange(AddressChange {
peer_id,
connection_id,
old,
new,
})),
FromSwarm::DialFailure(DialFailure {
peer_id,
handler,
error,
}) => Some(FromSwarm::DialFailure(DialFailure {
peer_id,
handler: map_into_handler(handler)?,
error,
})),
FromSwarm::ListenFailure(ListenFailure {
local_addr,
send_back_addr,
handler,
}) => Some(FromSwarm::ListenFailure(ListenFailure {
local_addr,
send_back_addr,
handler: map_into_handler(handler)?,
})),
FromSwarm::NewListener(NewListener { listener_id }) => {
Some(FromSwarm::NewListener(NewListener { listener_id }))
}
FromSwarm::NewListenAddr(NewListenAddr { listener_id, addr }) => {
Some(FromSwarm::NewListenAddr(NewListenAddr {
listener_id,
addr,
}))
}
FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id, addr }) => {
Some(FromSwarm::ExpiredListenAddr(ExpiredListenAddr {
listener_id,
addr,
}))
}
FromSwarm::ListenerError(ListenerError { listener_id, err }) => {
Some(FromSwarm::ListenerError(ListenerError { listener_id, err }))
}
FromSwarm::ListenerClosed(ListenerClosed {
listener_id,
reason,
}) => Some(FromSwarm::ListenerClosed(ListenerClosed {
listener_id,
reason,
})),
FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => {
Some(FromSwarm::NewExternalAddr(NewExternalAddr { addr }))
}
FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }) => {
Some(FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }))
}
}
}
}
/// Helper function to call [`NetworkBehaviour`]'s `inject_*` methods given a `FromSwarm.
/// TODO: Remove this function when we remove the remaining `inject_*` calls
/// from [`Either`] and [`Toggle`].
pub(crate) fn inject_from_swarm<T: NetworkBehaviour>(
behaviour: &mut T,
event: FromSwarm<T::ConnectionHandler>,
) {
match event {
FromSwarm::ConnectionEstablished(ConnectionEstablished {
peer_id,
connection_id,
endpoint,
failed_addresses,
other_established,
}) => {
#[allow(deprecated)]
behaviour.inject_connection_established(
&peer_id,
&connection_id,
endpoint,
Some(&failed_addresses.into()),
other_established,
);
}
FromSwarm::ConnectionClosed(ConnectionClosed {
peer_id,
connection_id,
endpoint,
handler,
remaining_established,
}) => {
#[allow(deprecated)]
behaviour.inject_connection_closed(
&peer_id,
&connection_id,
endpoint,
handler,
remaining_established,
);
}
FromSwarm::AddressChange(AddressChange {
peer_id,
connection_id,
old,
new,
}) => {
#[allow(deprecated)]
behaviour.inject_address_change(&peer_id, &connection_id, old, new);
}
FromSwarm::DialFailure(DialFailure {
peer_id,
handler,
error,
}) => {
#[allow(deprecated)]
behaviour.inject_dial_failure(peer_id, handler, error);
}
FromSwarm::ListenFailure(ListenFailure {
local_addr,
send_back_addr,
handler,
}) => {
#[allow(deprecated)]
behaviour.inject_listen_failure(local_addr, send_back_addr, handler);
}
FromSwarm::NewListener(NewListener { listener_id }) => {
#[allow(deprecated)]
behaviour.inject_new_listener(listener_id);
}
FromSwarm::NewListenAddr(NewListenAddr { listener_id, addr }) => {
#[allow(deprecated)]
behaviour.inject_new_listen_addr(listener_id, addr);
}
FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id, addr }) => {
#[allow(deprecated)]
behaviour.inject_expired_listen_addr(listener_id, addr);
}
FromSwarm::ListenerError(ListenerError { listener_id, err }) => {
#[allow(deprecated)]
behaviour.inject_listener_error(listener_id, err);
}
FromSwarm::ListenerClosed(ListenerClosed {
listener_id,
reason,
}) => {
#[allow(deprecated)]
behaviour.inject_listener_closed(listener_id, reason);
}
FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => {
#[allow(deprecated)]
behaviour.inject_new_external_addr(addr);
}
FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }) =>
{
#[allow(deprecated)]
behaviour.inject_expired_external_addr(addr)
}
}
}

View File

@ -18,12 +18,12 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use crate::handler::{either::IntoEitherHandler, ConnectionHandler, IntoConnectionHandler};
use crate::{DialError, NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use either::Either;
use libp2p_core::{
connection::ConnectionId, transport::ListenerId, ConnectedPoint, Multiaddr, PeerId,
use crate::behaviour::{
self, inject_from_swarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters,
};
use crate::handler::either::IntoEitherHandler;
use either::Either;
use libp2p_core::{Multiaddr, PeerId};
use std::{task::Context, task::Poll};
/// Implementation of [`NetworkBehaviour`] that can be either of two implementations.
@ -49,173 +49,50 @@ where
}
}
fn inject_connection_established(
&mut self,
peer_id: &PeerId,
connection: &ConnectionId,
endpoint: &ConnectedPoint,
errors: Option<&Vec<Multiaddr>>,
other_established: usize,
) {
fn on_swarm_event(&mut self, event: behaviour::FromSwarm<Self::ConnectionHandler>) {
match self {
Either::Left(a) => a.inject_connection_established(
peer_id,
connection,
endpoint,
errors,
other_established,
),
Either::Right(b) => b.inject_connection_established(
peer_id,
connection,
endpoint,
errors,
other_established,
),
}
}
fn inject_connection_closed(
&mut self,
peer_id: &PeerId,
connection: &ConnectionId,
endpoint: &ConnectedPoint,
handler: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize,
) {
match (self, handler) {
(Either::Left(behaviour), Either::Left(handler)) => behaviour.inject_connection_closed(
peer_id,
connection,
endpoint,
handler,
remaining_established,
),
(Either::Right(behaviour), Either::Right(handler)) => behaviour
.inject_connection_closed(
peer_id,
connection,
endpoint,
handler,
remaining_established,
Either::Left(b) => inject_from_swarm(
b,
event.map_handler(
|h| h.unwrap_left(),
|h| match h {
Either::Left(h) => h,
Either::Right(_) => unreachable!(),
},
),
_ => unreachable!(),
),
Either::Right(b) => inject_from_swarm(
b,
event.map_handler(
|h| h.unwrap_right(),
|h| match h {
Either::Right(h) => h,
Either::Left(_) => unreachable!(),
},
),
),
}
}
fn inject_address_change(
&mut self,
peer_id: &PeerId,
connection: &ConnectionId,
old: &ConnectedPoint,
new: &ConnectedPoint,
) {
match self {
Either::Left(a) => a.inject_address_change(peer_id, connection, old, new),
Either::Right(b) => b.inject_address_change(peer_id, connection, old, new),
}
}
fn inject_event(
fn on_connection_handler_event(
&mut self,
peer_id: PeerId,
connection: ConnectionId,
event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
connection_id: libp2p_core::connection::ConnectionId,
event: crate::THandlerOutEvent<Self>,
) {
match (self, event) {
(Either::Left(behaviour), Either::Left(event)) => {
behaviour.inject_event(peer_id, connection, event)
(Either::Left(left), Either::Left(event)) => {
#[allow(deprecated)]
left.inject_event(peer_id, connection_id, event);
}
(Either::Right(behaviour), Either::Right(event)) => {
behaviour.inject_event(peer_id, connection, event)
(Either::Right(right), Either::Right(event)) => {
#[allow(deprecated)]
right.inject_event(peer_id, connection_id, event);
}
_ => unreachable!(),
}
}
fn inject_dial_failure(
&mut self,
peer_id: Option<PeerId>,
handler: Self::ConnectionHandler,
error: &DialError,
) {
match (self, handler) {
(Either::Left(behaviour), IntoEitherHandler::Left(handler)) => {
behaviour.inject_dial_failure(peer_id, handler, error)
}
(Either::Right(behaviour), IntoEitherHandler::Right(handler)) => {
behaviour.inject_dial_failure(peer_id, handler, error)
}
_ => unreachable!(),
}
}
fn inject_listen_failure(
&mut self,
local_addr: &Multiaddr,
send_back_addr: &Multiaddr,
handler: Self::ConnectionHandler,
) {
match (self, handler) {
(Either::Left(behaviour), IntoEitherHandler::Left(handler)) => {
behaviour.inject_listen_failure(local_addr, send_back_addr, handler)
}
(Either::Right(behaviour), IntoEitherHandler::Right(handler)) => {
behaviour.inject_listen_failure(local_addr, send_back_addr, handler)
}
_ => unreachable!(),
}
}
fn inject_new_listener(&mut self, id: ListenerId) {
match self {
Either::Left(a) => a.inject_new_listener(id),
Either::Right(b) => b.inject_new_listener(id),
}
}
fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) {
match self {
Either::Left(a) => a.inject_new_listen_addr(id, addr),
Either::Right(b) => b.inject_new_listen_addr(id, addr),
}
}
fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) {
match self {
Either::Left(a) => a.inject_expired_listen_addr(id, addr),
Either::Right(b) => b.inject_expired_listen_addr(id, addr),
}
}
fn inject_new_external_addr(&mut self, addr: &Multiaddr) {
match self {
Either::Left(a) => a.inject_new_external_addr(addr),
Either::Right(b) => b.inject_new_external_addr(addr),
}
}
fn inject_expired_external_addr(&mut self, addr: &Multiaddr) {
match self {
Either::Left(a) => a.inject_expired_external_addr(addr),
Either::Right(b) => b.inject_expired_external_addr(addr),
}
}
fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) {
match self {
Either::Left(a) => a.inject_listener_error(id, err),
Either::Right(b) => b.inject_listener_error(id, err),
}
}
fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) {
match self {
Either::Left(a) => a.inject_listener_closed(id, reason),
Either::Right(b) => b.inject_listener_closed(id, reason),
}
}
fn poll(
&mut self,
cx: &mut Context<'_>,

View File

@ -18,17 +18,16 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use crate::behaviour::{inject_from_swarm, FromSwarm};
use crate::handler::{
ConnectionHandler, ConnectionHandlerEvent, ConnectionHandlerUpgrErr, IntoConnectionHandler,
KeepAlive, SubstreamProtocol,
};
use crate::upgrade::{InboundUpgradeSend, OutboundUpgradeSend, SendWrapper};
use crate::{DialError, NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use crate::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use either::Either;
use libp2p_core::{
connection::ConnectionId,
either::{EitherError, EitherOutput},
transport::ListenerId,
upgrade::{DeniedUpgrade, EitherUpgrade},
ConnectedPoint, Multiaddr, PeerId,
};
@ -84,134 +83,23 @@ where
.unwrap_or_else(Vec::new)
}
fn inject_connection_established(
&mut self,
peer_id: &PeerId,
connection: &ConnectionId,
endpoint: &ConnectedPoint,
errors: Option<&Vec<Multiaddr>>,
other_established: usize,
) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_connection_established(
peer_id,
connection,
endpoint,
errors,
other_established,
)
}
}
fn inject_connection_closed(
&mut self,
peer_id: &PeerId,
connection: &ConnectionId,
endpoint: &ConnectedPoint,
handler: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize,
) {
if let Some(inner) = self.inner.as_mut() {
if let Some(handler) = handler.inner {
inner.inject_connection_closed(
peer_id,
connection,
endpoint,
handler,
remaining_established,
)
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
if let Some(behaviour) = &mut self.inner {
if let Some(event) = event.maybe_map_handler(|h| h.inner, |h| h.inner) {
inject_from_swarm(behaviour, event);
}
}
}
fn inject_address_change(
&mut self,
peer_id: &PeerId,
connection: &ConnectionId,
old: &ConnectedPoint,
new: &ConnectedPoint,
) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_address_change(peer_id, connection, old, new)
}
}
fn inject_event(
fn on_connection_handler_event(
&mut self,
peer_id: PeerId,
connection: ConnectionId,
event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
connection_id: libp2p_core::connection::ConnectionId,
event: crate::THandlerOutEvent<Self>,
) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_event(peer_id, connection, event);
}
}
fn inject_dial_failure(
&mut self,
peer_id: Option<PeerId>,
handler: Self::ConnectionHandler,
error: &DialError,
) {
if let Some(inner) = self.inner.as_mut() {
if let Some(handler) = handler.inner {
inner.inject_dial_failure(peer_id, handler, error)
}
}
}
fn inject_listen_failure(
&mut self,
local_addr: &Multiaddr,
send_back_addr: &Multiaddr,
handler: Self::ConnectionHandler,
) {
if let Some(inner) = self.inner.as_mut() {
if let Some(handler) = handler.inner {
inner.inject_listen_failure(local_addr, send_back_addr, handler)
}
}
}
fn inject_new_listener(&mut self, id: ListenerId) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_new_listener(id)
}
}
fn inject_new_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_new_listen_addr(id, addr)
}
}
fn inject_expired_listen_addr(&mut self, id: ListenerId, addr: &Multiaddr) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_expired_listen_addr(id, addr)
}
}
fn inject_new_external_addr(&mut self, addr: &Multiaddr) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_new_external_addr(addr)
}
}
fn inject_expired_external_addr(&mut self, addr: &Multiaddr) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_expired_external_addr(addr)
}
}
fn inject_listener_error(&mut self, id: ListenerId, err: &(dyn std::error::Error + 'static)) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_listener_error(id, err)
}
}
fn inject_listener_closed(&mut self, id: ListenerId, reason: Result<(), &std::io::Error>) {
if let Some(inner) = self.inner.as_mut() {
inner.inject_listener_closed(id, reason)
if let Some(behaviour) = &mut self.inner {
#[allow(deprecated)]
behaviour.inject_event(peer_id, connection_id, event)
}
}

View File

@ -1,4 +1,4 @@
use crate::behaviour::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use crate::behaviour::{FromSwarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use crate::handler::{InboundUpgradeSend, OutboundUpgradeSend};
use crate::{ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol};
use libp2p_core::connection::ConnectionId;
@ -19,7 +19,7 @@ impl NetworkBehaviour for Behaviour {
ConnectionHandler
}
fn inject_event(&mut self, _: PeerId, _: ConnectionId, event: Void) {
fn on_connection_handler_event(&mut self, _: PeerId, _: ConnectionId, event: Void) {
void::unreachable(event)
}
@ -30,6 +30,23 @@ impl NetworkBehaviour for Behaviour {
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
Poll::Pending
}
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
match event {
FromSwarm::ConnectionEstablished(_)
| FromSwarm::ConnectionClosed(_)
| FromSwarm::AddressChange(_)
| FromSwarm::DialFailure(_)
| FromSwarm::ListenFailure(_)
| FromSwarm::NewListener(_)
| FromSwarm::NewListenAddr(_)
| FromSwarm::ExpiredListenAddr(_)
| FromSwarm::ListenerError(_)
| FromSwarm::ListenerClosed(_)
| FromSwarm::NewExternalAddr(_)
| FromSwarm::ExpiredExternalAddr(_) => {}
}
}
}
/// An implementation of [`ConnectionHandler`] that neither handles any protocols nor does it keep the connection alive.

View File

@ -29,6 +29,8 @@ use libp2p_core::upgrade::{EitherUpgrade, UpgradeError};
use libp2p_core::{ConnectedPoint, Multiaddr, PeerId};
use std::task::{Context, Poll};
/// Auxiliary type to allow implementing [`IntoConnectionHandler`]. As [`IntoConnectionHandler`] is
/// already implemented for T, we cannot implement it for Either<A, B>.
pub enum IntoEitherHandler<L, R> {
Left(L),
Right(R),
@ -64,6 +66,29 @@ where
}
}
// Taken from https://github.com/bluss/either.
impl<L, R> IntoEitherHandler<L, R> {
/// Returns the left value.
pub fn unwrap_left(self) -> L {
match self {
IntoEitherHandler::Left(l) => l,
IntoEitherHandler::Right(_) => {
panic!("called `IntoEitherHandler::unwrap_left()` on a `Right` value.",)
}
}
}
/// Returns the right value.
pub fn unwrap_right(self) -> R {
match self {
IntoEitherHandler::Right(r) => r,
IntoEitherHandler::Left(_) => {
panic!("called `IntoEitherHandler::unwrap_right()` on a `Left` value.",)
}
}
}
}
/// Implementation of a [`ConnectionHandler`] that represents either of two [`ConnectionHandler`]
/// implementations.
impl<L, R> ConnectionHandler for Either<L, R>

View File

@ -1,4 +1,4 @@
use crate::behaviour::{NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use crate::behaviour::{FromSwarm, NetworkBehaviour, NetworkBehaviourAction, PollParameters};
use crate::handler::{
ConnectionHandlerEvent, ConnectionHandlerUpgrErr, KeepAlive, SubstreamProtocol,
};
@ -29,7 +29,7 @@ impl NetworkBehaviour for Behaviour {
ConnectionHandler
}
fn inject_event(&mut self, _: PeerId, _: ConnectionId, event: Void) {
fn on_connection_handler_event(&mut self, _: PeerId, _: ConnectionId, event: Void) {
void::unreachable(event)
}
@ -40,6 +40,23 @@ impl NetworkBehaviour for Behaviour {
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
Poll::Pending
}
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
match event {
FromSwarm::ConnectionEstablished(_)
| FromSwarm::ConnectionClosed(_)
| FromSwarm::AddressChange(_)
| FromSwarm::DialFailure(_)
| FromSwarm::ListenFailure(_)
| FromSwarm::NewListener(_)
| FromSwarm::NewListenAddr(_)
| FromSwarm::ExpiredListenAddr(_)
| FromSwarm::ListenerError(_)
| FromSwarm::ListenerClosed(_)
| FromSwarm::NewExternalAddr(_)
| FromSwarm::ExpiredExternalAddr(_) => {}
}
}
}
/// Implementation of [`ConnectionHandler`] that doesn't handle anything but keeps the connection alive.

View File

@ -71,6 +71,19 @@ pub mod keep_alive;
/// Bundles all symbols required for the [`libp2p_swarm_derive::NetworkBehaviour`] macro.
#[doc(hidden)]
pub mod derive_prelude {
pub use crate::behaviour::AddressChange;
pub use crate::behaviour::ConnectionClosed;
pub use crate::behaviour::ConnectionEstablished;
pub use crate::behaviour::DialFailure;
pub use crate::behaviour::ExpiredExternalAddr;
pub use crate::behaviour::ExpiredListenAddr;
pub use crate::behaviour::FromSwarm;
pub use crate::behaviour::ListenFailure;
pub use crate::behaviour::ListenerClosed;
pub use crate::behaviour::ListenerError;
pub use crate::behaviour::NewExternalAddr;
pub use crate::behaviour::NewListenAddr;
pub use crate::behaviour::NewListener;
pub use crate::ConnectionHandler;
pub use crate::DialError;
pub use crate::IntoConnectionHandler;
@ -432,6 +445,7 @@ where
/// Depending on the underlying transport, one listener may have multiple listening addresses.
pub fn listen_on(&mut self, addr: Multiaddr) -> Result<ListenerId, TransportError<io::Error>> {
let id = self.transport.listen_on(addr)?;
#[allow(deprecated)]
self.behaviour.inject_new_listener(id);
Ok(id)
}
@ -500,6 +514,7 @@ where
PeerCondition::Always => true,
};
if !condition_matched {
#[allow(deprecated)]
self.behaviour.inject_dial_failure(
Some(peer_id),
handler,
@ -512,6 +527,7 @@ where
// Check if peer is banned.
if self.banned_peers.contains(&peer_id) {
let error = DialError::Banned;
#[allow(deprecated)]
self.behaviour
.inject_dial_failure(Some(peer_id), handler, &error);
return Err(error);
@ -549,6 +565,7 @@ where
if addresses.is_empty() {
let error = DialError::NoAddresses;
#[allow(deprecated)]
self.behaviour
.inject_dial_failure(Some(peer_id), handler, &error);
return Err(error);
@ -632,6 +649,7 @@ where
Ok(_connection_id) => Ok(()),
Err((connection_limit, handler)) => {
let error = DialError::ConnectionLimit(connection_limit);
#[allow(deprecated)]
self.behaviour.inject_dial_failure(peer_id, handler, &error);
Err(error)
}
@ -673,12 +691,14 @@ where
let result = self.external_addrs.add(a.clone(), s);
let expired = match &result {
AddAddressResult::Inserted { expired } => {
#[allow(deprecated)]
self.behaviour.inject_new_external_addr(&a);
expired
}
AddAddressResult::Updated { expired } => expired,
};
for a in expired {
#[allow(deprecated)]
self.behaviour.inject_expired_external_addr(&a.addr);
}
result
@ -692,6 +712,7 @@ where
/// otherwise.
pub fn remove_external_address(&mut self, addr: &Multiaddr) -> bool {
if self.external_addrs.remove(addr) {
#[allow(deprecated)]
self.behaviour.inject_expired_external_addr(addr);
true
} else {
@ -798,6 +819,7 @@ where
let failed_addresses = concurrent_dial_errors
.as_ref()
.map(|es| es.iter().map(|(a, _)| a).cloned().collect());
#[allow(deprecated)]
self.behaviour.inject_connection_established(
&peer_id,
&id,
@ -821,6 +843,7 @@ where
} => {
let error = error.into();
#[allow(deprecated)]
self.behaviour.inject_dial_failure(peer, handler, &error);
if let Some(peer) = peer {
@ -842,6 +865,7 @@ where
handler,
} => {
log::debug!("Incoming connection failed: {:?}", error);
#[allow(deprecated)]
self.behaviour
.inject_listen_failure(&local_addr, &send_back_addr, handler);
return Some(SwarmEvent::IncomingConnectionError {
@ -882,6 +906,7 @@ where
.into_iter()
.filter(|conn_id| !self.banned_peer_connections.contains(conn_id))
.count();
#[allow(deprecated)]
self.behaviour.inject_connection_closed(
&peer_id,
&id,
@ -901,6 +926,7 @@ where
if self.banned_peer_connections.contains(&id) {
log::debug!("Ignoring event from banned peer: {} {:?}.", peer_id, id);
} else {
#[allow(deprecated)]
self.behaviour.inject_event(peer_id, id, event);
}
}
@ -911,6 +937,7 @@ where
old_endpoint,
} => {
if !self.banned_peer_connections.contains(&id) {
#[allow(deprecated)]
self.behaviour.inject_address_change(
&peer_id,
&id,
@ -954,6 +981,7 @@ where
});
}
Err((connection_limit, handler)) => {
#[allow(deprecated)]
self.behaviour
.inject_listen_failure(&local_addr, &send_back_addr, handler);
log::warn!("Incoming connection rejected: {:?}", connection_limit);
@ -969,6 +997,7 @@ where
if !addrs.contains(&listen_addr) {
addrs.push(listen_addr.clone())
}
#[allow(deprecated)]
self.behaviour
.inject_new_listen_addr(listener_id, &listen_addr);
return Some(SwarmEvent::NewListenAddr {
@ -988,6 +1017,7 @@ where
if let Some(addrs) = self.listened_addrs.get_mut(&listener_id) {
addrs.retain(|a| a != &listen_addr);
}
#[allow(deprecated)]
self.behaviour
.inject_expired_listen_addr(listener_id, &listen_addr);
return Some(SwarmEvent::ExpiredListenAddr {
@ -1002,8 +1032,10 @@ where
log::debug!("Listener {:?}; Closed by {:?}.", listener_id, reason);
let addrs = self.listened_addrs.remove(&listener_id).unwrap_or_default();
for addr in addrs.iter() {
#[allow(deprecated)]
self.behaviour.inject_expired_listen_addr(listener_id, addr);
}
#[allow(deprecated)]
self.behaviour.inject_listener_closed(
listener_id,
match &reason {
@ -1018,6 +1050,7 @@ where
});
}
TransportEvent::ListenerError { listener_id, error } => {
#[allow(deprecated)]
self.behaviour.inject_listener_error(listener_id, &error);
return Some(SwarmEvent::ListenerError { listener_id, error });
}
@ -1868,7 +1901,7 @@ mod tests {
// The banned connection was established. Check that it was not reported to
// the behaviour of the banning swarm.
assert_eq!(
swarm2.behaviour.inject_connection_established.len(), s2_expected_conns,
swarm2.behaviour.on_connection_established.len(), s2_expected_conns,
"No additional closed connections should be reported for the banned peer"
);
@ -1882,7 +1915,7 @@ mod tests {
if swarm2.network_info().num_peers() == 0 {
// The banned connection has closed. Check that it was not reported.
assert_eq!(
swarm2.behaviour.inject_connection_closed.len(), s2_expected_conns,
swarm2.behaviour.on_connection_closed.len(), s2_expected_conns,
"No additional closed connections should be reported for the banned peer"
);
assert!(swarm2.banned_peer_connections.is_empty());
@ -1897,7 +1930,7 @@ mod tests {
}
}
Stage::Reconnecting => {
if swarm1.behaviour.inject_connection_established.len() == s1_expected_conns
if swarm1.behaviour.on_connection_established.len() == s1_expected_conns
&& swarm2.behaviour.assert_connected(s2_expected_conns, 2)
{
return Poll::Ready(());
@ -2082,9 +2115,8 @@ mod tests {
State::Connecting => {
if swarms_connected(&swarm1, &swarm2, num_connections) {
disconnected_conn_id = {
let conn_id = swarm2.behaviour.inject_connection_established
[num_connections / 2]
.1;
let conn_id =
swarm2.behaviour.on_connection_established[num_connections / 2].1;
swarm2.behaviour.inner().next_action.replace(
NetworkBehaviourAction::CloseConnection {
peer_id: swarm1_id,
@ -2100,20 +2132,17 @@ mod tests {
for s in &[&swarm1, &swarm2] {
assert!(s
.behaviour
.inject_connection_closed
.on_connection_closed
.iter()
.all(|(.., remaining_conns)| *remaining_conns > 0));
assert_eq!(
s.behaviour.inject_connection_established.len(),
num_connections
);
assert_eq!(s.behaviour.on_connection_established.len(), num_connections);
s.behaviour.assert_connected(num_connections, 1);
}
if [&swarm1, &swarm2]
.iter()
.all(|s| s.behaviour.inject_connection_closed.len() == 1)
.all(|s| s.behaviour.on_connection_closed.len() == 1)
{
let conn_id = swarm2.behaviour.inject_connection_closed[0].1;
let conn_id = swarm2.behaviour.on_connection_closed[0].1;
assert_eq!(Some(conn_id), disconnected_conn_id);
return Poll::Ready(());
}

View File

@ -18,8 +18,12 @@
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
use crate::behaviour::{
ConnectionClosed, ConnectionEstablished, DialFailure, ExpiredExternalAddr, ExpiredListenAddr,
FromSwarm, ListenerClosed, ListenerError, NewExternalAddr, NewListenAddr, NewListener,
};
use crate::{
ConnectionHandler, DialError, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction,
ConnectionHandler, IntoConnectionHandler, NetworkBehaviour, NetworkBehaviourAction,
PollParameters,
};
use libp2p_core::{
@ -76,8 +80,6 @@ where
self.addresses.get(p).map_or(Vec::new(), |v| v.clone())
}
fn inject_event(&mut self, _: PeerId, _: ConnectionId, _: THandler::OutEvent) {}
fn poll(
&mut self,
_: &mut Context,
@ -85,6 +87,32 @@ where
) -> Poll<NetworkBehaviourAction<Self::OutEvent, Self::ConnectionHandler>> {
self.next_action.take().map_or(Poll::Pending, Poll::Ready)
}
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
match event {
FromSwarm::ConnectionEstablished(_)
| FromSwarm::ConnectionClosed(_)
| FromSwarm::AddressChange(_)
| FromSwarm::DialFailure(_)
| FromSwarm::ListenFailure(_)
| FromSwarm::NewListener(_)
| FromSwarm::NewListenAddr(_)
| FromSwarm::ExpiredListenAddr(_)
| FromSwarm::ListenerError(_)
| FromSwarm::ListenerClosed(_)
| FromSwarm::NewExternalAddr(_)
| FromSwarm::ExpiredExternalAddr(_) => {}
}
}
fn on_connection_handler_event(
&mut self,
_peer_id: PeerId,
_connection_id: ConnectionId,
_event: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as
ConnectionHandler>::OutEvent,
) {
}
}
/// A `CallTraceBehaviour` is a `NetworkBehaviour` that tracks
@ -97,43 +125,45 @@ where
inner: TInner,
pub addresses_of_peer: Vec<PeerId>,
pub inject_connection_established: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>,
pub inject_connection_closed: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>,
pub inject_event: Vec<(
pub on_connection_established: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>,
pub on_connection_closed: Vec<(PeerId, ConnectionId, ConnectedPoint, usize)>,
pub on_event: Vec<(
PeerId,
ConnectionId,
<<TInner::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
)>,
pub inject_dial_failure: Vec<Option<PeerId>>,
pub inject_new_listener: Vec<ListenerId>,
pub inject_new_listen_addr: Vec<(ListenerId, Multiaddr)>,
pub inject_new_external_addr: Vec<Multiaddr>,
pub inject_expired_listen_addr: Vec<(ListenerId, Multiaddr)>,
pub inject_expired_external_addr: Vec<Multiaddr>,
pub inject_listener_error: Vec<ListenerId>,
pub inject_listener_closed: Vec<(ListenerId, bool)>,
pub on_dial_failure: Vec<Option<PeerId>>,
pub on_new_listener: Vec<ListenerId>,
pub on_new_listen_addr: Vec<(ListenerId, Multiaddr)>,
pub on_new_external_addr: Vec<Multiaddr>,
pub on_expired_listen_addr: Vec<(ListenerId, Multiaddr)>,
pub on_expired_external_addr: Vec<Multiaddr>,
pub on_listener_error: Vec<ListenerId>,
pub on_listener_closed: Vec<(ListenerId, bool)>,
pub poll: usize,
}
impl<TInner> CallTraceBehaviour<TInner>
where
TInner: NetworkBehaviour,
<<TInner::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent:
Clone,
{
pub fn new(inner: TInner) -> Self {
Self {
inner,
addresses_of_peer: Vec::new(),
inject_connection_established: Vec::new(),
inject_connection_closed: Vec::new(),
inject_event: Vec::new(),
inject_dial_failure: Vec::new(),
inject_new_listener: Vec::new(),
inject_new_listen_addr: Vec::new(),
inject_new_external_addr: Vec::new(),
inject_expired_listen_addr: Vec::new(),
inject_expired_external_addr: Vec::new(),
inject_listener_error: Vec::new(),
inject_listener_closed: Vec::new(),
on_connection_established: Vec::new(),
on_connection_closed: Vec::new(),
on_event: Vec::new(),
on_dial_failure: Vec::new(),
on_new_listener: Vec::new(),
on_new_listen_addr: Vec::new(),
on_new_external_addr: Vec::new(),
on_expired_listen_addr: Vec::new(),
on_expired_external_addr: Vec::new(),
on_listener_error: Vec::new(),
on_listener_closed: Vec::new(),
poll: 0,
}
}
@ -141,15 +171,15 @@ where
#[allow(dead_code)]
pub fn reset(&mut self) {
self.addresses_of_peer = Vec::new();
self.inject_connection_established = Vec::new();
self.inject_connection_closed = Vec::new();
self.inject_event = Vec::new();
self.inject_dial_failure = Vec::new();
self.inject_new_listen_addr = Vec::new();
self.inject_new_external_addr = Vec::new();
self.inject_expired_listen_addr = Vec::new();
self.inject_listener_error = Vec::new();
self.inject_listener_closed = Vec::new();
self.on_connection_established = Vec::new();
self.on_connection_closed = Vec::new();
self.on_event = Vec::new();
self.on_dial_failure = Vec::new();
self.on_new_listen_addr = Vec::new();
self.on_new_external_addr = Vec::new();
self.on_expired_listen_addr = Vec::new();
self.on_listener_error = Vec::new();
self.on_listener_closed = Vec::new();
self.poll = 0;
}
@ -158,12 +188,12 @@ where
}
pub fn num_connections_to_peer(&self, peer: PeerId) -> usize {
self.inject_connection_established
self.on_connection_established
.iter()
.filter(|(peer_id, _, _, _)| *peer_id == peer)
.count()
- self
.inject_connection_closed
.on_connection_closed
.iter()
.filter(|(peer_id, _, _, _)| *peer_id == peer)
.count()
@ -178,9 +208,9 @@ where
expected_closed_connections: usize,
expected_disconnections: usize,
) -> bool {
if self.inject_connection_closed.len() == expected_closed_connections {
if self.on_connection_closed.len() == expected_closed_connections {
assert_eq!(
self.inject_connection_closed
self.on_connection_closed
.iter()
.filter(|(.., remaining_established)| { *remaining_established == 0 })
.count(),
@ -201,9 +231,9 @@ where
expected_established_connections: usize,
expected_connections: usize,
) -> bool {
if self.inject_connection_established.len() == expected_established_connections {
if self.on_connection_established.len() == expected_established_connections {
assert_eq!(
self.inject_connection_established
self.on_connection_established
.iter()
.filter(|(.., reported_aditional_connections)| {
*reported_aditional_connections == 0
@ -216,40 +246,23 @@ where
false
}
}
impl<TInner> NetworkBehaviour for CallTraceBehaviour<TInner>
where
TInner: NetworkBehaviour,
<<TInner::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent:
Clone,
{
type ConnectionHandler = TInner::ConnectionHandler;
type OutEvent = TInner::OutEvent;
fn new_handler(&mut self) -> Self::ConnectionHandler {
self.inner.new_handler()
}
fn addresses_of_peer(&mut self, p: &PeerId) -> Vec<Multiaddr> {
self.addresses_of_peer.push(*p);
self.inner.addresses_of_peer(p)
}
fn inject_connection_established(
fn on_connection_established(
&mut self,
p: &PeerId,
c: &ConnectionId,
e: &ConnectedPoint,
errors: Option<&Vec<Multiaddr>>,
other_established: usize,
ConnectionEstablished {
peer_id,
connection_id,
endpoint,
failed_addresses,
other_established,
}: ConnectionEstablished,
) {
let mut other_peer_connections = self
.inject_connection_established
.on_connection_established
.iter()
.rev() // take last to first
.filter_map(|(peer, .., other_established)| {
if p == peer {
if &peer_id == peer {
Some(other_established)
} else {
None
@ -271,26 +284,39 @@ where
} else {
assert_eq!(other_established, 0)
}
self.inject_connection_established
.push((*p, *c, e.clone(), other_established));
self.inner
.inject_connection_established(p, c, e, errors, other_established);
self.on_connection_established.push((
peer_id,
connection_id,
endpoint.clone(),
other_established,
));
let errors = Some(failed_addresses.to_vec());
#[allow(deprecated)]
self.inner.inject_connection_established(
&peer_id,
&connection_id,
endpoint,
errors.as_ref(),
other_established,
);
}
fn inject_connection_closed(
fn on_connection_closed(
&mut self,
p: &PeerId,
c: &ConnectionId,
e: &ConnectedPoint,
handler: <Self::ConnectionHandler as IntoConnectionHandler>::Handler,
remaining_established: usize,
ConnectionClosed {
peer_id,
connection_id,
endpoint,
handler,
remaining_established,
}: ConnectionClosed<<Self as NetworkBehaviour>::ConnectionHandler>,
) {
let mut other_closed_connections = self
.inject_connection_established
.on_connection_established
.iter()
.rev() // take last to first
.filter_map(|(peer, .., remaining_established)| {
if p == peer {
if &peer_id == peer {
Some(remaining_established)
} else {
None
@ -313,87 +339,133 @@ where
assert_eq!(remaining_established, 0)
}
assert!(
self.inject_connection_established
self.on_connection_established
.iter()
.any(|(peer, conn_id, endpoint, _)| (peer, conn_id, endpoint) == (p, c, e)),
.any(|(peer, conn_id, endpoint, _)| (peer, conn_id, endpoint)
== (&peer_id, &connection_id, endpoint)),
"`inject_connection_closed` is called only for connections for \
which `inject_connection_established` was called first."
);
self.inject_connection_closed
.push((*p, *c, e.clone(), remaining_established));
self.inner
.inject_connection_closed(p, c, e, handler, remaining_established);
self.on_connection_closed.push((
peer_id,
connection_id,
endpoint.clone(),
remaining_established,
));
#[allow(deprecated)]
self.inner.inject_connection_closed(
&peer_id,
&connection_id,
endpoint,
handler,
remaining_established,
);
}
}
impl<TInner> NetworkBehaviour for CallTraceBehaviour<TInner>
where
TInner: NetworkBehaviour,
<<TInner::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent:
Clone,
{
type ConnectionHandler = TInner::ConnectionHandler;
type OutEvent = TInner::OutEvent;
fn new_handler(&mut self) -> Self::ConnectionHandler {
self.inner.new_handler()
}
fn inject_event(
fn addresses_of_peer(&mut self, p: &PeerId) -> Vec<Multiaddr> {
self.addresses_of_peer.push(*p);
self.inner.addresses_of_peer(p)
}
fn on_swarm_event(&mut self, event: FromSwarm<Self::ConnectionHandler>) {
match event {
FromSwarm::ConnectionEstablished(connection_established) => {
self.on_connection_established(connection_established)
}
FromSwarm::ConnectionClosed(connection_closed) => {
self.on_connection_closed(connection_closed)
}
FromSwarm::DialFailure(DialFailure {
peer_id,
handler,
error,
}) => {
self.on_dial_failure.push(peer_id);
#[allow(deprecated)]
self.inner.inject_dial_failure(peer_id, handler, error);
}
FromSwarm::NewListener(NewListener { listener_id }) => {
self.on_new_listener.push(listener_id);
#[allow(deprecated)]
self.inner.inject_new_listener(listener_id);
}
FromSwarm::NewListenAddr(NewListenAddr { listener_id, addr }) => {
self.on_new_listen_addr.push((listener_id, addr.clone()));
#[allow(deprecated)]
self.inner.inject_new_listen_addr(listener_id, addr);
}
FromSwarm::ExpiredListenAddr(ExpiredListenAddr { listener_id, addr }) => {
self.on_expired_listen_addr
.push((listener_id, addr.clone()));
#[allow(deprecated)]
self.inner.inject_expired_listen_addr(listener_id, addr);
}
FromSwarm::NewExternalAddr(NewExternalAddr { addr }) => {
self.on_new_external_addr.push(addr.clone());
#[allow(deprecated)]
self.inner.inject_new_external_addr(addr);
}
FromSwarm::ExpiredExternalAddr(ExpiredExternalAddr { addr }) => {
self.on_expired_external_addr.push(addr.clone());
#[allow(deprecated)]
self.inner.inject_expired_external_addr(addr);
}
FromSwarm::ListenerError(ListenerError { listener_id, err }) => {
self.on_listener_error.push(listener_id);
#[allow(deprecated)]
self.inner.inject_listener_error(listener_id, err);
}
FromSwarm::ListenerClosed(ListenerClosed {
listener_id,
reason,
}) => {
self.on_listener_closed.push((listener_id, reason.is_ok()));
#[allow(deprecated)]
self.inner.inject_listener_closed(listener_id, reason);
}
_ => {}
}
}
fn on_connection_handler_event(
&mut self,
p: PeerId,
c: ConnectionId,
e: <<Self::ConnectionHandler as IntoConnectionHandler>::Handler as ConnectionHandler>::OutEvent,
) {
assert!(
self.inject_connection_established
self.on_connection_established
.iter()
.any(|(peer_id, conn_id, ..)| *peer_id == p && c == *conn_id),
"`inject_event` is called for reported connections."
"`on_connection_handler_event` is called for reported connections."
);
assert!(
!self
.inject_connection_closed
.on_connection_closed
.iter()
.any(|(peer_id, conn_id, ..)| *peer_id == p && c == *conn_id),
"`inject_event` is never called for closed connections."
"`on_connection_handler_event` is never called for closed connections."
);
self.inject_event.push((p, c, e.clone()));
self.on_event.push((p, c, e.clone()));
#[allow(deprecated)]
self.inner.inject_event(p, c, e);
}
fn inject_dial_failure(
&mut self,
p: Option<PeerId>,
handler: Self::ConnectionHandler,
error: &DialError,
) {
self.inject_dial_failure.push(p);
self.inner.inject_dial_failure(p, handler, error);
}
fn inject_new_listener(&mut self, id: ListenerId) {
self.inject_new_listener.push(id);
self.inner.inject_new_listener(id);
}
fn inject_new_listen_addr(&mut self, id: ListenerId, a: &Multiaddr) {
self.inject_new_listen_addr.push((id, a.clone()));
self.inner.inject_new_listen_addr(id, a);
}
fn inject_expired_listen_addr(&mut self, id: ListenerId, a: &Multiaddr) {
self.inject_expired_listen_addr.push((id, a.clone()));
self.inner.inject_expired_listen_addr(id, a);
}
fn inject_new_external_addr(&mut self, a: &Multiaddr) {
self.inject_new_external_addr.push(a.clone());
self.inner.inject_new_external_addr(a);
}
fn inject_expired_external_addr(&mut self, a: &Multiaddr) {
self.inject_expired_external_addr.push(a.clone());
self.inner.inject_expired_external_addr(a);
}
fn inject_listener_error(&mut self, l: ListenerId, e: &(dyn std::error::Error + 'static)) {
self.inject_listener_error.push(l);
self.inner.inject_listener_error(l, e);
}
fn inject_listener_closed(&mut self, l: ListenerId, r: Result<(), &std::io::Error>) {
self.inject_listener_closed.push((l, r.is_ok()));
self.inner.inject_listener_closed(l, r);
}
fn poll(
&mut self,
cx: &mut Context,