extern crate alloc;
use alloc::string::String;
use async_channel::{Receiver, Sender};
use futures::{FutureExt, future::BoxFuture};
use subduction_core::{authenticated::Authenticated, handler::Handler, peer::id::PeerId};
use subduction_keyhive::{KeyhiveMessage, SignedMessage, signed_message::CborError};
#[allow(missing_debug_implementations)]
pub enum KeyhiveCommand {
HandleInbound {
peer_id: PeerId,
message: KeyhiveMessage,
reply: Sender<Result<(), HandleError>>,
},
PeerDisconnect {
peer_id: PeerId,
},
}
#[derive(Debug, thiserror::Error)]
pub enum HandleError {
#[error("failed to decode keyhive payload: {0}")]
Decode(#[from] CborError),
#[error("keyhive protocol error: {0}")]
Protocol(String),
#[error("keyhive actor has shut down")]
ActorGone,
}
#[derive(Clone)]
pub struct KeyhiveProtocolHandle {
tx: Sender<KeyhiveCommand>,
}
impl core::fmt::Debug for KeyhiveProtocolHandle {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("KeyhiveProtocolHandle")
.finish_non_exhaustive()
}
}
impl KeyhiveProtocolHandle {
#[must_use]
pub const fn new(tx: Sender<KeyhiveCommand>) -> Self {
Self { tx }
}
#[must_use]
pub fn channel() -> (Self, Receiver<KeyhiveCommand>) {
let (tx, rx) = async_channel::bounded(1024);
(Self { tx }, rx)
}
}
pub async fn run_actor<F, Fut, D, DFut>(rx: Receiver<KeyhiveCommand>, process: F, on_disconnect: D)
where
F: Fn(PeerId, SignedMessage) -> Fut,
Fut: core::future::Future<Output = Result<(), String>>,
D: Fn(PeerId) -> DFut,
DFut: core::future::Future<Output = ()>,
{
while let Ok(cmd) = rx.recv().await {
match cmd {
KeyhiveCommand::HandleInbound {
peer_id,
message,
reply,
} => {
let result = match message.into_signed() {
Ok(signed_msg) => process(peer_id, signed_msg)
.await
.map_err(HandleError::Protocol),
Err(e) => Err(HandleError::Decode(e)),
};
drop(reply.send(result).await);
}
KeyhiveCommand::PeerDisconnect { peer_id } => {
on_disconnect(peer_id).await;
}
}
}
tracing::debug!("keyhive actor shutting down (channel closed)");
}
impl<C> Handler<future_form::Sendable, C> for KeyhiveProtocolHandle
where
C: Clone + Send + Sync + 'static,
{
type Message = KeyhiveMessage;
type HandlerError = HandleError;
fn handle<'a>(
&'a self,
conn: &'a Authenticated<C, future_form::Sendable>,
message: KeyhiveMessage,
) -> BoxFuture<'a, Result<(), Self::HandlerError>> {
let peer_id = conn.peer_id();
let tx = self.tx.clone();
async move {
let (reply_tx, reply_rx) = async_channel::bounded(1);
tx.send(KeyhiveCommand::HandleInbound {
peer_id,
message,
reply: reply_tx,
})
.await
.map_err(|_| HandleError::ActorGone)?;
reply_rx.recv().await.map_err(|_| HandleError::ActorGone)?
}
.boxed()
}
fn on_peer_disconnect(&self, peer: PeerId) -> BoxFuture<'_, ()> {
let tx = self.tx.clone();
async move {
drop(
tx.send(KeyhiveCommand::PeerDisconnect { peer_id: peer })
.await,
);
}
.boxed()
}
}
#[cfg(test)]
#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
mod tests {
use alloc::{string::ToString, vec};
use subduction_keyhive::SignedMessage;
use testresult::TestResult;
use super::*;
#[derive(Clone, PartialEq)]
struct DummyConn;
fn test_peer_id() -> PeerId {
PeerId::new([0xAB; 32])
}
fn valid_keyhive_message() -> KeyhiveMessage {
let signed = SignedMessage::with_contact_card(vec![1, 2, 3], vec![4, 5, 6]);
let cbor = signed.to_cbor().expect("CBOR serialization");
KeyhiveMessage::new(cbor)
}
fn test_conn() -> Authenticated<DummyConn, future_form::Sendable> {
Authenticated::new_for_test(DummyConn, test_peer_id())
}
#[tokio::test]
async fn actor_processes_handle_inbound() -> TestResult {
let (handle, rx) = KeyhiveProtocolHandle::channel();
tokio::spawn(run_actor(
rx,
|_peer_id, _msg| async { Ok(()) },
|_peer_id| async {},
));
let conn = test_conn();
let msg = valid_keyhive_message();
let result = Handler::<future_form::Sendable, DummyConn>::handle(&handle, &conn, msg).await;
assert!(result.is_ok());
Ok(())
}
#[tokio::test]
async fn actor_processes_peer_disconnect() -> TestResult {
let (handle, rx) = KeyhiveProtocolHandle::channel();
let (done_tx, done_rx) = async_channel::bounded::<PeerId>(1);
tokio::spawn(run_actor(
rx,
|_peer_id, _msg| async { Ok(()) },
move |peer_id| {
let done_tx = done_tx.clone();
async move {
let _ = done_tx.send(peer_id).await;
}
},
));
Handler::<future_form::Sendable, DummyConn>::on_peer_disconnect(&handle, test_peer_id())
.await;
let disconnected_peer = done_rx.recv().await?;
assert_eq!(disconnected_peer, test_peer_id());
Ok(())
}
#[tokio::test]
async fn handle_returns_actor_gone_when_receiver_dropped() -> TestResult {
let (handle, rx) = KeyhiveProtocolHandle::channel();
drop(rx);
let conn = test_conn();
let msg = valid_keyhive_message();
let result = Handler::<future_form::Sendable, DummyConn>::handle(&handle, &conn, msg).await;
assert!(matches!(result, Err(HandleError::ActorGone)));
Ok(())
}
#[tokio::test]
async fn handle_returns_decode_error_for_invalid_cbor() -> TestResult {
let (handle, rx) = KeyhiveProtocolHandle::channel();
tokio::spawn(run_actor(
rx,
|_peer_id, _msg| async { Ok(()) },
|_peer_id| async {},
));
let conn = test_conn();
let msg = KeyhiveMessage::new(vec![0xFF, 0xFF]);
let result = Handler::<future_form::Sendable, DummyConn>::handle(&handle, &conn, msg).await;
assert!(matches!(result, Err(HandleError::Decode(_))));
Ok(())
}
#[tokio::test]
async fn handle_returns_protocol_error_from_process() -> TestResult {
let (handle, rx) = KeyhiveProtocolHandle::channel();
tokio::spawn(run_actor(
rx,
|_peer_id, _msg| async { Err("boom".to_string()) },
|_peer_id| async {},
));
let conn = test_conn();
let msg = valid_keyhive_message();
let result = Handler::<future_form::Sendable, DummyConn>::handle(&handle, &conn, msg).await;
match result {
Err(HandleError::Protocol(s)) => assert_eq!(s, "boom"),
other => panic!("expected Protocol(\"boom\"), got {other:?}"),
}
Ok(())
}
#[tokio::test]
async fn disconnect_is_fire_and_forget_when_actor_gone() -> TestResult {
let (handle, rx) = KeyhiveProtocolHandle::channel();
drop(rx);
Handler::<future_form::Sendable, DummyConn>::on_peer_disconnect(&handle, test_peer_id())
.await;
Ok(())
}
#[tokio::test]
async fn actor_shuts_down_when_all_handles_dropped() -> TestResult {
let (handle, rx) = KeyhiveProtocolHandle::channel();
let (done_tx, done_rx) = async_channel::bounded::<()>(1);
tokio::spawn(async move {
run_actor(rx, |_peer_id, _msg| async { Ok(()) }, |_peer_id| async {}).await;
let _ = done_tx.send(()).await;
});
drop(handle);
done_rx.recv().await?;
Ok(())
}
}