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

            
11
use std::sync::Arc;
12

            
13
use tokio::runtime::Handle;
14
use tokio::sync::{Semaphore, mpsc, watch};
15

            
16
use crate::ctx::{EpochBumper, InterruptHandle, ScriptCtx};
17
use crate::envelope::{EnvelopeError, Frame, RequestId, read_frame};
18
use crate::framing::FrameError;
19
use crate::session::failure::{EvalFailure, rejected};
20
use crate::session::{Session, SessionError};
21

            
22
mod worker;
23

            
24
use worker::{Job, work};
25

            
26
/// Streams per connection, stream 0 included.
27
pub const MAX_STREAMS: usize = 8;
28
/// Requests a stream queues before it answers `busy`.
29
pub 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.
32
const REPLY_CAPACITY: usize = MAX_STREAMS;
33

            
34
/// `Session::new` or `Session::guarded`.
35
pub type OpenSession = fn(ScriptCtx) -> Result<Session, SessionError>;
36

            
37
struct Stream {
38
    queue: mpsc::Sender<Job>,
39
    bumper: EpochBumper,
40
    interrupt: InterruptHandle,
41
    closed: watch::Sender<bool>,
42
}
43

            
44
impl Stream {
45
1610
    fn abort(&self) {
46
1610
        self.interrupt.interrupt();
47
1610
        self.bumper.bump();
48
1610
    }
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)]
55
pub struct AbortHandle(Arc<watch::Sender<bool>>);
56

            
57
impl AbortHandle {
58
4802
    pub fn abort(&self) {
59
4802
        self.0.send_replace(true);
60
4802
    }
61
}
62

            
63
pub 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

            
73
impl 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
9153
    pub fn new(
80
9153
        handle: &Handle,
81
9153
        ctx: ScriptCtx,
82
9153
        open: OpenSession,
83
9153
    ) -> Result<(Self, mpsc::Receiver<String>), SessionError> {
84
9153
        let (replies, receiver) = mpsc::channel(REPLY_CAPACITY);
85
9153
        let mut mux = Self {
86
9153
            ctx,
87
9153
            open,
88
9153
            handle: handle.clone(),
89
9153
            replies,
90
9153
            permits: Arc::new(Semaphore::new(1)),
91
9153
            streams: Vec::with_capacity(MAX_STREAMS),
92
9153
            aborted: AbortHandle(Arc::new(watch::channel(false).0)),
93
9153
        };
94
9153
        mux.open_stream(0)?;
95
9153
        Ok((mux, receiver))
96
9153
    }
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
3308087
    pub fn frame(&mut self, frame: &str) -> Option<String> {
101
3308087
        match read_frame(frame) {
102
3285827
            Ok(Frame::Request { id, stream, form }) => self.request(id, stream, form),
103
            Ok(Frame::Interrupt(stream)) => {
104
805
                self.interrupt(stream);
105
805
                None
106
            }
107
            Ok(Frame::Close(stream)) => {
108
328
                self.close(stream);
109
328
                None
110
            }
111
21127
            Err(err) => Some(rejected(0, EvalFailure::Envelope(err))),
112
        }
113
3308087
    }
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
3294245
    pub async fn ready(&self, frame: &str) {
119
20594
        let Ok(Frame::Request { stream, .. }) = read_frame(frame) else {
120
132
            return;
121
        };
122
20462
        if let Some(index) = self.position(stream) {
123
20459
            self.streams[index].1.queue.reserve().await.ok();
124
3
        }
125
20550
    }
126

            
127
    /// A sender into the reply channel, for a reader that writes the refusals
128
    /// [`Mux::frame`] returns.
129
    #[must_use]
130
4830
    pub fn replies(&self) -> mpsc::Sender<String> {
131
4830
        self.replies.clone()
132
4830
    }
133

            
134
    #[must_use]
135
9122
    pub fn abort_handle(&self) -> AbortHandle {
136
9122
        self.aborted.clone()
137
9122
    }
138

            
139
    /// Aborts the request `stream` is running or about to start; ignored when unopened.
