use std::{future::Future, io, panic::AssertUnwindSafe, time::Duration};
use futures_util::FutureExt;
use tokio::{
io::{AsyncRead, AsyncWrite, split},
net::TcpStream,
sync::mpsc,
time::timeout,
};
use tracing::*;
#[cfg(doc)]
use crate::Node;
use crate::{
Connection, Pea2Pea,
node::NodeTask,
protocols::{
ProtocolHandler, ReturnableConnection, install_protocol_handler, panic_message,
run_setup_handler_loop,
},
};
pub trait Handshake: Pea2Pea
where
Self: Clone + Send + Sync + 'static,
{
const TIMEOUT_MS: u64 = 3_000;
fn enable_handshake(&self) -> impl Future<Output = ()> + Send {
async {
let (conn_sender, conn_receiver) =
mpsc::channel::<ReturnableConnection>(self.node().config().max_connecting as usize);
let self_clone = self.clone();
let handler_loop = async move {
let node = self_clone.node().clone();
run_setup_handler_loop(node, "Handshake", conn_receiver, |conn, setup_tasks| {
let self_clone = self_clone.clone();
setup_tasks.spawn(async move {
self_clone.handle_new_connection(conn).await;
});
})
.await;
};
install_protocol_handler(
self.node(),
NodeTask::Handshake,
"Handshake",
|protocols| &protocols.handshake,
ProtocolHandler(conn_sender),
handler_loop,
)
.await;
}
}
fn perform_handshake(
&self,
conn: Connection,
) -> impl Future<Output = io::Result<Connection>> + Send;
fn borrow_stream<'a>(&self, conn: &'a mut Connection) -> &'a mut TcpStream {
conn.stream
.as_mut()
.expect("Stream not found; perhaps you've already called take_stream?")
}
fn take_stream(&self, conn: &mut Connection) -> TcpStream {
conn.stream
.take()
.expect("Stream already taken; make sure take_stream is only called once")
}
fn return_stream<T: AsyncRead + AsyncWrite + Send + Sync + 'static>(
&self,
conn: &mut Connection,
stream: T,
) {
let (reader, writer) = split(stream);
conn.reader = Some(Box::new(reader));
conn.writer = Some(Box::new(writer));
}
}
trait HandshakeInternal: Handshake {
fn handle_new_connection(
&self,
conn_with_returner: ReturnableConnection,
) -> impl Future<Output = ()> + Send;
}
impl<H: Handshake> HandshakeInternal for H {
async fn handle_new_connection(&self, (conn, conn_returner): ReturnableConnection) {
let conn_span = conn.span().clone();
debug!(parent: &conn_span, "executing Handshake logic...");
let handshake = AssertUnwindSafe(self.perform_handshake(conn)).catch_unwind();
let result = timeout(Duration::from_millis(Self::TIMEOUT_MS), handshake).await;
let ret = match result {
Ok(Ok(Ok(conn))) => {
debug!(parent: &conn_span, "handshake succeeded");
Ok(conn)
}
Ok(Ok(Err(e))) => {
error!(parent: &conn_span, "handshake failed: {e}");
Err(e)
}
Ok(Err(payload)) => {
error!(parent: &conn_span, "Handshake::perform_handshake panicked: {}", panic_message(&*payload));
Err(io::Error::other("Handshake::perform_handshake panicked"))
}
Err(_) => {
self.node().heuristics().register_handshake_timeout();
error!(parent: &conn_span, "handshake timed out");
Err(io::ErrorKind::TimedOut.into())
}
};
if conn_returner.send(ret).is_err() {
error!(parent: conn_span, "couldn't return a Connection from the Handshake handler");
}
}
}