Skip to main content

weirdnet_agent/remote/
memory.rs

1//! In-process channels: tests, and apps that run both ends in one process.
2
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5
6use async_trait::async_trait;
7use tokio::sync::mpsc;
8
9use super::{Channel, Dialer, FrameRx, FrameTx, RemoteError};
10
11struct MemTx(mpsc::UnboundedSender<Vec<u8>>);
12struct MemRx(mpsc::UnboundedReceiver<Vec<u8>>);
13
14#[async_trait]
15impl FrameTx for MemTx {
16    async fn send(&mut self, message: Vec<u8>) -> Result<(), RemoteError> {
17        self.0.send(message).map_err(|_| RemoteError::Closed)
18    }
19}
20
21#[async_trait]
22impl FrameRx for MemRx {
23    async fn recv(&mut self) -> Result<Option<Vec<u8>>, RemoteError> {
24        Ok(self.0.recv().await)
25    }
26}
27
28/// Two connected channel ends.
29pub fn memory_pair() -> (Channel, Channel) {
30    let (a_tx, b_rx) = mpsc::unbounded_channel();
31    let (b_tx, a_rx) = mpsc::unbounded_channel();
32    (Channel::new(Box::new(MemTx(a_tx)), Box::new(MemRx(a_rx))), Channel::new(Box::new(MemTx(b_tx)), Box::new(MemRx(b_rx))))
33}
34
35type Handler = Arc<dyn Fn(Channel, String) + Send + Sync>;
36
37/// A [`Dialer`] over [`memory_pair`]: each routed node gets a handler that receives the serving
38/// end and the protocol (it usually spawns [`super::infer::serve`] or [`super::task::serve`]).
39/// Nodes without a route are unreachable.
40#[derive(Default, Clone)]
41pub struct MemoryDialer {
42    routes: Arc<Mutex<HashMap<String, Handler>>>,
43}
44
45impl MemoryDialer {
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    pub fn route(&self, node: &str, handler: impl Fn(Channel, String) + Send + Sync + 'static) {
51        self.routes.lock().unwrap().insert(node.to_string(), Arc::new(handler));
52    }
53
54    pub fn unroute(&self, node: &str) {
55        self.routes.lock().unwrap().remove(node);
56    }
57}
58
59#[async_trait]
60impl Dialer for MemoryDialer {
61    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError> {
62        let handler = self.routes.lock().unwrap().get(node).cloned();
63        let Some(handler) = handler else {
64            return Err(RemoteError::Unreachable { message: format!("{node} is not reachable") });
65        };
66        let (ours, theirs) = memory_pair();
67        handler(theirs, protocol.to_string());
68        Ok(ours)
69    }
70}