use std::{
future::Future,
net::SocketAddr,
panic::{AssertUnwindSafe, resume_unwind},
};
use futures_util::FutureExt;
use tokio::{
sync::{mpsc, oneshot},
task::JoinHandle,
};
use tracing::*;
#[cfg(doc)]
use crate::{
Connection, Node,
protocols::{Handshake, OnDisconnect, Reading, Writing},
};
use crate::{
Pea2Pea,
connections::{DisconnectOrigin, create_connection_span},
node::NodeTask,
protocols::{DisconnectOnDrop, ProtocolHandler, panic_message},
};
pub(crate) type OnConnectBundle = (JoinHandle<()>, bool);
pub trait OnConnect: Pea2Pea
where
Self: Clone + Send + Sync + 'static,
{
const ABORTABLE: bool = true;
fn enable_on_connect(&self) -> impl Future<Output = ()> {
async {
assert!(
self.node().protocols.on_connect.get().is_none(),
"the OnConnect protocol was enabled more than once!"
);
let (from_node_sender, mut from_node_receiver) =
mpsc::channel::<(SocketAddr, oneshot::Sender<OnConnectBundle>)>(
self.node().config().max_connections as usize,
);
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();
let handle = tokio::spawn(async move {
let mut conn_cleanup = DisconnectOnDrop::new(
self_clone2.node().clone(),
addr,
DisconnectOrigin::OnConnectAbort,
);
match AssertUnwindSafe(self_clone2.on_connect(addr))
.catch_unwind()
.await
{
Ok(()) => {
conn_cleanup.node.take();
}
Err(payload) => {
let conn_span =
create_connection_span(addr, self_clone2.node().span());
error!(parent: conn_span, "OnConnect::on_connect panicked: {}", panic_message(&*payload));
resume_unwind(payload); }
}
});
let _ = notifier.send((handle, Self::ABORTABLE)); }
});
let _ = rx.await;
if self
.node()
.register_task(NodeTask::OnConnect, on_connect_task)
.is_err()
{
trace!("the node shut down before the OnConnect protocol could be enabled");
return;
}
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;
}