aimo_core/
router.rs

1use anyhow::anyhow;
2use async_trait::async_trait;
3use tokio::sync::mpsc;
4
5use crate::transport::{Request, Response};
6
7/// RequestTransport is owned by connection sender
8pub struct Connection<TSend, TRecv> {
9    pub tx: mpsc::Sender<TSend>,
10    pub rx: mpsc::Receiver<TRecv>,
11}
12
13impl<TSend, TRecv> Connection<TSend, TRecv> {
14    pub async fn recv(&mut self) -> anyhow::Result<TRecv> {
15        self.rx.recv().await.ok_or(anyhow!("Connection closed"))
16    }
17}
18
19pub fn make_connection<TSend, TRecv>(
20    send_buffer: usize,
21    recv_buffer: usize,
22) -> (Connection<TSend, TRecv>, Connection<TRecv, TSend>) {
23    let (send_tx, send_rx) = mpsc::channel(send_buffer);
24    let (recv_tx, recv_rx) = mpsc::channel(recv_buffer);
25
26    (
27        Connection {
28            tx: send_tx,
29            rx: recv_rx,
30        },
31        Connection {
32            tx: recv_tx,
33            rx: send_rx,
34        },
35    )
36}
37
38pub type ResponseHandler = Connection<Response, Request>;
39
40/// Request to response transport abstraction
41///
42/// ```
43/// // > Clients
44/// // send request ------------------> Received response
45/// // --------------------------------------
46/// // > Connection to Router
47/// // tx                               rx
48/// //  |                                |
49/// // rx                               tx
50/// // --------------------------------------
51/// // > Router: We're here
52/// // Find responder tx by id         Find requester by id
53/// // --------------------------------------
54/// // > Connection to service providers
55/// // tx                              rx
56/// //  |                               |
57/// // rx                              tx
58/// // --------------------------------------
59/// // > Service providers
60/// // responder -----> process -----> Response
61/// ```
62#[async_trait]
63pub trait Router {
64    async fn route_request(&self, request: Request) -> anyhow::Result<mpsc::Receiver<Response>>;
65
66    async fn register_service(&self, service_id: String) -> anyhow::Result<ResponseHandler>;
67
68    async fn drop_service(&self, service_id: String) -> anyhow::Result<()>;
69}