Lines
99.15 %
Functions
97.14 %
Branches
100 %
//! One connection, several nomiscript streams (ADR-0036).
//!
//! A stream is an unchanged [`Session`] with its own worker and a bounded queue.
//! One eval runs at a time across the connection's streams.
//! Replies go through a bounded channel that [`Mux::new`] hands back. A worker
//! waits while it is full. [`Mux::frame`] never waits: it returns a refusal as
//! data, so the caller decides where it goes. A reader that must not outrun the
//! streams calls [`Mux::ready`] first.
use std::sync::Arc;
use tokio::runtime::Handle;
use tokio::sync::{Semaphore, mpsc, watch};
use crate::ctx::{EpochBumper, InterruptHandle, ScriptCtx};
use crate::envelope::{EnvelopeError, Frame, RequestId, read_frame};
use crate::framing::FrameError;
use crate::session::failure::{EvalFailure, rejected};
use crate::session::{Session, SessionError};
mod worker;
use worker::{Job, work};
/// Streams per connection, stream 0 included.
pub const MAX_STREAMS: usize = 8;
/// Requests a stream queues before it answers `busy`.
pub const QUEUE_CAPACITY: usize = 32;
/// Replies held for the consumer: one per stream, so no worker waits for room
/// while its stream has an unsent reply. Refusals the reader writes share the slots.
const REPLY_CAPACITY: usize = MAX_STREAMS;
/// `Session::new` or `Session::guarded`.
pub type OpenSession = fn(ScriptCtx) -> Result<Session, SessionError>;
struct Stream {
queue: mpsc::Sender<Job>,
bumper: EpochBumper,
interrupt: InterruptHandle,
closed: watch::Sender<bool>,
}
impl Stream {
fn abort(&self) {
self.interrupt.interrupt();
self.bumper.bump();
/// Aborts every stream of its [`Mux`], whether or not the `Mux` is still alive:
/// what runs is dropped at its next yield and what is queued is answered
/// `interrupted`. For a client that is gone.
#[derive(Clone)]
pub struct AbortHandle(Arc<watch::Sender<bool>>);
impl AbortHandle {
pub fn abort(&self) {
self.0.send_replace(true);
pub struct Mux {
ctx: ScriptCtx,
open: OpenSession,
handle: Handle,
replies: mpsc::Sender<String>,
permits: Arc<Semaphore>,
streams: Vec<(u32, Stream)>,
aborted: AbortHandle,
impl Mux {
/// Opens stream 0. Every reply, from every stream, goes to the returned
/// receiver; it ends once the `Mux` and the last worker are gone.
///
/// # Errors
/// Stream 0 could not be built.
pub fn new(
handle: &Handle,
) -> Result<(Self, mpsc::Receiver<String>), SessionError> {
let (replies, receiver) = mpsc::channel(REPLY_CAPACITY);
let mut mux = Self {
ctx,
open,
handle: handle.clone(),
replies,
permits: Arc::new(Semaphore::new(1)),
streams: Vec::with_capacity(MAX_STREAMS),
aborted: AbortHandle(Arc::new(watch::channel(false).0)),
};
mux.open_stream(0)?;
Ok((mux, receiver))
/// Handles one frame and never waits. Every error is a reply: the refusal
/// to write, when the frame got one at once.
pub fn frame(&mut self, frame: &str) -> Option<String> {
match read_frame(frame) {
Ok(Frame::Request { id, stream, form }) => self.request(id, stream, form),
Ok(Frame::Interrupt(stream)) => {
self.interrupt(stream);
None
Ok(Frame::Close(stream)) => {
self.close(stream);
Err(err) => Some(rejected(0, EvalFailure::Envelope(err))),
/// Waits until the stream `frame` requests has room in its queue, so the
/// next [`Mux::frame`] queues it instead of answering `busy`. Returns at
/// once for control frames, unopened streams and unreadable heads.
pub async fn ready(&self, frame: &str) {
let Ok(Frame::Request { stream, .. }) = read_frame(frame) else {
return;
if let Some(index) = self.position(stream) {
self.streams[index].1.queue.reserve().await.ok();
/// A sender into the reply channel, for a reader that writes the refusals
/// [`Mux::frame`] returns.
#[must_use]
pub fn replies(&self) -> mpsc::Sender<String> {
self.replies.clone()
pub fn abort_handle(&self) -> AbortHandle {
self.aborted.clone()
/// Aborts the request `stream` is running or about to start; ignored when unopened.
pub fn interrupt(&self, stream: u32) {
self.streams[index].1.abort();
/// Removes `stream`; its worker answers what is still queued `interrupted`.
/// Stream 0 and unopened streams are ignored.
pub fn close(&mut self, stream: u32) {
let Some(index) = self.position(stream).filter(|_| stream != 0) else {
let (_, closing) = self.streams.swap_remove(index);
closing.abort();
closing.closed.send_replace(true);
fn position(&self, stream: u32) -> Option<usize> {
self.streams.iter().position(|(n, _)| *n == stream)
fn request(&mut self, id: RequestId, stream: u32, form: &str) -> Option<String> {
let index = match self.position(stream) {
Some(index) => index,
None => match self.admit(stream, &id) {
Ok(index) => index,
Err(refusal) => return Some(refusal),
},
if self.streams[index].1.queue.is_closed() {
self.streams.swap_remove(index);
return Some(rejected(stream, EvalFailure::Interrupted(id)));
match self.streams[index].1.queue.try_reserve() {
Ok(slot) => {
slot.send(Job {
id,
form: form.to_owned(),
});
Err(_) => Some(rejected(stream, EvalFailure::Busy(id))),
/// Opens the stream a first request names, or answers that request itself.
fn admit(&mut self, stream: u32, id: &RequestId) -> Result<usize, String> {
if self.streams.len() >= MAX_STREAMS {
return Err(rejected(stream, EvalFailure::TooManyStreams(id.clone())));
let Err(err) = self.open_stream(stream) else {
return Ok(self.streams.len() - 1);
let failure = match err {
SessionError::Engine(err) => EvalFailure::Engine(id.clone(), err),
SessionError::Prelude(err) => EvalFailure::Eval(id.clone(), err),
Err(rejected(stream, failure))
fn open_stream(&mut self, number: u32) -> Result<(), SessionError> {
let session = (self.open)(self.ctx.clone())?;
let (queue, jobs) = mpsc::channel(QUEUE_CAPACITY);
let (closed, closed_rx) = watch::channel(false);
let stream = Stream {
queue,
bumper: session.epoch_bumper(),
interrupt: session.interrupt_handle(),
closed,
let lane = worker::Lane {
number,
jobs,
closed: closed_rx,
aborted: self.aborted.0.subscribe(),
replies: self.replies.clone(),
permits: Arc::clone(&self.permits),
self.handle.spawn(work(session, lane));
self.streams.push((number, stream));
Ok(())
/// The `parse` reply for input that could not be framed.
pub fn reject_input(err: &FrameError) -> String {
let failure = EvalFailure::Envelope(EnvelopeError::Parse(err.to_string()));
rejected(0, failure)
#[cfg(test)]
mod tests;