Skip to main content

taba/rpc/
sessions.rs

1//! Sessions, as a backend reaches them.
2
3use alloc::{borrow::ToOwned, collections::BTreeMap, string::String, sync::Arc};
4use core::{any::Any, panic::AssertUnwindSafe, pin::pin};
5use std::sync::{Mutex, MutexGuard};
6
7use futures_util::{FutureExt, Stream, StreamExt};
8use serde::{Deserialize, Serialize};
9use tokio::{
10    runtime::Handle,
11    sync::{
12        Semaphore,
13        mpsc::{self, Receiver, Sender},
14    },
15};
16use tokio_util::task::JoinMap;
17
18use super::{
19    Error, Router,
20    wire::{Batch, Frame, Kind, Message, Rejection, SafeInteger},
21};
22use crate::{Input, Output};
23
24/// A session's id.
25#[derive(
26    Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Output, Input,
27)]
28pub struct SessionId(SafeInteger);
29
30/// Sessions, each at an address, answered by one [`Router`].
31///
32/// A backend hands it each connect, send and poll, and decides when an address's sessions end.
33///
34/// Session ids count up to JavaScript's <code>2<sup>53</sup> - 1</code> (9 quadrillion). After
35/// that many connects, ids stop changing, and each new session replaces the last. At a million
36/// connects a second, that's about 285 years.
37#[derive(Debug)]
38pub struct Sessions {
39    inner: Mutex<Inner>,
40    router: Arc<Router>,
41    runtime: Handle,
42}
43
44impl Sessions {
45    /// Sessions whose handlers run on `runtime`.
46    pub fn new(router: Router, runtime: Handle) -> Self {
47        Self { inner: Mutex::default(), router: Arc::new(router), runtime }
48    }
49
50    /// Starts a session at `address`.
51    pub fn connect(&self, address: impl Into<String>) -> SessionId {
52        let address = address.into();
53        self.lock().connect(address)
54    }
55
56    /// Applies a batch of messages, in the order sent.
57    ///
58    /// # Errors
59    ///
60    /// The session has ended, or `body` is malformed for send.
61    pub fn send(&self, address: &str, body: &[u8]) -> Result<(), Error> {
62        let Batch(id, messages) = serde_json::from_slice(body).map_err(Error::malformed)?;
63        let mut inner = self.lock();
64        let session = inner.get(address, id)?;
65        session.reap();
66        for message in messages {
67            session.apply(&self.router, &self.runtime, message);
68        }
69        Ok(())
70    }
71
72    /// The session's next frame, once there is one.
73    ///
74    /// # Errors
75    ///
76    /// The session has ended, or `body` isn't a poll.
77    pub fn poll(
78        &self,
79        address: &str,
80        body: &[u8],
81    ) -> impl Future<Output = Result<Frame, Error>> + Send + use<> {
82        let poll = serde_json::from_slice(body).map_err(Error::malformed).and_then(|id| {
83            let mut inner = self.lock();
84            let session = inner.get(address, id)?;
85            Ok(Arc::clone(&session.poll))
86        });
87
88        async move { poll?.lock().await.recv().await.ok_or_else(Error::ended) }
89    }
90
91    /// Ends every session at `address`, aborting their calls and subscriptions.
92    pub fn end(&self, address: &str) {
93        self.lock().end(address);
94    }
95
96    /// This lock is internal to taba, handlers run code in their own tasks.
97    fn lock(&self) -> MutexGuard<'_, Inner> {
98        self.inner.lock().unwrap()
99    }
100}
101
102/// Sessions by id.
103#[derive(Debug, Default)]
104struct Inner {
105    by_id: BTreeMap<SessionId, Session>,
106
107    /// The id the next connect gets.
108    next: SafeInteger,
109}
110
111impl Inner {
112    /// Starts a session at `address`.
113    fn connect(&mut self, address: String) -> SessionId {
114        let id = SessionId(self.next);
115        self.next = self.next.saturating_next();
116        self.by_id.insert(id, Session::new(address));
117        id
118    }
119
120    /// The session `id` names at `address`, or [`Error::ended`].
121    ///
122    /// This prevents a request from being able to look at other sessions.
123    fn get(&mut self, address: &str, id: SessionId) -> Result<&mut Session, Error> {
124        let session = self.by_id.get_mut(&id).filter(|session| session.address == address);
125        session.ok_or_else(Error::ended)
126    }
127
128    fn end(&mut self, address: &str) {
129        self.by_id.retain(|_, session| session.address != address);
130    }
131}
132
133/// What one session owns.
134///
135/// Its own mailbox gives an old session's frames no route to a new one.
136#[derive(Debug)]
137struct Session {
138    /// The only address whose requests reach it.
139    address: String,
140
141    /// Tasks post frames to it, and a poll takes them from `poll`.
142    mailbox: Mailbox,
143
144    /// How many `next`s each running strand hasn't answered yet.
145    nexts: BTreeMap<SafeInteger, Arc<Semaphore>>,
146
147    /// Held across a poll's wait, so a second poll waits its turn.
148    poll: Arc<tokio::sync::Mutex<Receiver<Frame>>>,
149
150    /// Dropping it aborts every call and subscription still running.
151    tasks: JoinMap<SafeInteger, ()>,
152}
153
154impl Session {
155    /// A session at `address`.
156    ///
157    /// Its mailbox holds one frame, so a task posting waits until a poll takes the last one.
158    fn new(address: String) -> Self {
159        let (mailbox, poll) = mpsc::channel(1);
160        let mailbox = Mailbox(mailbox);
161        let poll = Arc::new(tokio::sync::Mutex::new(poll));
162        Self { address, mailbox, poll, tasks: JoinMap::new(), nexts: BTreeMap::new() }
163    }
164
165    /// Forgets each finished task and its `next`s.
166    fn reap(&mut self) {
167        while let Some((id, _)) = self.tasks.try_join_next() {
168            self.nexts.remove(&id);
169        }
170    }
171
172    /// Starts, pulls or cancels one request.
173    fn apply(&mut self, router: &Arc<Router>, runtime: &Handle, message: Message) {
174        match message {
175            Message::Call(id, name, request) => {
176                let router = Arc::clone(router);
177                let mailbox = self.mailbox.clone();
178                let task = mailbox.clone().guarded(id, async move {
179                    mailbox.post(id, router.call(&name, &request).await).await;
180                });
181                self.tasks.spawn_on(id, task, runtime);
182            }
183            Message::Subscribe(id, name, request) => {
184                let router = Arc::clone(router);
185
186                // handler lazily starts at first `next`
187                let frames = async move { router.subscribe(&name, &request) }.flatten_stream();
188
189                let nexts = Arc::new(Semaphore::new(0));
190                let mailbox = self.mailbox.clone();
191                let delivered = mailbox.clone().deliver(id, frames, Arc::clone(&nexts));
192                let task = mailbox.guarded(id, delivered);
193                self.tasks.spawn_on(id, task, runtime);
194                self.nexts.insert(id, nexts);
195            }
196            Message::Next(id) => {
197                if let Some(nexts) = self.nexts.get(&id) {
198                    nexts.add_permits(1);
199                }
200            }
201            Message::Cancel(id) => {
202                self.tasks.abort(&id);
203                self.nexts.remove(&id);
204            }
205        }
206    }
207}
208
209/// Where a session's tasks post their frames.
210#[derive(Clone, Debug)]
211struct Mailbox(Sender<Frame>);
212
213impl Mailbox {
214    /// Waits for room, then posts `kind` under the request `id`.
215    async fn post(&self, id: SafeInteger, kind: Kind) {
216        // send fails only once the session ends and drops the receiver
217        let _ = self.0.send(Frame { id, kind }).await;
218    }
219
220    /// Answers each `next` with one frame, until the strand's first frame that isn't a value.
221    async fn deliver(
222        self,
223        id: SafeInteger,
224        frames: impl Stream<Item = Kind>,
225        nexts: Arc<Semaphore>,
226    ) {
227        let mut frames = pin!(frames);
228        while let Ok(owed) = nexts.acquire().await {
229            owed.forget();
230            let kind = frames.next().await.unwrap_or(Kind::End);
231            let is_last = !matches!(kind, Kind::Value(_));
232            self.post(id, kind).await;
233            if is_last {
234                return;
235            }
236        }
237    }
238
239    /// Runs request `id`'s task, rejecting the request if the app's code panics.
240    async fn guarded(self, id: SafeInteger, task: impl Future<Output = ()>) {
241        if let Err(payload) = AssertUnwindSafe(task).catch_unwind().await {
242            let message = panic_message(&*payload).to_owned();
243            self.post(id, Kind::Reject(Rejection::Panic(message))).await;
244        }
245    }
246}
247
248/// Taken from `std::panicking::payload_as_str`.
249fn panic_message(payload: &(dyn Any + Send)) -> &str {
250    if let Some(message) = payload.downcast_ref::<&str>() {
251        message
252    } else if let Some(message) = payload.downcast_ref::<String>() {
253        message
254    } else {
255        "Box<dyn Any>"
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use alloc::string::{String, ToString};
262    use core::{future::ready, time::Duration};
263
264    use futures_util::stream::{self, Empty};
265    use serde_json::{Value, json};
266    use tokio::{
267        runtime::{Builder, Runtime},
268        time::timeout,
269    };
270
271    use super::{SessionId, Sessions};
272    use crate::{
273        Never, Procedures,
274        rpc::{
275            Error, Router,
276            tests::{Buy, Ore},
277        },
278    };
279
280    /// A test backend over [`Sessions`], on a runtime the test drives.
281    struct Backend {
282        runtime: Runtime,
283        sessions: Sessions,
284    }
285
286    impl Backend {
287        fn new(router: Router) -> Self {
288            let runtime =
289                Builder::new_current_thread().enable_time().start_paused(true).build().unwrap();
290            let sessions = Sessions::new(router, runtime.handle().clone());
291            Self { runtime, sessions }
292        }
293
294        /// Sends `batch` as `id`'s session at `address`.
295        fn send(&self, address: &str, id: SessionId, batch: Value) -> Result<(), Error> {
296            self.sessions.send(address, &serde_json::to_vec(&json!([id, batch])).unwrap())
297        }
298
299        /// The next frame for `id`'s session at `address` as JSON, or why there's none.
300        ///
301        /// The runtime's clock is [paused](tokio::time::pause), so the timeout fires only when
302        /// no task can post a frame.
303        fn poll(&self, address: &str, id: SessionId) -> String {
304            let poll = self.sessions.poll(address, &serde_json::to_vec(&id).unwrap());
305            let poll = async { timeout(Duration::from_secs(1), poll).await };
306            match self.runtime.block_on(poll) {
307                Ok(Ok(frame)) => serde_json::to_string(&frame).unwrap(),
308                Ok(Err(error)) => error.to_string(),
309                Err(_) => "no frame is coming".to_string(),
310            }
311        }
312    }
313
314    #[test]
315    fn a_call_answers_under_its_id() {
316        let buy = |_: Buy| ready(Ok(3));
317        let builder = Router::builder([Procedures::new().declare::<Buy>()]);
318        let backend = Backend::new(builder.handle(buy).build().unwrap());
319        let id = backend.sessions.connect("main");
320        let call = json!([{ "kind": "call", "value": [42, "taba::rpc::tests::Buy", { "generator": "Drill" }] }]);
321        backend.send("main", id, call).unwrap();
322        insta::assert_snapshot!(backend.poll("main", id), @r#"{"id":42,"kind":"value","value":3}"#);
323    }
324
325    #[test]
326    fn a_strand_waits_for_each_next_until_it_ends() {
327        let ore = |_: Ore| stream::iter([Ok(3), Ok(6)]);
328        let buy = |_: Buy| ready(Ok(10));
329        let builder = Router::builder([Procedures::new().declare::<Ore>().declare::<Buy>()]);
330        let backend = Backend::new(builder.handle(ore).handle(buy).build().unwrap());
331        let id = backend.sessions.connect("main");
332        let batches = [
333            json!([
334                { "kind": "subscribe", "value": [0, "taba::rpc::tests::Ore", null] },
335                { "kind": "call", "value": [1, "taba::rpc::tests::Buy", { "generator": "Drill" }] },
336            ]),
337            json!([
338                { "kind": "next", "value": 0 },
339                { "kind": "call", "value": [2, "taba::rpc::tests::Buy", { "generator": "Drill" }] },
340            ]),
341            json!([]),
342            json!([{ "kind": "next", "value": 0 }]),
343            json!([{ "kind": "next", "value": 0 }]),
344        ];
345        let frames = batches.map(|batch| {
346            backend.send("main", id, batch).unwrap();
347            backend.poll("main", id)
348        });
349        insta::assert_snapshot!(frames.join("\n"), @r#"
350        {"id":1,"kind":"value","value":10}
351        {"id":0,"kind":"value","value":3}
352        {"id":2,"kind":"value","value":10}
353        {"id":0,"kind":"value","value":6}
354        {"id":0,"kind":"end"}
355        "#);
356    }
357
358    #[test]
359    fn a_strand_answers_every_next() {
360        let ore = |_: Ore| stream::iter([Ok(3), Ok(6)]);
361        let buy = |_: Buy| ready(Ok(10));
362        let builder = Router::builder([Procedures::new().declare::<Ore>().declare::<Buy>()]);
363        let backend = Backend::new(builder.handle(ore).handle(buy).build().unwrap());
364        let id = backend.sessions.connect("main");
365        let batch = json!([
366            { "kind": "subscribe", "value": [0, "taba::rpc::tests::Ore", null] },
367            { "kind": "next", "value": 0 },
368            { "kind": "next", "value": 0 },
369            { "kind": "call", "value": [1, "taba::rpc::tests::Buy", { "generator": "Drill" }] },
370        ]);
371        backend.send("main", id, batch).unwrap();
372        let frames = [backend.poll("main", id), backend.poll("main", id)];
373        insta::assert_snapshot!(frames.join("\n"), @r#"
374        {"id":0,"kind":"value","value":3}
375        {"id":0,"kind":"value","value":6}
376        "#);
377    }
378
379    #[test]
380    fn a_strand_starts_at_its_first_next() {
381        let ore = |_: Ore| -> Empty<Result<u32, Never>> { panic!("the mine flooded") };
382        let buy = |_: Buy| ready(Ok(10));
383        let builder = Router::builder([Procedures::new().declare::<Ore>().declare::<Buy>()]);
384        let backend = Backend::new(builder.handle(ore).handle(buy).build().unwrap());
385        let id = backend.sessions.connect("main");
386        let batches = [
387            json!([
388                { "kind": "subscribe", "value": [0, "taba::rpc::tests::Ore", null] },
389                { "kind": "call", "value": [1, "taba::rpc::tests::Buy", { "generator": "Drill" }] },
390            ]),
391            json!([{ "kind": "next", "value": 0 }]),
392        ];
393        let frames = batches.map(|batch| {
394            backend.send("main", id, batch).unwrap();
395            backend.poll("main", id)
396        });
397        insta::assert_snapshot!(frames.join("\n"), @r#"
398        {"id":1,"kind":"value","value":10}
399        {"id":0,"kind":"reject","value":{"kind":"panic","value":"the mine flooded"}}
400        "#);
401    }
402
403    #[test]
404    fn a_cancel_stops_its_strand() {
405        let ore = |_: Ore| stream::iter([Ok(3), Ok(6)]);
406        let buy = |_: Buy| ready(Ok(10));
407        let builder = Router::builder([Procedures::new().declare::<Ore>().declare::<Buy>()]);
408        let backend = Backend::new(builder.handle(ore).handle(buy).build().unwrap());
409        let id = backend.sessions.connect("main");
410        let batch = json!([
411            { "kind": "subscribe", "value": [0, "taba::rpc::tests::Ore", null] },
412            { "kind": "cancel", "value": 0 },
413            { "kind": "next", "value": 0 },
414            { "kind": "call", "value": [1, "taba::rpc::tests::Buy", { "generator": "Drill" }] },
415        ]);
416        backend.send("main", id, batch).unwrap();
417        insta::assert_snapshot!(backend.poll("main", id), @r#"{"id":1,"kind":"value","value":10}"#);
418    }
419
420    #[test]
421    fn a_panic_rejects_only_its_request() {
422        let depth = 3;
423        let ore = move |_: Ore| -> Empty<Result<u32, Never>> {
424            panic!("the mine flooded at depth {depth}")
425        };
426        let buy = |_: Buy| ready(Ok(10));
427        let builder = Router::builder([Procedures::new().declare::<Ore>().declare::<Buy>()]);
428        let backend = Backend::new(builder.handle(ore).handle(buy).build().unwrap());
429        let id = backend.sessions.connect("main");
430        let batches = [
431            json!([
432                { "kind": "subscribe", "value": [0, "taba::rpc::tests::Ore", null] },
433                { "kind": "next", "value": 0 },
434            ]),
435            json!([{ "kind": "call", "value": [1, "taba::rpc::tests::Buy", { "generator": "Drill" }] }]),
436        ];
437        let frames = batches.map(|batch| {
438            backend.send("main", id, batch).unwrap();
439            backend.poll("main", id)
440        });
441        insta::assert_snapshot!(frames.join("\n"), @r#"
442        {"id":0,"kind":"reject","value":{"kind":"panic","value":"the mine flooded at depth 3"}}
443        {"id":1,"kind":"value","value":10}
444        "#);
445    }
446
447    #[test]
448    fn an_ended_session_refuses_its_requests() {
449        let backend = Backend::new(Router::builder([]).build().unwrap());
450        let old = backend.sessions.connect("main");
451        let held = backend.sessions.poll("main", &serde_json::to_vec(&old).unwrap());
452        backend.sessions.end("main");
453        backend.sessions.connect("main");
454        let refused = [
455            backend.send("main", old, json!([])).unwrap_err().to_string(),
456            backend.runtime.block_on(held).unwrap_err().to_string(),
457            backend.poll("main", old),
458        ];
459        insta::assert_snapshot!(refused.join("\n"), @"
460        this session has ended
461        this session has ended
462        this session has ended
463        ");
464    }
465
466    #[test]
467    fn a_session_answers_only_its_address() {
468        let buy = |_: Buy| ready(Ok(10));
469        let builder = Router::builder([Procedures::new().declare::<Buy>()]);
470        let backend = Backend::new(builder.handle(buy).build().unwrap());
471        let id = backend.sessions.connect("main");
472        let call = json!([{ "kind": "call", "value": [0, "taba::rpc::tests::Buy", { "generator": "Drill" }] }]);
473        let elsewhere = backend.send("other", id, call.clone()).unwrap_err().to_string();
474        backend.send("main", id, call).unwrap();
475        let answered = backend.poll("main", id);
476        insta::assert_snapshot!([elsewhere, answered].join("\n"), @r#"
477        this session has ended
478        {"id":0,"kind":"value","value":10}
479        "#);
480    }
481
482    #[test]
483    fn a_malformed_body_says_why() {
484        let backend = Backend::new(Router::builder([]).build().unwrap());
485        let error = backend.sessions.send("main", br#"{"session":0,"batch":[]}"#).unwrap_err();
486        insta::assert_snapshot!(error, @"can't read what was sent: invalid type: map, expected tuple struct Batch at line 1 column 0");
487    }
488}