Skip to main content

hyprstream_tui/
shell_driver.rs

1//! Dedicated-thread async drivers for `!Send` language-shell interpreters (and,
2//! via [`NamespaceDriver`], for direct `Namespace` access that doesn't need an
3//! interpreter at all).
4//!
5//! The synchronous slash-command path (`ChatApp::handle_vfs_command`) needs to run
6//! async VFS futures to completion from a key-event handler that must not spin. A
7//! `Poll::Pending` on a VFS read that legitimately blocks on an external event
8//! (e.g. an `/exec/instances/<id>/exit` read awaiting a worker-completion signal)
9//! must park the caller, not hot-spin a core — which a noop-waker poll loop cannot
10//! do, because a noop waker never delivers the wake-up.
11//!
12//! ## The driver
13//!
14//! [`ShellOwner`] spawns one dedicated OS thread per shell. That thread runs a
15//! single-threaded `tokio::runtime::Runtime` (`Builder::new_current_thread()`)
16//! driving a `tokio::task::LocalSet`, the same pattern used by
17//! `hyprstream-workers::workflow::runner`'s per-job `TclShell` owner
18//! (`crates/hyprstream-workers/src/workflow/runner.rs`, `run_job`). Because the
19//! shell never leaves that thread, a `Pending` future registers a *real* waker
20//! tied to the runtime's reactor/timer/notify machinery — the executor parks the
21//! thread (zero CPU) until something actually wakes it, instead of spinning.
22//!
23//! `TclShell`'s `!Send` constraint (it wraps a molt `Interp`, which is `Rc`-based)
24//! is load-bearing here: the shell is constructed on, and never leaves, its owner
25//! thread — the whole point of a single-threaded `LocalSet` owner.
26//!
27//! ## The blocking `eval()` leg
28//!
29//! [`ShellOwner::eval`] round-trips a request to the owner thread and waits for the
30//! reply over a plain `std::sync::mpsc` channel — deliberately NOT
31//! `tokio::sync::oneshot::Receiver::blocking_recv()`, because `handle_input` runs
32//! in two different contexts depending on how the TUI is hosted:
33//!
34//!   - a bare OS thread with no tokio runtime at all (`spawn_app_process` /
35//!     `run_app_loop`, the TuiService-hosted path), and
36//!   - directly inside an active tokio runtime (the CLI shell's event loop in
37//!     `crates/hyprstream/src/cli/shell_handlers.rs`, which calls
38//!     `app.handle_input()` from within a `tokio::select!` arm).
39//!
40//! `tokio::sync::oneshot::Receiver::blocking_recv()` panics ("Cannot block the
41//! current thread from within a runtime") in the second context. `std::sync::mpsc`
42//! has no opinion about tokio and parks the calling OS thread via a condvar in
43//! both contexts, so it is safe everywhere `handle_vfs_command` is called from.
44//! This blocks the calling (input-handling) thread for the duration of one `eval`
45//! — a parked wait, not a spinning one. Making `handle_vfs_command` fully
46//! non-blocking would mean enqueue-and-poll against `ShellOwner` rather than
47//! waiting inline.
48
49use std::sync::mpsc as std_mpsc;
50
51// ─────────────────────────────────────────────────────────────────────────────
52// TclShell owner
53// ─────────────────────────────────────────────────────────────────────────────
54
55/// One ad-hoc `eval()` request sent to a [`ShellOwner`]'s dedicated thread.
56///
57/// The job runs `shell.eval(&script)` and sends the result back over `reply` —
58/// encapsulating the reply send keeps the channel a plain `FnOnce(&mut TclShell)`
59/// regardless of the job's result type.
60struct TclEvalJob {
61    script: String,
62    reply: std_mpsc::Sender<Result<String, String>>,
63}
64
65/// Dedicated-thread owner for a `TclShell`.
66///
67/// Spawns one OS thread that builds a current-thread tokio runtime + `LocalSet`,
68/// constructs the `TclShell` on that thread (preserving its `!Send` requirement),
69/// and services ad-hoc `eval()` calls (from slash-command routing) via
70/// [`Self::eval`], which blocks the *calling* thread (parked, not spinning) until
71/// the owner thread replies.
72///
73/// Dropping the `ShellOwner` drops `job_tx`, which ends the owner thread's job
74/// loop.
75pub struct ShellOwner {
76    job_tx: std_mpsc::Sender<TclEvalJob>,
77    _handle: std::thread::JoinHandle<()>,
78}
79
80impl ShellOwner {
81    /// Spawn the owner thread, constructing a `TclShell` from `subject`/`namespace`.
82    pub fn spawn(
83        subject: hyprstream_vfs::Subject,
84        namespace: std::sync::Arc<hyprstream_vfs::Namespace>,
85    ) -> Self {
86        let (job_tx, job_rx) = std_mpsc::channel::<TclEvalJob>();
87
88        #[allow(clippy::expect_used)] // thread spawn failure is unrecoverable here
89        let handle = std::thread::Builder::new()
90            .name("tcl-shell-owner".into())
91            .spawn(move || {
92                // Single-threaded runtime + LocalSet: the same pattern used by
93                // hyprstream-workers::workflow::runner's per-job TclShell owner
94                // (crates/hyprstream-workers/src/workflow/runner.rs, run_job).
95                // A Pending future here registers a real waker tied to this
96                // runtime's reactor — `.await` parks the thread; it does not spin.
97                #[allow(clippy::expect_used)] // runtime creation failure is unrecoverable
98                let rt = tokio::runtime::Builder::new_current_thread()
99                    .enable_all()
100                    .build()
101                    .expect("tcl-shell-owner runtime");
102                let local = tokio::task::LocalSet::new();
103
104                local.block_on(&rt, async move {
105                    let mut shell = hyprstream_workers_tcl::TclShell::new(subject, namespace);
106
107                    // Bridge the plain std::sync::mpsc job queue into this
108                    // LocalSet without ever blocking the runtime thread itself:
109                    // a tiny forwarder thread does the (parked, not spun)
110                    // std::sync::mpsc::Receiver::recv(), then hands jobs off
111                    // through a tokio channel this task can `.await` on.
112                    let (bridge_tx, mut bridge_rx) =
113                        tokio::sync::mpsc::unbounded_channel::<TclEvalJob>();
114                    std::thread::spawn(move || {
115                        while let Ok(job) = job_rx.recv() {
116                            if bridge_tx.send(job).is_err() {
117                                break;
118                            }
119                        }
120                    });
121
122                    // job_tx (held by ShellOwner) dropped — owner is torn down.
123                    while let Some(TclEvalJob { script, reply }) = bridge_rx.recv().await {
124                        let result = shell.eval(&script).await;
125                        let _ = reply.send(result);
126                    }
127                });
128            })
129            .expect("spawn tcl-shell-owner thread");
130
131        Self {
132            job_tx,
133            _handle: handle,
134        }
135    }
136
137    /// Evaluate a Tcl script on the owner thread and block (parked, not spun)
138    /// until the result is ready.
139    ///
140    /// Safe to call from any thread context, including from inside an active
141    /// tokio runtime — uses `std::sync::mpsc`, not `tokio::sync::oneshot`, for
142    /// the reply leg specifically so it never hits tokio's "cannot block the
143    /// current thread from within a runtime" panic (see module docs).
144    pub fn eval(&self, script: &str) -> Result<String, String> {
145        let (reply_tx, reply_rx) = std_mpsc::channel();
146        let sent = self.job_tx.send(TclEvalJob {
147            script: script.to_owned(),
148            reply: reply_tx,
149        });
150        if sent.is_err() {
151            return Err("tcl shell owner thread is gone".to_owned());
152        }
153        reply_rx
154            .recv()
155            .unwrap_or_else(|_| Err("tcl shell owner thread is gone".to_owned()))
156    }
157}
158
159// ─────────────────────────────────────────────────────────────────────────────
160// Direct Namespace driver (Tcl-independent VFS access for bare cat/ls routing)
161// ─────────────────────────────────────────────────────────────────────────────
162
163/// One direct `Namespace` request — `cat` or `ls` — dispatched without going
164/// through a `TclShell` at all.
165enum NsOp {
166    Cat(String),
167    Ls(String),
168}
169
170struct NsJob {
171    op: NsOp,
172    reply: std_mpsc::Sender<Result<String, String>>,
173}
174
175/// Dedicated-thread driver for direct `Namespace` access (`cat`/`ls`), with no
176/// Tcl interpreter involved at all.
177///
178/// This is what lets `ChatApp::handle_vfs_command` decouple simple path reads
179/// from `TclShell`: a bare path like `/srv/model/status` no longer needs an
180/// interpreter to exist, let alone to `eval("cat ...")` through one. Unlike
181/// [`ShellOwner`], `Namespace::cat`/`Namespace::ls` futures are plain `Send`
182/// (no `Rc`, no `!Send` constraint) — so this driver doesn't need a `LocalSet`,
183/// just a parked single-threaded runtime to give synchronous callers (which may
184/// or may not already be inside a tokio runtime — see module docs) a non-spinning
185/// way to wait on an async VFS call.
186pub struct NamespaceDriver {
187    job_tx: std_mpsc::Sender<NsJob>,
188    _handle: std::thread::JoinHandle<()>,
189}
190
191impl NamespaceDriver {
192    /// Spawn the driver thread bound to `namespace`/`subject`.
193    pub fn spawn(
194        subject: hyprstream_vfs::Subject,
195        namespace: std::sync::Arc<hyprstream_vfs::Namespace>,
196    ) -> Self {
197        let (job_tx, job_rx) = std_mpsc::channel::<NsJob>();
198
199        #[allow(clippy::expect_used)] // thread spawn failure is unrecoverable here
200        let handle = std::thread::Builder::new()
201            .name("vfs-namespace-driver".into())
202            .spawn(move || {
203                #[allow(clippy::expect_used)] // runtime creation failure is unrecoverable
204                let rt = tokio::runtime::Builder::new_current_thread()
205                    .enable_all()
206                    .build()
207                    .expect("vfs-namespace-driver runtime");
208
209                // job_rx.recv() blocks this dedicated OS thread (parked via
210                // condvar, not spun) between requests. Each request is then
211                // driven to completion with its own `rt.block_on(..)` — this
212                // thread has no other work, so there is nothing to interleave
213                // with and no benefit to keeping a task alive across requests.
214                while let Ok(NsJob { op, reply }) = job_rx.recv() {
215                    let result = rt.block_on(async {
216                        match op {
217                            NsOp::Cat(path) => namespace
218                                .cat(&path, &subject)
219                                .await
220                                .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
221                                .map_err(|e| e.to_string()),
222                            NsOp::Ls(path) => namespace
223                                .ls(&path, &subject)
224                                .await
225                                .map(|entries| {
226                                    entries
227                                        .iter()
228                                        .map(|e| {
229                                            if e.is_dir {
230                                                format!("{}/", e.name)
231                                            } else {
232                                                e.name.clone()
233                                            }
234                                        })
235                                        .collect::<Vec<_>>()
236                                        .join("\n")
237                                })
238                                .map_err(|e| e.to_string()),
239                        }
240                    });
241                    let _ = reply.send(result);
242                }
243            })
244            .expect("spawn vfs-namespace-driver thread");
245
246        Self {
247            job_tx,
248            _handle: handle,
249        }
250    }
251
252    /// Read a file's contents as a UTF-8 (lossy) string. Blocks the calling
253    /// thread (parked, not spun) until the result is ready; safe to call from
254    /// any thread context, including from inside an active tokio runtime.
255    pub fn cat(&self, path: &str) -> Result<String, String> {
256        self.request(NsOp::Cat(path.to_owned()))
257    }
258
259    /// List a directory's entries (directories suffixed with `/`), newline-joined.
260    pub fn ls(&self, path: &str) -> Result<String, String> {
261        self.request(NsOp::Ls(path.to_owned()))
262    }
263
264    fn request(&self, op: NsOp) -> Result<String, String> {
265        let (reply_tx, reply_rx) = std_mpsc::channel();
266        if self
267            .job_tx
268            .send(NsJob {
269                op,
270                reply: reply_tx,
271            })
272            .is_err()
273        {
274            return Err("vfs namespace driver thread is gone".to_owned());
275        }
276        reply_rx
277            .recv()
278            .unwrap_or_else(|_| Err("vfs namespace driver thread is gone".to_owned()))
279    }
280}