Skip to main content

taba/rpc/
router.rs

1//! Procedure router, how an app attaches handlers to procedures.
2
3use alloc::{
4    boxed::Box,
5    collections::BTreeMap,
6    string::{String, ToString},
7    vec::Vec,
8};
9use core::{fmt, future::ready};
10
11use futures_util::{FutureExt, Stream, StreamExt, stream};
12use serde::{Serialize, de::DeserializeOwned};
13use serde_json::value::{RawValue, to_raw_value};
14
15use self::sealed::Erased;
16use super::wire::Kind;
17use crate::{IntoReply, Once, Procedure, Procedures, Strand};
18
19/// A [`Router`] being assembled.
20///
21/// `S` is the state the next handlers get, `()` until [`with_state`](Self::with_state) is called.
22#[derive(Debug)]
23pub struct Builder<S = ()> {
24    names: BTreeMap<String, Pairing>,
25    state: S,
26}
27
28/// A name's declaration and handlers.
29#[derive(Debug, Default)]
30struct Pairing {
31    declared: bool,
32    handlers: Vec<Erased>,
33}
34
35impl<S> Builder<S> {
36    /// Gives the next handlers `state`.
37    pub fn with_state<S2>(self, state: S2) -> Builder<S2> {
38        Builder { names: self.names, state }
39    }
40
41    /// Replies to `P` with `handler`.
42    pub fn handle<H, Args, P>(self, handler: H) -> Self
43    where
44        H: Handler<Args, S, Request = P> + Send + Sync + 'static,
45        P: DeserializeOwned + Procedure,
46        P::Output: IntoReply,
47        H::Return: Replies<<P::Output as IntoReply>::Reply, P::Error>,
48        S: Clone + Send + Sync + 'static,
49    {
50        let state = self.state.clone();
51        self.handle_with(state, handler)
52    }
53
54    /// Replies to `P` with `handler`, which gets its own `state`.
55    pub fn handle_with<S2, H, Args, P>(mut self, state: S2, handler: H) -> Self
56    where
57        H: Handler<Args, S2, Request = P> + Send + Sync + 'static,
58        P: DeserializeOwned + Procedure,
59        P::Output: IntoReply,
60        H::Return: Replies<<P::Output as IntoReply>::Reply, P::Error>,
61        S2: Clone + Send + Sync + 'static,
62    {
63        let parsed = move |request: &RawValue| match serde_json::from_str::<P>(request.get()) {
64            Ok(request) => Ok(handler.call(state.clone(), request)),
65            Err(error) => Err(Kind::invalid(error)),
66        };
67        let erased = H::Return::erase(parsed);
68        self.names.entry(P::named().path()).or_default().handlers.push(erased);
69        self
70    }
71
72    /// A router with one handler for each procedure.
73    ///
74    /// # Errors
75    ///
76    /// Every procedure and handler that don't pair up.
77    pub fn build(self) -> Result<Router, BuildError> {
78        let mut problems = Vec::new();
79        let mut paired = BTreeMap::new();
80        for (name, Pairing { declared, mut handlers }) in self.names {
81            let handler = handlers.pop();
82            match (declared, handler, handlers.len()) {
83                (true, Some(handler), 0) => _ = paired.insert(name, handler),
84                (true, None, _) => problems.push(Problem::Missing(name)),
85                (true, Some(_), rest) => problems.push(Problem::Several(name, rest + 1)),
86                (false, _, _) => problems.push(Problem::Undeclared(name)),
87            }
88        }
89        if !problems.is_empty() {
90            return Err(BuildError(problems));
91        }
92        Ok(Router { handlers: paired })
93    }
94}
95
96/// A function that replies to a procedure.
97pub trait Handler<Args, S> {
98    /// The procedure it replies to.
99    type Request;
100
101    /// A future for a call, or a stream for a subscription.
102    type Return;
103
104    /// Replies to `request`, given the app's state.
105    fn call(&self, state: S, request: Self::Request) -> Self::Return;
106}
107
108impl<F, Fut, P, S> Handler<(P,), S> for F
109where
110    F: Fn(P) -> Fut,
111{
112    type Request = P;
113    type Return = Fut;
114
115    fn call(&self, _: S, request: P) -> Fut {
116        self(request)
117    }
118}
119
120impl<F, Fut, S, P> Handler<(State<S>, P), S> for F
121where
122    F: Fn(State<S>, P) -> Fut,
123{
124    type Request = P;
125    type Return = Fut;
126
127    fn call(&self, state: S, request: P) -> Fut {
128        self(State(state), request)
129    }
130}
131
132/// The app's state, as a handler's argument.
133#[derive(Debug)]
134pub struct State<S>(pub S);
135
136/// Handlers, by procedure name.
137#[derive(Debug)]
138pub struct Router {
139    handlers: BTreeMap<String, Erased>,
140}
141
142impl Router {
143    /// Starts a router for the procedures in `lists`.
144    pub fn builder(lists: impl IntoIterator<Item = Procedures>) -> Builder {
145        let mut builder = Builder { names: BTreeMap::new(), state: () };
146        for declaration in lists.into_iter().flat_map(|list| list.declarations) {
147            builder.names.entry((declaration.named)().path()).or_default().declared = true;
148        }
149        builder
150    }
151
152    /// Replies to a call.
153    pub(crate) fn call(
154        &self,
155        name: &str,
156        request: &RawValue,
157    ) -> impl Future<Output = Kind> + Send + use<> {
158        match self.handlers.get(name) {
159            Some(Erased::Call(call)) => call(request),
160            _ => ready(Kind::unknown(name.to_string())).boxed(),
161        }
162    }
163
164    /// Replies to a subscription, a frame per item, until its handler's stream ends.
165    pub(crate) fn subscribe(
166        &self,
167        name: &str,
168        request: &RawValue,
169    ) -> impl Stream<Item = Kind> + Send + use<> {
170        match self.handlers.get(name) {
171            Some(Erased::Strand(strand)) => strand(request),
172            _ => stream::once(ready(Kind::unknown(name.to_string()))).boxed(),
173        }
174    }
175}
176
177/// What a handler returns, for a procedure whose reply is `R`.
178///
179/// A future fits a [`Once`] reply, and a stream fits a [`Strand`]. Sitting on what the handler
180/// returns puts that type first in rustc's errors.
181///
182/// [Sealed](https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed).
183pub trait Replies<R, E>: Sized {
184    #[doc(hidden)]
185    fn erase(parsed: impl Fn(&RawValue) -> Result<Self, Kind> + Send + Sync + 'static) -> Erased;
186}
187
188impl<Fut, T, E> Replies<Once<T>, E> for Fut
189where
190    Fut: Future<Output = Result<T, E>> + Send + 'static,
191    T: Serialize + 'static,
192    E: Serialize + 'static,
193{
194    fn erase(parsed: impl Fn(&RawValue) -> Result<Fut, Kind> + Send + Sync + 'static) -> Erased {
195        Erased::Call(Box::new(move |request| match parsed(request) {
196            Ok(future) => future.map(reply).boxed(),
197            Err(reject) => ready(reject).boxed(),
198        }))
199    }
200}
201
202impl<St, T, E> Replies<Strand<T>, E> for St
203where
204    St: Stream<Item = Result<T, E>> + Send + 'static,
205    T: Serialize + 'static,
206    E: Serialize + 'static,
207{
208    fn erase(parsed: impl Fn(&RawValue) -> Result<St, Kind> + Send + Sync + 'static) -> Erased {
209        Erased::Strand(Box::new(move |request| match parsed(request) {
210            Ok(stream) => stream.map(reply).boxed(),
211            Err(reject) => stream::once(ready(reject)).boxed(),
212        }))
213    }
214}
215
216mod sealed {
217    //! [Seals] [`Replies`](super::Replies) through `erase`'s return type.
218    //!
219    //! [Seals]: https://rust-lang.github.io/api-guidelines/future-proofing.html#sealed-traits-protect-against-downstream-implementations-c-sealed
220
221    use alloc::boxed::Box;
222    use core::fmt;
223
224    use futures_util::{future::BoxFuture, stream::BoxStream};
225    use serde_json::value::RawValue;
226
227    use crate::rpc::wire::Kind;
228
229    /// A handler and its state, ready for the router.
230    pub enum Erased {
231        Call(OnRequest<BoxFuture<'static, Kind>>),
232        Strand(OnRequest<BoxStream<'static, Kind>>),
233    }
234
235    /// Parses a request and starts its handler, so the reply borrows nothing.
236    type OnRequest<T> = Box<dyn Fn(&RawValue) -> T + Send + Sync>;
237
238    impl fmt::Debug for Erased {
239        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240            f.debug_struct("Erased").finish_non_exhaustive()
241        }
242    }
243}
244
245/// A handler's result as its frame, rejected when serde can't encode it.
246fn reply<T: Serialize, E: Serialize>(result: Result<T, E>) -> Kind {
247    let encoded = match result {
248        Ok(output) => to_raw_value(&output).map(Kind::Value),
249        Err(error) => to_raw_value(&error).map(Kind::Error),
250    };
251    encoded.unwrap_or_else(Kind::unencodable)
252}
253
254/// Failed to build a [`Router`].
255#[derive(Debug)]
256pub struct BuildError(Vec<Problem>);
257
258impl fmt::Display for BuildError {
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        f.write_str("can't build the router:")?;
261        self.0.iter().try_for_each(|problem| write!(f, "\n\t{problem}"))
262    }
263}
264
265impl core::error::Error for BuildError {}
266
267#[derive(Debug)]
268enum Problem {
269    Missing(String),
270    Several(String, usize),
271    Undeclared(String),
272}
273
274impl fmt::Display for Problem {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        match self {
277            Self::Missing(name) => write!(f, "no handler for `{name}`"),
278            Self::Several(name, count) => write!(f, "{count} handlers for `{name}`"),
279            Self::Undeclared(name) => write!(f, "a handler for `{name}`, which isn't declared"),
280        }
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use std::{future::ready, prelude::rust_2024::*};
287
288    use futures_util::{FutureExt, StreamExt, stream};
289    use serde_json::value::RawValue;
290
291    use super::{Procedures, Router, State};
292    use crate::rpc::tests::{Buy, BuyError, Game, Generator, Hire, Ore, Sell};
293
294    #[test]
295    fn every_reply_kind() {
296        async fn buy(State(game): State<Game>, Buy { generator }: Buy) -> Result<u32, BuyError> {
297            match generator {
298                Generator::Drill => Ok(game.drills),
299                Generator::Furnace => Err(BuyError::CantAfford { missing: 30 }),
300            }
301        }
302
303        let sell = |State(game): State<Game>, _: Sell| ready(Ok(game.drills));
304        let ore = |_: Ore| stream::iter([Ok(3), Ok(6)]);
305
306        let shop = Procedures::new().declare::<Buy>().declare::<Sell>();
307        let mine = Procedures::new().declare::<Ore>();
308        let builder = Router::builder([shop, mine]);
309        let builder = builder.with_state(Game { drills: 3 }).handle(buy).handle(ore);
310        let router = builder.handle_with(Game { drills: 9 }, sell).build().unwrap();
311        let calls = [
312            ("taba::rpc::tests::Buy", r#"{"generator":"Drill"}"#),
313            ("taba::rpc::tests::Buy", r#"{"generator":"Furnace"}"#),
314            ("taba::rpc::tests::Buy", r#"{"generatr":"Drill"}"#),
315            ("taba::rpc::tests::Sell", "null"),
316            ("taba::rpc::tests::Hire", "null"),
317            ("taba::rpc::tests::Ore", "null"),
318        ];
319        let replies = calls.map(|(name, request)| {
320            let request = RawValue::from_string(request.into()).unwrap();
321            let reply = router.call(name, &request).now_or_never().unwrap();
322            serde_json::to_string(&reply).unwrap()
323        });
324        insta::assert_snapshot!(replies.join("\n"), @r#"
325        {"kind":"value","value":3}
326        {"kind":"error","value":{"CantAfford":{"missing":30}}}
327        {"kind":"reject","value":{"kind":"invalid","value":"missing field `generator` at line 1 column 20"}}
328        {"kind":"value","value":9}
329        {"kind":"reject","value":{"kind":"unknown","value":"taba::rpc::tests::Hire"}}
330        {"kind":"reject","value":{"kind":"unknown","value":"taba::rpc::tests::Ore"}}
331        "#);
332
333        let subscriptions = [
334            ("taba::rpc::tests::Ore", "null"),
335            ("taba::rpc::tests::Ore", "7"),
336            ("taba::rpc::tests::Buy", r#"{"generator":"Drill"}"#),
337        ];
338        let strands = subscriptions.map(|(name, request)| {
339            let request = RawValue::from_string(request.into()).unwrap();
340            let frames: Vec<_> = router.subscribe(name, &request).collect().now_or_never().unwrap();
341            serde_json::to_string(&frames).unwrap()
342        });
343        insta::assert_snapshot!(strands.join("\n"), @r#"
344        [{"kind":"value","value":3},{"kind":"value","value":6}]
345        [{"kind":"reject","value":{"kind":"invalid","value":"invalid type: integer `7`, expected unit struct Ore at line 1 column 1"}}]
346        [{"kind":"reject","value":{"kind":"unknown","value":"taba::rpc::tests::Buy"}}]
347        "#);
348    }
349
350    #[test]
351    fn every_build_problem() {
352        async fn buy(_: Buy) -> Result<u32, BuyError> {
353            Ok(0)
354        }
355
356        // a second handler for `Buy` clashes, whatever kind of handler it is
357        let also_buy = |_: Buy| ready(Ok(0));
358        let undeclared = |_: Hire| ready(Ok(0));
359
360        // the same procedure from two lists is one declaration
361        let shop = Procedures::new().declare::<Buy>().declare::<Sell>();
362        let builder = Router::builder([shop, Procedures::new().declare::<Buy>()]);
363        let error = builder.handle(buy).handle(also_buy).handle(undeclared).build().unwrap_err();
364        insta::assert_snapshot!(error, @"
365        can't build the router:
366        \t2 handlers for `taba::rpc::tests::Buy`
367        \ta handler for `taba::rpc::tests::Hire`, which isn't declared
368        \tno handler for `taba::rpc::tests::Sell`
369        ");
370    }
371}