use crate::{protocols::ReturnableConnection, Connection, Pea2Pea};
use tokio::{
sync::{mpsc, oneshot},
task,
time::timeout,
};
use tracing::*;
use std::{io, time::Duration};
#[async_trait::async_trait]
pub trait Handshake: Pea2Pea
where
Self: Clone + Send + Sync + 'static,
{
async fn enable_handshake(&self) {
let (from_node_sender, mut from_node_receiver) =
mpsc::unbounded_channel::<ReturnableConnection>();
let (tx, rx) = oneshot::channel::<()>();
let self_clone = self.clone();
let handshake_task = tokio::spawn(async move {
trace!(parent: self_clone.node().span(), "spawned the Handshake handler task");
tx.send(()).unwrap();
while let Some((conn, result_sender)) = from_node_receiver.recv().await {
let addr = conn.addr;
let node = self_clone.clone();
task::spawn(async move {
debug!(parent: node.node().span(), "shaking hands with {} as the {:?}", addr, !conn.side);
let result = timeout(
Duration::from_millis(node.node().config().max_handshake_time_ms),
node.perform_handshake(conn),
)
.await;
let ret = match result {
Ok(Ok(conn)) => {
debug!(parent: node.node().span(), "successfully handshaken with {}", addr);
Ok(conn)
}
Ok(Err(e)) => {
error!(parent: node.node().span(), "handshake with {} failed: {}", addr, e);
Err(e)
}
Err(_) => {
error!(parent: node.node().span(), "handshake with {} timed out", addr);
Err(io::ErrorKind::TimedOut.into())
}
};
if result_sender.send(ret).is_err() {
unreachable!("could't return a Connection to the Node");
}
});
}
});
let _ = rx.await;
self.node().tasks.lock().push(handshake_task);
let hdl = HandshakeHandler(from_node_sender);
assert!(
self.node().protocols.handshake_handler.set(hdl).is_ok(),
"the Handshake protocol was enabled more than once!"
);
}
async fn perform_handshake(&self, conn: Connection) -> io::Result<Connection>;
}
pub struct HandshakeHandler(mpsc::UnboundedSender<ReturnableConnection>);
impl HandshakeHandler {
pub(crate) fn trigger(&self, item: ReturnableConnection) {
if self.0.send(item).is_err() {
unreachable!(); }
}
}