1use rpc::mux::{AbortHandle, Mux, OpenSession};
10use rpc::session::SessionError;
11use rpc::{RequestId, ScriptCtx, parse_response};
12use tokio::runtime::Handle;
13use tokio::sync::mpsc;
14
15type FrameFn = Box<dyn FnMut(&str) -> Option<String> + Send>;
17
18pub(crate) const UNAVAILABLE: &str = "console unavailable";
20
21pub(crate) const MAIN_STREAM: u32 = 0;
23
24#[derive(Debug)]
26pub enum DrainItem {
27 Routed { id: i64, wire: String },
29 Unroutable(String),
32}
33
34pub struct ConsoleEval {
36 frame: FrameFn,
37 replies: mpsc::Receiver<String>,
38 abort: Option<AbortHandle>,
40 next_id: i64,
44 next_stream: u32,
46 refused: Vec<DrainItem>,
49}
50
51impl ConsoleEval {
52 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 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 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 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 pub fn interrupt(&mut self, stream: u32) {
115 (self.frame)(&format!("(:interrupt {stream})"));
116 }
117
118 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
139fn 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;