use std::net::SocketAddr;
use tokio::sync::{mpsc, oneshot};
use tracing::*;
#[cfg(doc)]
use crate::{
Connection,
protocols::{Reading, Writing},
};
use crate::{P2P, protocols::ProtocolHandler};
#[async_trait::async_trait]
pub trait OnConnect: P2P
where
Self: Clone + Send + Sync + 'static,
{
async fn enable_on_connect(&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 on_connect_task = tokio::spawn(async move {
trace!(parent: self_clone.tcp().span(), "spawned the OnConnect handler task");
if tx.send(()).is_err() {
error!(parent: self_clone.tcp().span(), "OnConnect handler creation interrupted! shutting down the node");
self_clone.tcp().shut_down().await;
return;
}
while let Some((addr, notifier)) = from_node_receiver.recv().await {
let self_clone2 = self_clone.clone();
tokio::spawn(async move {
self_clone2.on_connect(addr).await;
let _ = notifier.send(()); });
}
});
let _ = rx.await;
self.tcp().tasks.lock().push(on_connect_task);
let hdl = Box::new(ProtocolHandler(from_node_sender));
assert!(self.tcp().protocols.on_connect.set(hdl).is_ok(), "the OnConnect protocol was enabled more than once!");
}
async fn on_connect(&self, addr: SocketAddr);
}