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#[derive(Clone)]
38struct Route {
39    /// `None`: every protocol.
40    protocols: Option<Vec<String>>,
41    handler: Handler,
42}
43
44/// A [`Dialer`] over [`memory_pair`]: each routed node gets a handler that receives the serving
45/// end and the protocol (it usually spawns [`super::infer::serve`] or [`super::task::serve`]).
46/// Nodes without a route are unreachable.
47#[derive(Default, Clone)]
48pub struct MemoryDialer {
49    routes: Arc<Mutex<HashMap<String, Route>>>,
50}
51
52impl MemoryDialer {
53    pub fn new() -> Self {
54        Self::default()
55    }
56
57    pub fn route(&self, node: &str, handler: impl Fn(Channel, String) + Send + Sync + 'static) {
58        self.routes.lock().unwrap().insert(node.to_string(), Route { protocols: None, handler: Arc::new(handler) });
59    }
60
61    /// Like [`route`](Self::route), but the node serves only `protocols`; opening another one
62    /// fails with [`RemoteError::Unsupported`] (like an older node).
63    pub fn route_only(&self, node: &str, protocols: &[&str], handler: impl Fn(Channel, String) + Send + Sync + 'static) {
64        let protocols = Some(protocols.iter().map(|p| p.to_string()).collect());
65        self.routes.lock().unwrap().insert(node.to_string(), Route { protocols, handler: Arc::new(handler) });
66    }
67
68    pub fn unroute(&self, node: &str) {
69        self.routes.lock().unwrap().remove(node);
70    }
71}
72
73#[async_trait]
74impl Dialer for MemoryDialer {
75    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError> {
76        let route = self.routes.lock().unwrap().get(node).cloned();
77        let Some(route) = route else {
78            return Err(RemoteError::Unreachable { message: format!("{node} is not reachable") });
79        };
80        if route.protocols.as_ref().is_some_and(|p| !p.iter().any(|p| p == protocol)) {
81            return Err(RemoteError::Unsupported { message: format!("{node} does not accept {protocol}") });
82        }
83        let (ours, theirs) = memory_pair();
84        (route.handler)(theirs, protocol.to_string());
85        Ok(ours)
86    }
87}