use std::net::SocketAddr;
use tokio::sync::{mpsc, oneshot};
use tracing::*;
#[cfg(doc)]
use crate::{Connection, protocols::Writing};
use crate::{P2P, protocols::ProtocolHandler};
#[async_trait::async_trait]
pub trait Disconnect: P2P
where
Self: Clone + Send + Sync + 'static,
{
async fn enable_disconnect(&self) {
let (from_node_sender, mut from_node_receiver) = mpsc::unbounded_channel::<(SocketAddr, oneshot::Sender<()>)>();
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();
tokio::spawn(async move {
self_clone2.handle_disconnect(peer_addr).await;
let _ = notifier.send(()); });
}
});
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);
}