#![cfg_attr(docsrs, feature(doc_cfg, doc_auto_cfg))]
mod handler;
mod protocol;
use std::{
collections::VecDeque,
task::{Context, Poll},
time::Duration,
};
use ant_libp2p_core::{transport::PortUse, Endpoint, Multiaddr};
use ant_libp2p_swarm::{
behaviour::FromSwarm, ConnectionDenied, ConnectionId, NetworkBehaviour, THandler,
THandlerInEvent, THandlerOutEvent, ToSwarm,
};
use handler::Handler;
pub use handler::{Config, Failure};
use libp2p_identity::PeerId;
pub use self::protocol::PROTOCOL_NAME;
pub struct Behaviour {
config: Config,
events: VecDeque<Event>,
}
#[derive(Debug)]
pub struct Event {
pub peer: PeerId,
pub connection: ConnectionId,
pub result: Result<Duration, Failure>,
}
impl Behaviour {
pub fn new(config: Config) -> Self {
Self {
config,
events: VecDeque::new(),
}
}
}
impl Default for Behaviour {
fn default() -> Self {
Self::new(Config::new())
}
}
impl NetworkBehaviour for Behaviour {
type ConnectionHandler = Handler;
type ToSwarm = Event;
fn handle_established_inbound_connection(
&mut self,
_: ConnectionId,
_: PeerId,
_: &Multiaddr,
_: &Multiaddr,
) -> Result<THandler<Self>, ConnectionDenied> {
Ok(Handler::new(self.config.clone()))
}
fn handle_established_outbound_connection(
&mut self,
_: ConnectionId,
_: PeerId,
_: &Multiaddr,
_: Endpoint,
_: PortUse,
) -> Result<THandler<Self>, ConnectionDenied> {
Ok(Handler::new(self.config.clone()))
}
fn on_connection_handler_event(
&mut self,
peer: PeerId,
connection: ConnectionId,
result: THandlerOutEvent<Self>,
) {
self.events.push_front(Event {
peer,
connection,
result,
})
}
#[tracing::instrument(level = "trace", name = "NetworkBehaviour::poll", skip(self))]
fn poll(&mut self, _: &mut Context<'_>) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> {
if let Some(e) = self.events.pop_back() {
Poll::Ready(ToSwarm::GenerateEvent(e))
} else {
Poll::Pending
}
}
fn on_swarm_event(&mut self, _event: FromSwarm) {}
}