Skip to main content

rpc/
mux.rs

1//! One connection, several nomiscript streams (ADR-0036).
2//!
3//! A stream is an unchanged [`Session`] with its own worker and a bounded queue.
4//! One eval runs at a time across the connection's streams.
5//!
6//! Replies go through a bounded channel that [`Mux::new`] hands back. A worker
7//! waits while it is full. [`Mux::frame`] never waits: it returns a refusal as
8//! data, so the caller decides where it goes. A reader that must not outrun the
9//! streams calls [`Mux::ready`] first.
10
11use std::sync::Arc;
12
13use tokio::runtime::Handle;
14use tokio::sync::{Semaphore, mpsc, watch};
15
16use crate::ctx::{EpochBumper, InterruptHandle, ScriptCtx};
17use crate::envelope::{EnvelopeError, Frame, RequestId, read_frame};
18use crate::framing::FrameError;
19use crate::session::failure::{EvalFailure, rejected};
20use crate::session::{Session, SessionError};
21
22mod worker;
23
24use worker::{Job, work};
25
26/// Streams per connection, stream 0 included.
27pub const MAX_STREAMS: usize = 8;
28/// Requests a stream queues before it answers `busy`.
29pub const QUEUE_CAPACITY: usize = 32;
30/// Replies held for the consumer: one per stream, so no worker waits for room
31/// while its stream has an unsent reply. Refusals the reader writes share the slots.
32const REPLY_CAPACITY: usize = MAX_STREAMS;
33
34/// `Session::new` or `Session::guarded`.
35pub type OpenSession = fn(ScriptCtx) -> Result<Session, SessionError>;
36
37struct Stream {
38    queue: mpsc::Sender<Job>,
39    bumper: EpochBumper,
40    interrupt: InterruptHandle,
41    closed: watch::Sender<bool>,
42}
43
44impl Stream {
45    fn abort(&self) {
46        self.interrupt.interrupt();
47        self.bumper.bump();
48    }
49}
50
51/// Aborts every stream of its [`Mux`], whether or not the `Mux` is still alive:
52/// what runs is dropped at its next yield and what is queued is answered
53/// `interrupted`. For a client that is gone.
54#[derive(Clone)]
55pub struct AbortHandle(Arc<watch::Sender<bool>>);
56
57impl AbortHandle {
58    pub fn abort(&self) {
59        self.0.send_replace(true);
60    }
61}
62
63pub struct Mux {
64    ctx: ScriptCtx,
65    open: OpenSession,
66    handle: Handle,
67    replies: mpsc::Sender<String>,
68    permits: Arc<Semaphore>,
69    streams: Vec<(u32, Stream)>,
70    aborted: AbortHandle,
71}
72
73impl Mux {
74    /// Opens stream 0. Every reply, from every stream, goes to the returned
75    /// receiver; it ends once the `Mux` and the last worker are gone.
76    ///
77    /// # Errors
78    /// Stream 0 could not be built.
79    pub fn new(
80        handle: &Handle,
81        ctx: ScriptCtx,
82        open: OpenSession,
83    ) -> Result<(Self, mpsc::Receiver<String>), SessionError> {
84        let (replies, receiver) = mpsc::channel(REPLY_CAPACITY);
85        let mut mux = Self {
86            ctx,
87            open,
88            handle: handle.clone(),
89            replies,
90            permits: Arc::new(Semaphore::new(1)),
91            streams: Vec::with_capacity(MAX_STREAMS),
92            aborted: AbortHandle(Arc::new(watch::channel(false).0)),
93        };
94        mux.open_stream(0)?;
95        Ok((mux, receiver))
96    }
97
98    /// Handles one frame and never waits. Every error is a reply: the refusal
99    /// to write, when the frame got one at once.
100    pub fn frame(&mut self, frame: &str) -> Option<String> {
101        match read_frame(frame) {
102            Ok(Frame::Request { id, stream, form }) => self.request(id, stream, form),
103            Ok(Frame::Interrupt(stream)) => {
104                self.interrupt(stream);
105                None
106            }
107            Ok(Frame::Close(stream)) => {
108                self.close(stream);
109                None
110            }
111            Err(err) => Some(rejected(0, EvalFailure::Envelope(err))),
112        }
113    }
114
115    /// Waits until the stream `frame` requests has room in its queue, so the
116    /// next [`Mux::frame`] queues it instead of answering `busy`. Returns at
117    /// once for control frames, unopened streams and unreadable heads.
118    pub async fn ready(&self, frame: &str) {
119        let Ok(Frame::Request { stream, .. }) = read_frame(frame) else {
120            return;
121        };
122        if let Some(index) = self.position(stream) {
123            self.streams[index].1.queue.reserve().await.ok();
124        }
125    }
126
127    /// A sender into the reply channel, for a reader that writes the refusals
128    /// [`Mux::frame`] returns.
129    #[must_use]
130    pub fn replies(&self) -> mpsc::Sender<String> {
131        self.replies.clone()
132    }
133
134    #[must_use]
135    pub fn abort_handle(&self) -> AbortHandle {
136        self.aborted.clone()
137    }
138
139    /// Aborts the request `stream` is running or about to start; ignored when unopened.
140    pub fn interrupt(&self, stream: u32) {
141        if let Some(index) = self.position(stream) {
142            self.streams[index].1.abort();
143        }
144    }
145
146    /// Removes `stream`; its worker answers what is still queued `interrupted`.
147    /// Stream 0 and unopened streams are ignored.
148    pub fn close(&mut self, stream: u32) {
149        let Some(index) = self.position(stream).filter(|_| stream != 0) else {
150            return;
151        };
152        let (_, closing) = self.streams.swap_remove(index);
153        closing.abort();
154        closing.closed.send_replace(true);
155    }
156
157    fn position(&self, stream: u32) -> Option<usize> {
158        self.streams.iter().position(|(n, _)| *n == stream)
159    }
160
161    fn request(&mut self, id: RequestId, stream: u32, form: &str) -> Option<String> {
162        let index = match self.position(stream) {
163            Some(index) => index,
164            None => match self.admit(stream, &id) {
165                Ok(index) => index,
166                Err(refusal) => return Some(refusal),
167            },
168        };
169        if self.streams[index].1.queue.is_closed() {
170            self.streams.swap_remove(index);
171            return Some(rejected(stream, EvalFailure::Interrupted(id)));
172        }
173        match self.streams[index].1.queue.try_reserve() {
174            Ok(slot) => {
175                slot.send(Job {
176                    id,
177                    form: form.to_owned(),
178                });
179                None
180            }
181            Err(_) => Some(rejected(stream, EvalFailure::Busy(id))),
182        }
183    }
184
185    /// Opens the stream a first request names, or answers that request itself.
186    fn admit(&mut self, stream: u32, id: &RequestId) -> Result<usize, String> {
187        if self.streams.len() >= MAX_STREAMS {
188            return Err(rejected(stream, EvalFailure::TooManyStreams(id.clone())));
189        }
190        let Err(err) = self.open_stream(stream) else {
191            return Ok(self.streams.len() - 1);
192        };
193        let failure = match err {
194            SessionError::Engine(err) => EvalFailure::Engine(id.clone(), err),
195            SessionError::Prelude(err) => EvalFailure::Eval(id.clone(), err),
196        };
197        Err(rejected(stream, failure))
198    }
199
200    fn open_stream(&mut self, number: u32) -> Result<(), SessionError> {
201        let session = (self.open)(self.ctx.clone())?;
202        let (queue, jobs) = mpsc::channel(QUEUE_CAPACITY);
203        let (closed, closed_rx) = watch::channel(false);
204        let stream = Stream {
205            queue,
206            bumper: session.epoch_bumper(),
207            interrupt: session.interrupt_handle(),
208            closed,
209        };
210        let lane = worker::Lane {
211            number,
212            jobs,
213            closed: closed_rx,
214            aborted: self.aborted.0.subscribe(),
215            replies: self.replies.clone(),
216            permits: Arc::clone(&self.permits),
217        };
218        self.handle.spawn(work(session, lane));
219        self.streams.push((number, stream));
220        Ok(())
221    }
222}
223
224/// The `parse` reply for input that could not be framed.
225#[must_use]
226pub fn reject_input(err: &FrameError) -> String {
227    let failure = EvalFailure::Envelope(EnvelopeError::Parse(err.to_string()));
228    rejected(0, failure)
229}
230
231#[cfg(test)]
232mod tests;