Skip to main content

tui/tabs/
nms_eval.rs

1//! Async eval bridge for the console windows.
2//!
3//! `ConsoleEval` owns one [`rpc::mux::Mux`] (through its frame function), its
4//! bounded reply receiver and the envelope id counter. The UI side is sync: `submit`
5//! never waits, `drain` is a `try_recv` loop, so the 200 ms `run_loop` never
6//! awaits eval. App requests ride stream `MAIN_STREAM`; each console window
7//! takes its own stream from [`ConsoleEval::open_stream`].
8
9use rpc::mux::{AbortHandle, Mux, OpenSession};
10use rpc::session::SessionError;
11use rpc::{RequestId, ScriptCtx, parse_response};
12use tokio::runtime::Handle;
13use tokio::sync::mpsc;
14
15/// Sends one frame without waiting; the refusal, when the frame got one at once.
16type FrameFn = Box<dyn FnMut(&str) -> Option<String> + Send>;
17
18/// Shown when a request cannot be sent: no console attached, or its ids ran out.
19pub(crate) const UNAVAILABLE: &str = "console unavailable";
20
21/// The stream of app requests; it always exists.
22pub(crate) const MAIN_STREAM: u32 = 0;
23
24/// A single drained item from the reply channel.
25#[derive(Debug)]
26pub enum DrainItem {
27    /// A response whose `:id` is a positive integer; route by that id.
28    Routed { id: i64, wire: String },
29    /// A response without a usable head (`:id 0`, a non-integer id or no
30    /// response at all); it belongs to no pending request.
31    Unroutable(String),
32}
33
34/// Async bridge between the sync TUI and an `rpc::mux::Mux`.
35pub struct ConsoleEval {
36    frame: FrameFn,
37    replies: mpsc::Receiver<String>,
38    /// Aborts every eval when the console goes away, so none outlives it.
39    abort: Option<AbortHandle>,
40    /// The wire `:id` of the next submission. Starts at 1 and only increments
41    /// via `checked_add`, so it never reaches 0 (an unreadable head) or a
42    /// negative value; the id space is refused once exhausted.
43    next_id: i64,
44    /// The number of the next console stream: connection-wide, never reused.
45    next_stream: u32,
46    /// Refusals the `Mux` answered at once, routed by the id of the submission
47    /// they refused.
48    refused: Vec<DrainItem>,
49}
50
51impl ConsoleEval {
52    /// Opens a `Mux` whose streams are built by `open` over `ctx`.
53    ///
54    /// # Errors
55    /// Stream 0 could not be built.
56    pub fn connect(
57        handle: &Handle,
58        ctx: ScriptCtx,
59        open: OpenSession,
60    ) -> Result<Self, SessionError> {
61        let (mut mux, replies) = Mux::new(handle, ctx, open)?;
62        let abort = Some(mux.abort_handle());
63        Ok(Self::over(
64            Box::new(move |frame| mux.frame(frame)),
65            replies,
66            abort,
67        ))
68    }
69
70    fn over(frame: FrameFn, replies: mpsc::Receiver<String>, abort: Option<AbortHandle>) -> Self {
71        Self {
72            frame,
73            replies,
74            abort,
75            next_id: 1,
76            next_stream: 1,
77            refused: Vec::new(),
78        }
79    }
80
81    /// Takes the next stream number; `None` once the numbers ran out.
82    pub fn open_stream(&mut self) -> Option<u32> {
83        let stream = self.next_stream;
84        self.next_stream = stream.checked_add(1)?;
85        Some(stream)
86    }
87
88    /// Wraps `form` in a fresh envelope for `stream` and hands it to the `Mux`.
89    /// Never waits. Returns the envelope id, or `None` once the ids ran out.
90    pub fn submit(&mut self, stream: u32, form: String) -> Option<i64> {
91        let id = self.next_id;
92        let next = id.checked_add(1)?;
93        let refusal = (self.frame)(&envelope(id, stream, &form));
94        self.next_id = next;
95        self.refused.extend(
96            refusal
97                .into_iter()
98                .map(|wire| DrainItem::Routed { id, wire }),
99        );
100        Some(id)
101    }
102
103    /// Drains every ready response without blocking: the refusals first, then
104    /// the replies, each classified by its `:id`.
105    pub fn drain(&mut self) -> Vec<DrainItem> {
106        let mut out = std::mem::take(&mut self.refused);
107        while let Ok(wire) = self.replies.try_recv() {
108            out.push(classify_response(wire));
109        }
110        out
111    }
112
113    /// Aborts what `stream` is running or about to start.
114    pub fn interrupt(&mut self, stream: u32) {
115        (self.frame)(&format!("(:interrupt {stream})"));
116    }
117
118    /// Closes `stream`; stream 0 is ignored.
119    pub fn close(&mut self, stream: u32) {
120        (self.frame)(&format!("(:close {stream})"));
121    }
122}
123
124impl Drop for ConsoleEval {
125    fn drop(&mut self) {
126        if let Some(abort) = &self.abort {
127            abort.abort();
128        }
129    }
130}
131
132fn envelope(id: i64, stream: u32, form: &str) -> String {
133    match stream {
134        MAIN_STREAM => format!("(:id {id} :form {form})"),
135        stream => format!("(:id {id} :stream {stream} :form {form})"),
136    }
137}
138
139/// Classifies a wire frame as routed or unroutable.
140fn classify_response(wire: String) -> DrainItem {
141    match parse_response(&wire) {
142        Ok(response) => match response.id {
143            RequestId::Int(n) if n > 0 => DrainItem::Routed { id: n, wire },
144            _ => DrainItem::Unroutable(wire),
145        },
146        Err(_) => DrainItem::Unroutable(wire),
147    }
148}
149
150#[cfg(test)]
151pub(crate) mod double;
152#[cfg(test)]
153mod tests;