Skip to main content

weirdnet_service/
service.rs

1//! Request/response services and sessions.
2//!
3//! A session is one stream. The client sends `Hello` with its [`Credentials`]; the server
4//! checks [`Access::session`] and answers `Welcome` (or `Failed`, then closes). After that the
5//! client sends `Call { id, body }` frames and the server answers each with `Ok { id, body }`
6//! or `Err { id, error }`, in completion order. Up to [`SessionOptions::max_in_flight`] calls
7//! run at once and up to [`SessionOptions::max_queued`] more wait for a slot; beyond that a
8//! call is answered [`ServiceError::Busy`], so a fast client never queues without bound.
9//! `Cancel { id }` stops a running or waiting call.
10
11use std::collections::{HashMap, VecDeque};
12use std::future::Future;
13use std::marker::PhantomData;
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::sync::{Arc, Mutex};
16use std::time::Duration;
17
18use serde::de::DeserializeOwned;
19use serde::{Deserialize, Serialize};
20use tokio::sync::{mpsc, oneshot};
21
22use crate::codec::{from_cbor, to_cbor};
23use crate::{Access, Admitted, Authorize, Caller, Channel, Credentials, ServiceError, WIRE};
24
25/// A typed request/response service. The request and response types are usually enums shared
26/// by the server and its clients (a `myapp-proto` crate).
27///
28/// ```
29/// use weirdnet_service::{Access, Admitted, Service, ServiceError};
30///
31/// struct Echo;
32///
33/// impl Service for Echo {
34///     type Request = String;
35///     type Response = String;
36///
37///     fn access(&self, _request: &String) -> Access {
38///         Access::new("echo")
39///     }
40///
41///     async fn call(&self, _who: Admitted, request: String) -> Result<String, ServiceError> {
42///         Ok(request)
43///     }
44/// }
45/// ```
46pub trait Service: Send + Sync + 'static {
47    type Request: DeserializeOwned + Send + 'static;
48    type Response: Serialize + Send + 'static;
49
50    /// What the request needs; the session asks the [`Authorize`] hook before [`call`](Self::call).
51    fn access(&self, request: &Self::Request) -> Access;
52
53    /// Handles one authorized request. `who` is what the hook returned.
54    fn call(&self, who: Admitted, request: Self::Request) -> impl Future<Output = Result<Self::Response, ServiceError>> + Send;
55}
56
57/// How a server runs sessions.
58#[derive(Debug, Clone)]
59#[non_exhaustive]
60pub struct SessionOptions {
61    /// Calls running at once per session (default 32).
62    pub max_in_flight: usize,
63    /// Calls waiting for a free slot (default 256); more are answered [`ServiceError::Busy`].
64    pub max_queued: usize,
65    /// How long a new stream may take to say `Hello` (default 10 s).
66    pub hello_timeout: Duration,
67}
68
69impl Default for SessionOptions {
70    fn default() -> Self {
71        Self { max_in_flight: 32, max_queued: 256, hello_timeout: Duration::from_secs(10) }
72    }
73}
74
75impl SessionOptions {
76    pub fn with_max_in_flight(mut self, n: usize) -> Self {
77        self.max_in_flight = n.max(1);
78        self
79    }
80
81    pub fn with_max_queued(mut self, n: usize) -> Self {
82        self.max_queued = n;
83        self
84    }
85
86    pub fn with_hello_timeout(mut self, d: Duration) -> Self {
87        self.hello_timeout = d;
88        self
89    }
90}
91
92#[derive(Debug, Serialize, Deserialize)]
93#[serde(rename_all = "snake_case")]
94pub(crate) enum ClientFrame {
95    Hello {
96        wire: u8,
97        credentials: Credentials,
98    },
99    Call {
100        id: u64,
101        #[serde(with = "serde_bytes")]
102        body: Vec<u8>,
103    },
104    Cancel {
105        id: u64,
106    },
107}
108
109#[derive(Debug, Serialize, Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub(crate) enum ServerFrame {
112    Welcome {
113        wire: u8,
114    },
115    Ok {
116        id: u64,
117        #[serde(with = "serde_bytes")]
118        body: Vec<u8>,
119    },
120    Err {
121        id: u64,
122        error: ServiceError,
123    },
124    Failed(ServiceError),
125}
126
127impl ServerFrame {
128    fn id(&self) -> Option<u64> {
129        match self {
130            ServerFrame::Ok { id, .. } | ServerFrame::Err { id, .. } => Some(*id),
131            _ => None,
132        }
133    }
134}
135
136/// Reads the `Hello` (or a feed's first message) within the timeout.
137pub(crate) async fn first<T: DeserializeOwned>(ch: &mut Channel, timeout: Duration) -> Result<Option<T>, ServiceError> {
138    match tokio::time::timeout(timeout, ch.recv_cbor::<T>()).await {
139        Ok(r) => r,
140        Err(_) => Err(ServiceError::Timeout),
141    }
142}
143
144/// Serves one session on `ch`. `peer` must be the transport-authenticated peer id. Returns
145/// when the client closes its side and every call has answered, or on a protocol error.
146pub async fn serve_session<S: Service>(
147    service: Arc<S>,
148    auth: Arc<dyn Authorize>,
149    mut ch: Channel,
150    peer: String,
151    options: &SessionOptions,
152) -> Result<(), ServiceError> {
153    let credentials = match first::<ClientFrame>(&mut ch, options.hello_timeout).await {
154        Ok(Some(ClientFrame::Hello { wire, credentials })) if wire == WIRE => credentials,
155        Ok(Some(ClientFrame::Hello { wire, .. })) => {
156            return ch.send_cbor(&ServerFrame::Failed(ServiceError::unsupported(format!("wire version {wire}")))).await;
157        }
158        Ok(Some(_)) => return ch.send_cbor(&ServerFrame::Failed(ServiceError::protocol("expected hello"))).await,
159        Ok(None) => return Ok(()),
160        Err(e) => {
161            let _ = ch.send_cbor(&ServerFrame::Failed(e.clone())).await;
162            return Err(e);
163        }
164    };
165    let caller = Caller::new(peer, credentials);
166    if let Err(e) = auth.authorize(&caller, &Access::session()) {
167        return ch.send_cbor(&ServerFrame::Failed(e)).await;
168    }
169    ch.send_cbor(&ServerFrame::Welcome { wire: WIRE }).await?;
170    let caller = Arc::new(caller);
171    let max = options.max_in_flight.max(1);
172    let Channel { mut tx, mut rx } = ch;
173    let (done_tx, mut done_rx) = mpsc::channel::<ServerFrame>(max);
174    let mut running: HashMap<u64, tokio::task::AbortHandle> = HashMap::new();
175    let mut queued: VecDeque<(u64, Admitted, S::Request)> = VecDeque::new();
176    let spawn = |id: u64, who: Admitted, request: S::Request| {
177        let (svc, done) = (service.clone(), done_tx.clone());
178        tokio::spawn(async move {
179            let frame = match svc.call(who, request).await {
180                Ok(resp) => match to_cbor(&resp) {
181                    Ok(body) => ServerFrame::Ok { id, body },
182                    Err(error) => ServerFrame::Err { id, error },
183                },
184                Err(error) => ServerFrame::Err { id, error },
185            };
186            let _ = done.send(frame).await;
187        })
188        .abort_handle()
189    };
190    let mut reading = true;
191    let result = loop {
192        if !reading && running.is_empty() && queued.is_empty() {
193            break Ok(());
194        }
195        tokio::select! {
196            frame = rx.recv(), if reading => {
197                let bytes = match frame {
198                    Ok(Some(b)) => b,
199                    Ok(None) => { reading = false; continue }
200                    Err(e) => break Err(e),
201                };
202                let reply = match from_cbor::<ClientFrame>(&bytes) {
203                    Ok(ClientFrame::Call { id, body }) => {
204                        if running.contains_key(&id) || queued.iter().any(|(q, _, _)| *q == id) {
205                            Some(ServerFrame::Err { id, error: ServiceError::bad_request("a call with this id is running") })
206                        } else {
207                            match from_cbor::<S::Request>(&body) {
208                                Err(e) => Some(ServerFrame::Err { id, error: ServiceError::bad_request(e.to_string()) }),
209                                Ok(request) => {
210                                    let access = service.access(&request);
211                                    match auth.authorize(&caller, &access) {
212                                        Err(error) => Some(ServerFrame::Err { id, error }),
213                                        Ok(who) if running.len() < max => {
214                                            running.insert(id, spawn(id, who, request));
215                                            None
216                                        }
217                                        Ok(who) if queued.len() < options.max_queued => {
218                                            queued.push_back((id, who, request));
219                                            None
220                                        }
221                                        Ok(_) => Some(ServerFrame::Err { id, error: ServiceError::Busy }),
222                                    }
223                                }
224                            }
225                        }
226                    }
227                    Ok(ClientFrame::Cancel { id }) => {
228                        let was_queued = queued.iter().position(|(q, _, _)| *q == id).map(|i| queued.remove(i)).is_some();
229                        let was_running = running.remove(&id).map(|h| h.abort()).is_some();
230                        (was_queued || was_running).then_some(ServerFrame::Err { id, error: ServiceError::Cancelled })
231                    }
232                    Ok(ClientFrame::Hello { .. }) => {
233                        let _ = tx.send(to_cbor(&ServerFrame::Failed(ServiceError::protocol("hello twice")))?).await;
234                        break Err(ServiceError::protocol("hello twice"));
235                    }
236                    Err(e) => {
237                        let _ = tx.send(to_cbor(&ServerFrame::Failed(e.clone()))?).await;
238                        break Err(e);
239                    }
240                };
241                if let Some(reply) = reply && let Err(e) = tx.send(to_cbor(&reply)?).await {
242                    break Err(e);
243                }
244            }
245            Some(frame) = done_rx.recv() => {
246                // A cancelled call that finished anyway has already been answered.
247                if frame.id().is_some_and(|id| running.remove(&id).is_some()) && let Err(e) = tx.send(to_cbor(&frame)?).await {
248                    break Err(e);
249                }
250            }
251        }
252        while running.len() < max
253            && let Some((id, who, request)) = queued.pop_front()
254        {
255            running.insert(id, spawn(id, who, request));
256        }
257    };
258    for h in running.values() {
259        h.abort();
260    }
261    result
262}
263
264enum Out {
265    Call { id: u64, body: Vec<u8> },
266    Cancel { id: u64 },
267}
268
269type Pending = Arc<Mutex<HashMap<u64, oneshot::Sender<Result<Vec<u8>, ServiceError>>>>>;
270
271fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
272    m.lock().unwrap_or_else(|e| e.into_inner())
273}
274
275/// A client's open session: concurrent typed calls over one stream. Cheap to share by
276/// reference; dropping it closes the stream once calls under way have answered or been
277/// dropped.
278pub struct Session<Req, Resp> {
279    out: mpsc::Sender<Out>,
280    pending: Pending,
281    next: AtomicU64,
282    closed: tokio::sync::watch::Receiver<bool>,
283    task: tokio::task::JoinHandle<()>,
284    _types: PhantomData<fn(Req) -> Resp>,
285}
286
287impl<Req, Resp> Drop for Session<Req, Resp> {
288    fn drop(&mut self) {
289        self.task.abort();
290    }
291}
292
293struct CancelGuard<'a> {
294    id: u64,
295    out: &'a mpsc::Sender<Out>,
296    pending: &'a Pending,
297    armed: bool,
298}
299
300impl Drop for CancelGuard<'_> {
301    fn drop(&mut self) {
302        if self.armed && lock(self.pending).remove(&self.id).is_some() {
303            let _ = self.out.try_send(Out::Cancel { id: self.id });
304        }
305    }
306}
307
308impl<Req: Serialize + Sync, Resp: DeserializeOwned> Session<Req, Resp> {
309    /// Says `Hello` on `ch` and waits for `Welcome`. Call from a Tokio runtime.
310    pub async fn start(mut ch: Channel, credentials: Credentials) -> Result<Self, ServiceError> {
311        ch.send_cbor(&ClientFrame::Hello { wire: WIRE, credentials }).await?;
312        match ch.recv_cbor::<ServerFrame>().await? {
313            Some(ServerFrame::Welcome { .. }) => {}
314            Some(ServerFrame::Failed(e)) => return Err(e),
315            Some(other) => return Err(ServiceError::protocol(format!("expected welcome, got {other:?}"))),
316            None => return Err(ServiceError::Closed),
317        }
318        let (out, mut out_rx) = mpsc::channel::<Out>(64);
319        let pending: Pending = Arc::default();
320        let (closed_tx, closed) = tokio::sync::watch::channel(false);
321        let p = pending.clone();
322        let Channel { mut tx, mut rx } = ch;
323        let task = tokio::spawn(async move {
324            let mut fail = ServiceError::Closed;
325            loop {
326                tokio::select! {
327                    o = out_rx.recv() => {
328                        let frame = match o {
329                            Some(Out::Call { id, body }) => ClientFrame::Call { id, body },
330                            Some(Out::Cancel { id }) => ClientFrame::Cancel { id },
331                            None => break,
332                        };
333                        let sent = match to_cbor(&frame) {
334                            Ok(bytes) => tx.send(bytes).await,
335                            Err(e) => Err(e),
336                        };
337                        if sent.is_err() {
338                            break;
339                        }
340                    }
341                    m = rx.recv() => {
342                        let frame = match m {
343                            Ok(Some(bytes)) => match from_cbor::<ServerFrame>(&bytes) {
344                                Ok(f) => f,
345                                Err(e) => { fail = e; break }
346                            },
347                            Ok(None) => break,
348                            Err(e) => { fail = e; break }
349                        };
350                        match frame {
351                            ServerFrame::Ok { id, body } => {
352                                if let Some(t) = lock(&p).remove(&id) {
353                                    let _ = t.send(Ok(body));
354                                }
355                            }
356                            ServerFrame::Err { id, error } => {
357                                if let Some(t) = lock(&p).remove(&id) {
358                                    let _ = t.send(Err(error));
359                                }
360                            }
361                            ServerFrame::Failed(e) => { fail = e; break }
362                            ServerFrame::Welcome { .. } => { fail = ServiceError::protocol("welcome twice"); break }
363                        }
364                    }
365                }
366            }
367            // Close the queue first, so a call racing the end fails to send instead of waiting.
368            out_rx.close();
369            let _ = closed_tx.send(true);
370            for (_, t) in lock(&p).drain() {
371                let _ = t.send(Err(fail.clone()));
372            }
373        });
374        Ok(Self { out, pending, next: AtomicU64::new(1), closed, task, _types: PhantomData })
375    }
376
377    /// One call. Dropping the future cancels the call on the server.
378    pub async fn call(&self, request: &Req) -> Result<Resp, ServiceError> {
379        if self.is_closed() {
380            return Err(ServiceError::Closed);
381        }
382        let id = self.next.fetch_add(1, Ordering::Relaxed);
383        let body = to_cbor(request)?;
384        let (t, r) = oneshot::channel();
385        lock(&self.pending).insert(id, t);
386        let mut guard = CancelGuard { id, out: &self.out, pending: &self.pending, armed: true };
387        if self.out.send(Out::Call { id, body }).await.is_err() {
388            lock(&self.pending).remove(&id);
389            guard.armed = false;
390            return Err(ServiceError::Closed);
391        }
392        let answer = r.await;
393        guard.armed = false;
394        let bytes = answer.map_err(|_| ServiceError::Closed)??;
395        from_cbor(&bytes)
396    }
397
398    /// [`call`](Self::call) with a deadline; on timeout the call is cancelled on the server.
399    pub async fn call_timeout(&self, request: &Req, timeout: Duration) -> Result<Resp, ServiceError> {
400        tokio::time::timeout(timeout, self.call(request)).await.unwrap_or(Err(ServiceError::Timeout))
401    }
402
403    /// The stream has ended; every further call fails with `Closed`.
404    pub fn is_closed(&self) -> bool {
405        *self.closed.borrow()
406    }
407
408    /// Calls sent and not yet answered.
409    pub fn in_flight(&self) -> usize {
410        lock(&self.pending).len()
411    }
412}
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    use crate::{AllowAll, memory_pair};
418
419    #[derive(Debug, Clone, Serialize, Deserialize)]
420    enum Req {
421        Add(i64, i64),
422        Sleep(u64),
423        Secret,
424    }
425
426    struct Calc;
427
428    impl Service for Calc {
429        type Request = Req;
430        type Response = i64;
431
432        fn access(&self, r: &Req) -> Access {
433            match r {
434                Req::Secret => Access::new("secret"),
435                _ => Access::new("calc"),
436            }
437        }
438
439        async fn call(&self, _who: Admitted, r: Req) -> Result<i64, ServiceError> {
440            match r {
441                Req::Add(a, b) => Ok(a + b),
442                Req::Sleep(ms) => {
443                    tokio::time::sleep(Duration::from_millis(ms)).await;
444                    Ok(ms as i64)
445                }
446                Req::Secret => Ok(42),
447            }
448        }
449    }
450
451    fn no_secrets() -> Arc<dyn Authorize> {
452        Arc::new(|c: &Caller, a: &Access| if a.permission == "secret" { Err(ServiceError::refused("role")) } else { AllowAll.authorize(c, a) })
453    }
454
455    async fn pair(auth: Arc<dyn Authorize>, opts: SessionOptions) -> Session<Req, i64> {
456        let (client, server) = memory_pair(8);
457        tokio::spawn(async move { serve_session(Arc::new(Calc), auth, server, "peer-a".into(), &opts).await });
458        Session::start(client, Credentials::new()).await.unwrap()
459    }
460
461    #[tokio::test]
462    async fn calls_run_concurrently_and_answer_in_completion_order() {
463        let s = pair(no_secrets(), SessionOptions::default()).await;
464        let (slow, fast) = tokio::join!(s.call(&Req::Sleep(200)), async {
465            let v = s.call(&Req::Add(2, 3)).await;
466            (v, std::time::Instant::now())
467        });
468        assert_eq!((slow.unwrap(), fast.0.unwrap()), (200, 5));
469        assert_eq!(s.call(&Req::Secret).await, Err(ServiceError::refused("role")));
470        assert_eq!(s.call(&Req::Add(1, 1)).await.unwrap(), 2, "a refusal does not end the session");
471        assert_eq!(s.in_flight(), 0);
472    }
473
474    #[tokio::test]
475    async fn timeouts_cancel_and_the_session_carries_on() {
476        let s = pair(no_secrets(), SessionOptions::default().with_max_in_flight(1)).await;
477        assert_eq!(s.call_timeout(&Req::Sleep(5_000), Duration::from_millis(50)).await, Err(ServiceError::Timeout));
478        // With one slot, this only runs once the cancelled call is gone.
479        let started = std::time::Instant::now();
480        assert_eq!(s.call_timeout(&Req::Add(4, 4), Duration::from_secs(2)).await.unwrap(), 8);
481        assert!(started.elapsed() < Duration::from_secs(1));
482    }
483
484    #[tokio::test]
485    async fn a_full_queue_answers_busy() {
486        let s = pair(no_secrets(), SessionOptions::default().with_max_in_flight(1).with_max_queued(1)).await;
487        let (a, b, c) = tokio::join!(s.call(&Req::Sleep(150)), s.call(&Req::Sleep(150)), s.call(&Req::Sleep(150)));
488        let mut got = [a, b, c].map(|r| r.map_err(|e| e == ServiceError::Busy));
489        got.sort();
490        assert_eq!(got, [Ok(150), Ok(150), Err(true)]);
491    }
492
493    #[tokio::test]
494    async fn refused_sessions_and_bad_bodies() {
495        let (client, server) = memory_pair(8);
496        let deny: Arc<dyn Authorize> = Arc::new(|_: &Caller, _: &Access| Err(ServiceError::refused("unknown-device")));
497        tokio::spawn(async move { serve_session(Arc::new(Calc), deny, server, "p".into(), &SessionOptions::default()).await });
498        assert_eq!(Session::<Req, i64>::start(client, Credentials::new()).await.err(), Some(ServiceError::refused("unknown-device")));
499
500        // A body of the wrong type is a bad request for that call only.
501        let s: Session<String, i64> = {
502            let (client, server) = memory_pair(8);
503            tokio::spawn(async move { serve_session(Arc::new(Calc), Arc::new(AllowAll), server, "p".into(), &SessionOptions::default()).await });
504            Session::start(client, Credentials::new()).await.unwrap()
505        };
506        assert!(matches!(s.call(&"nonsense".to_string()).await, Err(ServiceError::BadRequest { .. })));
507        assert!(!s.is_closed());
508    }
509
510    #[tokio::test]
511    async fn a_silent_client_times_out_and_a_closed_server_fails_calls() {
512        let (_client, server) = memory_pair(8);
513        let opts = SessionOptions::default().with_hello_timeout(Duration::from_millis(50));
514        assert_eq!(serve_session(Arc::new(Calc), Arc::new(AllowAll), server, "p".into(), &opts).await, Err(ServiceError::Timeout));
515
516        let (client, mut server) = memory_pair(8);
517        let srv = tokio::spawn(async move {
518            let _hello = server.recv_cbor::<ClientFrame>().await;
519            server.send_cbor(&ServerFrame::Welcome { wire: WIRE }).await.unwrap();
520            let _call = server.recv_cbor::<ClientFrame>().await;
521            drop(server);
522        });
523        let s = Session::<Req, i64>::start(client, Credentials::new()).await.unwrap();
524        assert_eq!(s.call(&Req::Add(1, 2)).await, Err(ServiceError::Closed));
525        srv.await.unwrap();
526        assert!(s.is_closed());
527    }
528}