1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
use core::fmt::{Debug, Display};
use core::marker::PhantomData;

use std::collections::{hash_map, HashMap};
use std::sync::Arc;

use anyhow::bail;
use futures::{Stream, StreamExt as _};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite};
use tokio::sync::{mpsc, Mutex};
use tokio_stream::wrappers::ReceiverStream;
use tracing::{instrument, trace};
use wasm_tokio::AsyncReadCore as _;

use crate::frame::conn::Accept;
use crate::frame::{Conn, ConnHandler, Incoming, Outgoing};
use crate::Serve;

/// wRPC server for framed transports
pub struct Server<C, I, O, H = ()> {
    handlers: Mutex<HashMap<String, HashMap<String, mpsc::Sender<(C, I, O)>>>>,
    conn_handler: PhantomData<H>,
}

impl<C, I, O, H> Server<C, I, O, H> {
    /// Constructs a new [Server]
    pub fn new() -> Self {
        Self {
            handlers: Mutex::default(),
            conn_handler: PhantomData,
        }
    }
}

impl<C, I, O> Default for Server<C, I, O> {
    fn default() -> Self {
        Self::new()
    }
}

/// Error returned by [`Server::accept`]
pub enum AcceptError<C, I, O> {
    /// I/O error
    IO(std::io::Error),
    /// Protocol version is not supported
    UnsupportedVersion(u8),
    /// Function was not handled
    UnhandledFunction {
        /// Instance
        instance: String,
        /// Function name
        name: String,
    },
    /// Message sending failed
    Send(mpsc::error::SendError<(C, I, O)>),
}

impl<C, I, O> Debug for AcceptError<C, I, O> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AcceptError::IO(err) => Debug::fmt(err, f),
            AcceptError::UnsupportedVersion(v) => write!(f, "unsupported version byte: {v}"),
            AcceptError::UnhandledFunction { instance, name } => {
                write!(f, "`{instance}#{name}` does not have a handler registered")
            }
            AcceptError::Send(err) => Debug::fmt(err, f),
        }
    }
}

impl<C, I, O> Display for AcceptError<C, I, O> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AcceptError::IO(err) => Display::fmt(err, f),
            AcceptError::UnsupportedVersion(v) => write!(f, "unsupported version byte: {v}"),
            AcceptError::UnhandledFunction { instance, name } => {
                write!(f, "`{instance}#{name}` does not have a handler registered")
            }
            AcceptError::Send(err) => Display::fmt(err, f),
        }
    }
}

impl<C, I, O> std::error::Error for AcceptError<C, I, O> {}

impl<C, I, O, H> Server<C, I, O, H>
where
    I: AsyncRead + Unpin,
    H: ConnHandler<I, O>,
{
    /// Accept a connection on an [Accept].
    ///
    /// # Errors
    ///
    /// Returns an error if accepting the connection has failed
    #[instrument(level = "trace", skip_all, ret(level = "trace"))]
    pub async fn accept(
        &self,
        listener: impl Accept<Context = C, Incoming = I, Outgoing = O>,
    ) -> Result<(), AcceptError<C, I, O>> {
        let (cx, tx, mut rx) = listener.accept().await.map_err(AcceptError::IO)?;
        let mut instance = String::default();
        let mut name = String::default();
        match rx.read_u8().await.map_err(AcceptError::IO)? {
            0x00 => {
                rx.read_core_name(&mut instance)
                    .await
                    .map_err(AcceptError::IO)?;
                rx.read_core_name(&mut name)
                    .await
                    .map_err(AcceptError::IO)?;
            }
            v => return Err(AcceptError::UnsupportedVersion(v)),
        }
        let h = self.handlers.lock().await;
        let h = h
            .get(&instance)
            .and_then(|h| h.get(&name))
            .ok_or_else(|| AcceptError::UnhandledFunction { instance, name })?;
        h.send((cx, rx, tx)).await.map_err(AcceptError::Send)?;
        Ok(())
    }
}

#[instrument(level = "trace", skip(srv, paths))]
async fn serve<C, I, O, H>(
    srv: &Server<C, I, O, H>,
    instance: &str,
    func: &str,
    paths: impl Into<Arc<[Box<[Option<usize>]>]>> + Send,
) -> anyhow::Result<impl Stream<Item = anyhow::Result<(C, Outgoing, Incoming)>> + 'static>
where
    C: Send + Sync + 'static,
    I: AsyncRead + Send + Sync + Unpin + 'static,
    O: AsyncWrite + Send + Sync + Unpin + 'static,
    H: ConnHandler<I, O>,
{
    let (tx, rx) = mpsc::channel(1024);
    let mut handlers = srv.handlers.lock().await;
    match handlers
        .entry(instance.to_string())
        .or_default()
        .entry(func.to_string())
    {
        hash_map::Entry::Occupied(_) => {
            bail!("handler for `{instance}#{func}` already exists")
        }
        hash_map::Entry::Vacant(entry) => {
            entry.insert(tx);
        }
    }
    let paths = paths.into();
    Ok(ReceiverStream::new(rx).map(move |(cx, rx, tx)| {
        trace!("received invocation");
        let Conn { tx, rx } = Conn::new::<H, _, _, _>(rx, tx, paths.iter());
        Ok((cx, tx, rx))
    }))
}

impl<C, I, O, H> Serve for Server<C, I, O, H>
where
    C: Send + Sync + 'static,
    I: AsyncRead + Send + Sync + Unpin + 'static,
    O: AsyncWrite + Send + Sync + Unpin + 'static,
    H: ConnHandler<I, O> + Send + Sync,
{
    type Context = C;
    type Outgoing = Outgoing;
    type Incoming = Incoming;

    async fn serve(
        &self,
        instance: &str,
        func: &str,
        paths: impl Into<Arc<[Box<[Option<usize>]>]>> + Send,
    ) -> anyhow::Result<
        impl Stream<Item = anyhow::Result<(Self::Context, Self::Outgoing, Self::Incoming)>> + 'static,
    > {
        serve(self, instance, func, paths).await
    }
}

impl<C, I, O, H> Serve for &Server<C, I, O, H>
where
    C: Send + Sync + 'static,
    I: AsyncRead + Send + Sync + Unpin + 'static,
    O: AsyncWrite + Send + Sync + Unpin + 'static,
    H: ConnHandler<I, O> + Send + Sync,
{
    type Context = C;
    type Outgoing = Outgoing;
    type Incoming = Incoming;

    async fn serve(
        &self,
        instance: &str,
        func: &str,
        paths: impl Into<Arc<[Box<[Option<usize>]>]>> + Send,
    ) -> anyhow::Result<
        impl Stream<Item = anyhow::Result<(Self::Context, Self::Outgoing, Self::Incoming)>> + 'static,
    > {
        serve(self, instance, func, paths).await
    }
}