use std::{net::SocketAddr, time::Duration};
use tokio::{
sync::{mpsc, oneshot},
task::JoinHandle,
time::timeout,
};
use tracing::*;
#[cfg(doc)]
use crate::{Connection, protocols::Writing};
use crate::{P2P, connections::create_connection_span, protocols::ProtocolHandler};
#[async_trait::async_trait]
pub trait Disconnect: P2P
where
Self: Clone + Send + Sync + 'static,
{
const TIMEOUT: Duration = Duration::from_secs(3);
async fn enable_disconnect(&self) {
let (from_node_sender, mut from_node_receiver) = mpsc::channel::<(
SocketAddr,
oneshot::Sender<(JoinHandle<()>, oneshot::Receiver<()>)>,
)>(self.tcp().config().max_connections as usize);
let (tx, rx) = oneshot::channel::<()>();
let self_clone = self.clone();
let disconnect_task = tokio::spawn(async move {
trace!(parent: self_clone.tcp().span(), "spawned the Disconnect handler task");
tx.send(()).unwrap();
while let Some((peer_addr, notifier)) = from_node_receiver.recv().await {
let self_clone2 = self_clone.clone();
let (done_tx, done_rx) = oneshot::channel();
let handle = tokio::spawn(async move {
if timeout(Self::TIMEOUT, self_clone2.handle_disconnect(peer_addr)).await.is_err() {
let conn_span = create_connection_span(peer_addr, self_clone2.tcp().span());
warn!(parent: conn_span, "Disconnect logic timed out");
}
let _ = done_tx.send(());
});
let _ = notifier.send((handle, done_rx)); }
});
let _ = rx.await;
self.tcp().tasks.lock().push(disconnect_task);
let hdl = Box::new(ProtocolHandler(from_node_sender));
assert!(
self.tcp().protocols.disconnect.set(hdl).is_ok(),
"the Disconnect protocol was enabled more than once!"
);
}
async fn handle_disconnect(&self, peer_addr: SocketAddr);
}