use std::{future::Future, net::SocketAddr};
use tokio::sync::{mpsc, oneshot};
use tracing::*;
#[cfg(doc)]
use crate::{
Connection, Node,
protocols::{Handshake, OnDisconnect, Reading, Writing},
};
use crate::{Pea2Pea, node::NodeTask, protocols::ProtocolHandler};
pub trait OnConnect: Pea2Pea
where
Self: Clone + Send + Sync + 'static,
{
fn enable_on_connect(&self) -> impl Future<Output = ()> {
async {
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.node().span(), "spawned the OnConnect handler task");
if tx.send(()).is_err() {
error!(parent: self_clone.node().span(), "OnConnect handler creation interrupted! shutting down the node");
self_clone.node().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.node()
.tasks
.lock()
.insert(NodeTask::OnConnect, on_connect_task);
let hdl = ProtocolHandler(from_node_sender);
assert!(
self.node().protocols.on_connect.set(hdl).is_ok(),
"the OnConnect protocol was enabled more than once!"
);
}
}
fn on_connect(&self, addr: SocketAddr) -> impl Future<Output = ()> + Send;
}