Lines
100 %
Functions
83.33 %
Branches
//! Async eval bridge for the console windows.
//!
//! `ConsoleEval` owns one [`rpc::mux::Mux`] (through its frame function), its
//! bounded reply receiver and the envelope id counter. The UI side is sync: `submit`
//! never waits, `drain` is a `try_recv` loop, so the 200 ms `run_loop` never
//! awaits eval. App requests ride stream `MAIN_STREAM`; each console window
//! takes its own stream from [`ConsoleEval::open_stream`].
use rpc::mux::{AbortHandle, Mux, OpenSession};
use rpc::session::SessionError;
use rpc::{RequestId, ScriptCtx, parse_response};
use tokio::runtime::Handle;
use tokio::sync::mpsc;
/// Sends one frame without waiting; the refusal, when the frame got one at once.
type FrameFn = Box<dyn FnMut(&str) -> Option<String> + Send>;
/// Shown when a request cannot be sent: no console attached, or its ids ran out.
pub(crate) const UNAVAILABLE: &str = "console unavailable";
/// The stream of app requests; it always exists.
pub(crate) const MAIN_STREAM: u32 = 0;
/// A single drained item from the reply channel.
#[derive(Debug)]
pub enum DrainItem {
/// A response whose `:id` is a positive integer; route by that id.
Routed { id: i64, wire: String },
/// A response without a usable head (`:id 0`, a non-integer id or no
/// response at all); it belongs to no pending request.
Unroutable(String),
}
/// Async bridge between the sync TUI and an `rpc::mux::Mux`.
pub struct ConsoleEval {
frame: FrameFn,
replies: mpsc::Receiver<String>,
/// Aborts every eval when the console goes away, so none outlives it.
abort: Option<AbortHandle>,
/// The wire `:id` of the next submission. Starts at 1 and only increments
/// via `checked_add`, so it never reaches 0 (an unreadable head) or a
/// negative value; the id space is refused once exhausted.
next_id: i64,
/// The number of the next console stream: connection-wide, never reused.
next_stream: u32,
/// Refusals the `Mux` answered at once, routed by the id of the submission
/// they refused.
refused: Vec<DrainItem>,
impl ConsoleEval {
/// Opens a `Mux` whose streams are built by `open` over `ctx`.
///
/// # Errors
/// Stream 0 could not be built.
pub fn connect(
handle: &Handle,
ctx: ScriptCtx,
open: OpenSession,
) -> Result<Self, SessionError> {
let (mut mux, replies) = Mux::new(handle, ctx, open)?;
let abort = Some(mux.abort_handle());
Ok(Self::over(
Box::new(move |frame| mux.frame(frame)),
replies,
abort,
))
fn over(frame: FrameFn, replies: mpsc::Receiver<String>, abort: Option<AbortHandle>) -> Self {
Self {
frame,
next_id: 1,
next_stream: 1,
refused: Vec::new(),
/// Takes the next stream number; `None` once the numbers ran out.
pub fn open_stream(&mut self) -> Option<u32> {
let stream = self.next_stream;
self.next_stream = stream.checked_add(1)?;
Some(stream)
/// Wraps `form` in a fresh envelope for `stream` and hands it to the `Mux`.
/// Never waits. Returns the envelope id, or `None` once the ids ran out.
pub fn submit(&mut self, stream: u32, form: String) -> Option<i64> {
let id = self.next_id;
let next = id.checked_add(1)?;
let refusal = (self.frame)(&envelope(id, stream, &form));
self.next_id = next;
self.refused.extend(
refusal
.into_iter()
.map(|wire| DrainItem::Routed { id, wire }),
);
Some(id)
/// Drains every ready response without blocking: the refusals first, then
/// the replies, each classified by its `:id`.
pub fn drain(&mut self) -> Vec<DrainItem> {
let mut out = std::mem::take(&mut self.refused);
while let Ok(wire) = self.replies.try_recv() {
out.push(classify_response(wire));
out
/// Aborts what `stream` is running or about to start.
pub fn interrupt(&mut self, stream: u32) {
(self.frame)(&format!("(:interrupt {stream})"));
/// Closes `stream`; stream 0 is ignored.
pub fn close(&mut self, stream: u32) {
(self.frame)(&format!("(:close {stream})"));
impl Drop for ConsoleEval {
fn drop(&mut self) {
if let Some(abort) = &self.abort {
abort.abort();
fn envelope(id: i64, stream: u32, form: &str) -> String {
match stream {
MAIN_STREAM => format!("(:id {id} :form {form})"),
stream => format!("(:id {id} :stream {stream} :form {form})"),
/// Classifies a wire frame as routed or unroutable.
fn classify_response(wire: String) -> DrainItem {
match parse_response(&wire) {
Ok(response) => match response.id {
RequestId::Int(n) if n > 0 => DrainItem::Routed { id: n, wire },
_ => DrainItem::Unroutable(wire),
},
Err(_) => DrainItem::Unroutable(wire),
#[cfg(test)]
pub(crate) mod double;
mod tests;