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

            
9
use rpc::mux::{AbortHandle, Mux, OpenSession};
10
use rpc::session::SessionError;
11
use rpc::{RequestId, ScriptCtx, parse_response};
12
use tokio::runtime::Handle;
13
use tokio::sync::mpsc;
14

            
15
/// Sends one frame without waiting; the refusal, when the frame got one at once.
16
type 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.
19
pub(crate) const UNAVAILABLE: &str = "console unavailable";
20

            
21
/// The stream of app requests; it always exists.
22
pub(crate) const MAIN_STREAM: u32 = 0;
23

            
24
/// A single drained item from the reply channel.
25
#[derive(Debug)]
26
pub 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`.
35
pub 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

            
51
impl ConsoleEval {
52
    /// Opens a `Mux` whose streams are built by `open` over `ctx`.
53
    ///
54
    /// # Errors
55
    /// Stream 0 could not be built.
56
39
    pub fn connect(
57
39
        handle: &Handle,
58
39
        ctx: ScriptCtx,
59
39
        open: OpenSession,
60
39
    ) -> Result<Self, SessionError> {
61
39
        let (mut mux, replies) = Mux::new(handle, ctx, open)?;
62
39
        let abort = Some(mux.abort_handle());
63
39
        Ok(Self::over(
64
168
            Box::new(move |frame| mux.frame(frame)),
65
39
            replies,
66
39
            abort,
67
        ))
68
39
    }
69

            
70
644
    fn over(frame: FrameFn, replies: mpsc::Receiver<String>, abort: Option<AbortHandle>) -> Self {
71
644
        Self {
72
644
            frame,
73
644
            replies,
74
644
            abort,
75
644
            next_id: 1,
76
644
            next_stream: 1,
77
644
            refused: Vec::new(),
78
644
        }
79
644
    }
80

            
81
    /// Takes the next stream number; `None` once the numbers ran out.
82
32
    pub fn open_stream(&mut self) -> Option<u32> {
83
32
        let stream = self.next_stream;
84
32
        self.next_stream = stream.checked_add(1)?;
85
32
        Some(stream)
86
32
    }
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
1363
    pub fn submit(&mut self, stream: u32, form: String) -> Option<i64> {
91
1363
        let id = self.next_id;
92
1363
        let next = id.checked_add(1)?;
93
1360
        let refusal = (self.frame)(&envelope(id, stream, &form));
94
1360
        self.next_id = next;
95
1360
        self.refused.extend(
96
1360
            refusal
97
1360
                .into_iter()
98
11
                .map(|wire| DrainItem::Routed { id, wire }),
99
        );
100
1360
        Some(id)
101
1363
    }
102

            
103
    /// Drains every ready response without blocking: the refusals first, then
104
    /// the replies, each classified by its `:id`.
105
792
    pub fn drain(&mut self) -> Vec<DrainItem> {
106
792
        let mut out = std::mem::take(&mut self.refused);
107
903
        while let Ok(wire) = self.replies.try_recv() {
108
111
            out.push(classify_response(wire));
109
        }
110
792
        out
111
792
    }
112

            
113
    /// Aborts what `stream` is running or about to start.
114
6
    pub fn interrupt(&mut self, stream: u32) {
115
6
        (self.frame)(&format!("(:interrupt {stream})"));
116
6
    }
117

            
118
    /// Closes `stream`; stream 0 is ignored.
119
3
    pub fn close(&mut self, stream: u32) {
120
3
        (self.frame)(&format!("(:close {stream})"));
121
3
    }
122
}
123

            
124
impl Drop for ConsoleEval {
125
644
    fn drop(&mut self) {
126
644
        if let Some(abort) = &self.abort {
127
39
            abort.abort();
128
605
        }
129
644
    }
130
}
131

            
132
1360
fn envelope(id: i64, stream: u32, form: &str) -> String {
133
1360
    match stream {
134
1324
        MAIN_STREAM => format!("(:id {id} :form {form})"),
135
36
        stream => format!("(:id {id} :stream {stream} :form {form})"),
136
    }
137
1360
}
138

            
139
/// Classifies a wire frame as routed or unroutable.
140
115
fn classify_response(wire: String) -> DrainItem {
141
115
    match parse_response(&wire) {
142
112
        Ok(response) => match response.id {
143
111
            RequestId::Int(n) if n > 0 => DrainItem::Routed { id: n, wire },
144
2
            _ => DrainItem::Unroutable(wire),
145
        },
146
3
        Err(_) => DrainItem::Unroutable(wire),
147
    }
148
115
}
149

            
150
#[cfg(test)]
151
pub(crate) mod double;
152
#[cfg(test)]
153
mod tests;