140
1285
    pub fn interrupt(&self, stream: u32) {
141
1285
        if let Some(index) = self.position(stream) {
142
1284
            self.streams[index].1.abort();
143
1
        }
144
1285
    }
145

            
146
    /// Removes `stream`; its worker answers what is still queued `interrupted`.
147
    /// Stream 0 and unopened streams are ignored.
148
328
    pub fn close(&mut self, stream: u32) {
149
328
        let Some(index) = self.position(stream).filter(|_| stream != 0) else {
150
2
            return;
151
        };
152
326
        let (_, closing) = self.streams.swap_remove(index);
153
326
        closing.abort();
154
326
        closing.closed.send_replace(true);
155
328
    }
156

            
157
6560885
    fn position(&self, stream: u32) -> Option<usize> {
158
6571621
        self.streams.iter().position(|(n, _)| *n == stream)
159
6560885
    }
160

            
161
3285827
    fn request(&mut self, id: RequestId, stream: u32, form: &str) -> Option<String> {
162
3285827
        let index = match self.position(stream) {
163
3282416
            Some(index) => index,
164
3411
            None => match self.admit(stream, &id) {
165
3248
                Ok(index) => index,
166
163
                Err(refusal) => return Some(refusal),
167
            },
168
        };
169
3285664
        if self.streams[index].1.queue.is_closed() {
170
1
            self.streams.swap_remove(index);
171
1
            return Some(rejected(stream, EvalFailure::Interrupted(id)));
172
3285663
        }
173
3285663
        match self.streams[index].1.queue.try_reserve() {
174
            Ok(slot) => {
175
3284381
                slot.send(Job {
176
3284381
                    id,
177
3284381
                    form: form.to_owned(),
178
3284381
                });
179
3284381
                None
180
            }
181
1282
            Err(_) => Some(rejected(stream, EvalFailure::Busy(id))),
182
        }
183
3285827
    }
184

            
185
    /// Opens the stream a first request names, or answers that request itself.
186
3411
    fn admit(&mut self, stream: u32, id: &RequestId) -> Result<usize, String> {
187
3411
        if self.streams.len() >= MAX_STREAMS {
188
162
            return Err(rejected(stream, EvalFailure::TooManyStreams(id.clone())));
189
3249
        }
190
3249
        let Err(err) = self.open_stream(stream) else {
191
3248
            return Ok(self.streams.len() - 1);
192
        };
193
1
        let failure = match err {
194
            SessionError::Engine(err) => EvalFailure::Engine(id.clone(), err),
195
1
            SessionError::Prelude(err) => EvalFailure::Eval(id.clone(), err),
196
        };
197
1
        Err(rejected(stream, failure))
198
3411
    }
199

            
200
12402
    fn open_stream(&mut self, number: u32) -> Result<(), SessionError> {
201
12402
        let session = (self.open)(self.ctx.clone())?;
202
12401
        let (queue, jobs) = mpsc::channel(QUEUE_CAPACITY);
203
12401
        let (closed, closed_rx) = watch::channel(false);
204
12401
        let stream = Stream {
205
12401
            queue,
206
12401
            bumper: session.epoch_bumper(),
207
12401
            interrupt: session.interrupt_handle(),
208
12401
            closed,
209
12401
        };
210
12401
        let lane = worker::Lane {
211
12401
            number,
212
12401
            jobs,
213
12401
            closed: closed_rx,
214
12401
            aborted: self.aborted.0.subscribe(),
215
12401
            replies: self.replies.clone(),
216
12401
            permits: Arc::clone(&self.permits),
217
12401
        };
218
12401
        self.handle.spawn(work(session, lane));
219
12401
        self.streams.push((number, stream));
220
12401
        Ok(())
221
12402
    }
222
}
223

            
224
/// The `parse` reply for input that could not be framed.
225
#[must_use]
226
481
pub fn reject_input(err: &FrameError) -> String {
227
481
    let failure = EvalFailure::Envelope(EnvelopeError::Parse(err.to_string()));
228
481
    rejected(0, failure)
229
481
}
230

            
231
#[cfg(test)]
232
mod tests;