use crate::{protocols::ReturnableItem, Pea2Pea};
#[cfg(doc)]
use crate::{protocols::Writing, Connection};
use tokio::{
sync::{mpsc, oneshot},
task,
};
use tracing::*;
use std::net::SocketAddr;
#[async_trait::async_trait]
pub trait Disconnect: Pea2Pea
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.node().span(), "spawned the Disconnect handler task");
tx.send(()).unwrap();
while let Some((addr, notifier)) = from_node_receiver.recv().await {
let self_clone2 = self_clone.clone();
task::spawn(async move {
self_clone2.handle_disconnect(addr).await;
let _ = notifier.send(()); });
}
});
let _ = rx.await;
self.node().tasks.lock().push(disconnect_task);
let hdl = DisconnectHandler(from_node_sender);
assert!(
self.node().protocols.disconnect_handler.set(hdl).is_ok(),
"the Disconnect protocol was enabled more than once!"
);
}
async fn handle_disconnect(&self, addr: SocketAddr);
}
pub struct DisconnectHandler(mpsc::UnboundedSender<ReturnableItem<SocketAddr, ()>>);
impl DisconnectHandler {
pub(crate) fn trigger(&self, item: ReturnableItem<SocketAddr, ()>) {
if self.0.send(item).is_err() {
unreachable!(); }
}
}