Skip to main content

hyprstream_workers_tcl/
mount.rs

1//! `/lang/tcl/` VFS mount — a **self-contained, stateful 9P file service**.
2//!
3//! [`TclMount::spawn`] owns its `!Send` molt interpreter + a dedicated driver
4//! thread internally; callers mount it and never touch its channels or state.
5//! The namespace is the only interface — a `/lang/tcl/eval` write is served by
6//! the mount's own driver. There is no external `rx` to drain, so adding a Tcl
7//! shell requires no edits to the dispatch/RPC/UI layer (epic #508, issue #634).
8//!
9//! Layout:
10//! - `/lang/tcl/eval`   — ctl file: write a Tcl script, read the result
11//! - `/lang/tcl/vars/`  — dynamic dir: list Tcl variables as readable files
12//! - `/lang/tcl/procs/` — dynamic dir: list defined procs as readable files
13//!
14//! Built on `hyprstream-vfs`'s `devfile` primitives (`ControlFile` for `eval`,
15//! `DynamicDir` for `vars`/`procs`) rather than hand-rolling the write→latch→
16//! read state machine — see `hyprstream_vfs::devfile` for the shared
17//! implementation (#609).
18
19use std::sync::Arc;
20
21use async_trait::async_trait;
22use hyprstream_vfs::devfile::{ControlFile, DevFileState, DevFuture, DynamicDir};
23use hyprstream_vfs::{DirEntry, Fid, Mount, MountError, Namespace, Stat, Subject};
24
25use crate::TclShell;
26
27// ─────────────────────────────────────────────────────────────────────────────
28// TclCommand — messages sent from mount threads to the interpreter owner
29// ─────────────────────────────────────────────────────────────────────────────
30
31/// A command sent from `TclMount` to the thread owning the Tcl interpreter.
32pub enum TclCommand {
33    /// Evaluate a Tcl script. Response: `Ok(result)` or `Err(error_msg)`.
34    Eval {
35        script: String,
36        resp: tokio::sync::oneshot::Sender<Result<String, String>>,
37    },
38    /// List all variable names in the current scope.
39    ListVars {
40        resp: tokio::sync::oneshot::Sender<Vec<String>>,
41    },
42    /// Get the value of a scalar variable.
43    GetVar {
44        name: String,
45        resp: tokio::sync::oneshot::Sender<Option<String>>,
46    },
47    /// List all user-defined procedure names.
48    ListProcs {
49        resp: tokio::sync::oneshot::Sender<Vec<String>>,
50    },
51    /// Get the body of a procedure.
52    GetProc {
53        name: String,
54        resp: tokio::sync::oneshot::Sender<Option<String>>,
55    },
56}
57
58// ─────────────────────────────────────────────────────────────────────────────
59// Fid types — internal state for each open file handle
60// ─────────────────────────────────────────────────────────────────────────────
61
62/// Which kind of file a fid refers to.
63#[derive(Clone, Debug)]
64enum TclFidKind {
65    /// The root directory `/lang/tcl/`.
66    Root,
67    /// The `eval` ctl file.
68    Eval,
69    /// The `vars/` directory.
70    VarsDir,
71    /// A specific variable: `vars/<name>`.
72    Var(String),
73    /// The `procs/` directory.
74    ProcsDir,
75    /// A specific procedure: `procs/<name>`.
76    Proc(String),
77}
78
79/// Fid state for the Tcl mount.
80struct TclFid {
81    kind: TclFidKind,
82    /// `eval` write→latch→read state (devfile::ControlFile). Unused for
83    /// other fid kinds, but cheap (an empty `Vec` behind a `Mutex`).
84    ctl_state: DevFileState,
85}
86
87// ─────────────────────────────────────────────────────────────────────────────
88// devfile callback type aliases
89// ─────────────────────────────────────────────────────────────────────────────
90
91type EvalCtl = ControlFile<
92    Box<dyn Fn(Vec<u8>) -> DevFuture<'static, Result<Vec<u8>, MountError>> + Send + Sync>,
93>;
94type ListFn = Box<dyn Fn() -> DevFuture<'static, Vec<String>> + Send + Sync>;
95type GetFn =
96    Box<dyn Fn(String) -> DevFuture<'static, Result<Option<Vec<u8>>, MountError>> + Send + Sync>;
97type VarsDir = DynamicDir<ListFn, GetFn>;
98type ProcsDir = DynamicDir<ListFn, GetFn>;
99
100// ─────────────────────────────────────────────────────────────────────────────
101// TclMount
102// ─────────────────────────────────────────────────────────────────────────────
103
104/// VFS mount that proxies `/lang/tcl` requests to a `!Send` Tcl interpreter
105/// owned by the mount itself.
106///
107/// Construct with [`TclMount::spawn`], which spins up a dedicated driver thread
108/// hosting the [`TclShell`] and drains the internal command channel. The driver
109/// exits cleanly when the mount is dropped (all command-channel senders live
110/// inside the mount, so the driver's `rx.recv()` returns `None` once they drop).
111/// Callers never hold the interpreter, the channel sender, or the receiver —
112/// the namespace is the only interface.
113pub struct TclMount {
114    eval: EvalCtl,
115    vars: VarsDir,
116    procs: ProcsDir,
117    /// Sender clone kept for the mount's lifetime. Declared LAST so it drops
118    /// after the devfile closures (`eval`/`vars`/`procs`), each of which also
119    /// holds a clone. When `TclMount` is dropped, every clone drops with it and
120    /// the driver's `rx.recv()` returns `None`, exiting the driver thread. The
121    /// field is `_`-prefixed because the struct never sends on it directly; it
122    /// exists to keep one clone alive for the lifetime of the mount.
123    _driver_tx: tokio::sync::mpsc::Sender<TclCommand>,
124}
125
126impl TclMount {
127    /// Spawn a self-contained `TclMount` whose driver thread owns a fresh
128    /// [`TclShell`] bound to `ns` under `subject`.
129    ///
130    /// The driver runs a `current_thread` tokio runtime + `LocalSet` (the molt
131    /// interpreter is `!Send` and its `eval` is async). Mount methods forward
132    /// each request over an internal channel and await the reply; the driver
133    /// pumps the [`TclShell`] between requests.
134    ///
135    /// `ns` is the namespace this mount will be mounted into — it lets
136    /// `/lang/tcl/eval` reuse the same `/bin/{cmd}` fallback resolution as an
137    /// inline `TclShell` (e.g. `cat /config/foo`).
138    #[allow(clippy::expect_used)] // Thread/runtime creation failure is unrecoverable
139    pub fn spawn(subject: Subject, ns: Arc<Namespace>) -> Self {
140        let (tx, rx) = tokio::sync::mpsc::channel::<TclCommand>(16);
141
142        std::thread::Builder::new()
143            .name("tcl-mount-driver".into())
144            .spawn(move || {
145                let rt = tokio::runtime::Builder::new_current_thread()
146                    .enable_all()
147                    .build()
148                    .expect("tcl-mount-driver runtime");
149                let local = tokio::task::LocalSet::new();
150                local.block_on(&rt, async move {
151                    let mut shell = TclShell::new(subject, ns);
152                    let mut rx = rx;
153                    while let Some(cmd) = rx.recv().await {
154                        shell.process_command(cmd).await;
155                    }
156                });
157            })
158            .expect("spawn tcl-mount-driver");
159
160        Self::build(tx)
161    }
162
163    /// Build a `TclMount` over an existing command-channel sender.
164    ///
165    /// Internal helper used by [`spawn`]; also used directly by tests that
166    /// drive the interpreter via a fake task instead of a real `TclShell`.
167    #[cfg(test)]
168    fn new(tx: tokio::sync::mpsc::Sender<TclCommand>) -> Self {
169        Self::build(tx)
170    }
171
172    fn build(tx: tokio::sync::mpsc::Sender<TclCommand>) -> Self {
173        let eval_tx = tx.clone();
174        let eval_handler = move |data: Vec<u8>| -> DevFuture<'static, Result<Vec<u8>, MountError>> {
175            let tx = eval_tx.clone();
176            let script = String::from_utf8_lossy(&data).into_owned();
177            Box::pin(async move {
178                let result = request(&tx, |resp| TclCommand::Eval { script, resp }).await?;
179                Ok(match result {
180                    Ok(s) => s.into_bytes(),
181                    Err(e) => format!("error: {e}").into_bytes(),
182                })
183            })
184        };
185        let eval = ControlFile::new(Box::new(eval_handler) as _);
186
187        let vars_tx = tx.clone();
188        let vars_get_tx = tx.clone();
189        let vars = DynamicDir::new(
190            Box::new(move || {
191                let tx = vars_tx.clone();
192                Box::pin(async move {
193                    request(&tx, |resp| TclCommand::ListVars { resp })
194                        .await
195                        .unwrap_or_default()
196                }) as DevFuture<'static, _>
197            }) as ListFn,
198            Box::new(move |name: String| {
199                let tx = vars_get_tx.clone();
200                Box::pin(async move {
201                    let val: Option<String> =
202                        request(&tx, |resp| TclCommand::GetVar { name, resp }).await?;
203                    Ok(val.map(String::into_bytes))
204                }) as DevFuture<'static, _>
205            }) as GetFn,
206        );
207
208        let procs_tx = tx.clone();
209        let procs_get_tx = tx.clone();
210        let procs = DynamicDir::new(
211            Box::new(move || {
212                let tx = procs_tx.clone();
213                Box::pin(async move {
214                    request(&tx, |resp| TclCommand::ListProcs { resp })
215                        .await
216                        .unwrap_or_default()
217                }) as DevFuture<'static, _>
218            }) as ListFn,
219            Box::new(move |name: String| {
220                let tx = procs_get_tx.clone();
221                Box::pin(async move {
222                    let val: Option<String> =
223                        request(&tx, |resp| TclCommand::GetProc { name, resp }).await?;
224                    Ok(val.map(String::into_bytes))
225                }) as DevFuture<'static, _>
226            }) as GetFn,
227        );
228
229        Self {
230            eval,
231            vars,
232            procs,
233            _driver_tx: tx,
234        }
235    }
236}
237
238/// Send a command and await the interpreter response.
239async fn request<T>(
240    tx: &tokio::sync::mpsc::Sender<TclCommand>,
241    build: impl FnOnce(tokio::sync::oneshot::Sender<T>) -> TclCommand,
242) -> Result<T, MountError> {
243    let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
244    let cmd = build(resp_tx);
245    tx.send(cmd)
246        .await
247        .map_err(|_| MountError::Io("tcl interpreter gone".into()))?;
248    resp_rx
249        .await
250        .map_err(|_| MountError::Io("tcl interpreter did not respond".into()))
251}
252
253#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
254#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
255impl Mount for TclMount {
256    async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
257        let kind = match components {
258            [] => TclFidKind::Root,
259            ["eval"] => TclFidKind::Eval,
260            ["vars"] => TclFidKind::VarsDir,
261            ["vars", name] => TclFidKind::Var((*name).to_owned()),
262            ["procs"] => TclFidKind::ProcsDir,
263            ["procs", name] => TclFidKind::Proc((*name).to_owned()),
264            _ => {
265                return Err(MountError::NotFound(components.join("/")));
266            }
267        };
268        Ok(Fid::new(TclFid {
269            kind,
270            ctl_state: DevFileState::new(),
271        }))
272    }
273
274    async fn open(&self, _fid: &mut Fid, _mode: u8, _caller: &Subject) -> Result<(), MountError> {
275        Ok(())
276    }
277
278    async fn read(
279        &self,
280        fid: &Fid,
281        offset: u64,
282        _count: u32,
283        _caller: &Subject,
284    ) -> Result<Vec<u8>, MountError> {
285        let inner = fid
286            .downcast_ref::<TclFid>()
287            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
288
289        match &inner.kind {
290            TclFidKind::Eval => Ok(self.eval.handle_read(&inner.ctl_state, offset)),
291            TclFidKind::Var(name) => self.vars.read(name, offset).await,
292            TclFidKind::Proc(name) => self.procs.read(name, offset).await,
293            TclFidKind::Root | TclFidKind::VarsDir | TclFidKind::ProcsDir => {
294                Err(MountError::IsDirectory("use readdir".into()))
295            }
296        }
297    }
298
299    async fn write(
300        &self,
301        fid: &Fid,
302        _offset: u64,
303        data: &[u8],
304        _caller: &Subject,
305    ) -> Result<u32, MountError> {
306        let inner = fid
307            .downcast_ref::<TclFid>()
308            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
309
310        match &inner.kind {
311            TclFidKind::Eval => self.eval.handle_write(&inner.ctl_state, data).await,
312            _ => Err(MountError::NotSupported("read-only".into())),
313        }
314    }
315
316    async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
317        let inner = fid
318            .downcast_ref::<TclFid>()
319            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
320
321        match &inner.kind {
322            TclFidKind::Root => Ok(vec![
323                DirEntry {
324                    name: "eval".into(),
325                    is_dir: false,
326                    size: 0,
327                    stat: None,
328                },
329                DirEntry {
330                    name: "vars".into(),
331                    is_dir: true,
332                    size: 0,
333                    stat: None,
334                },
335                DirEntry {
336                    name: "procs".into(),
337                    is_dir: true,
338                    size: 0,
339                    stat: None,
340                },
341            ]),
342            TclFidKind::VarsDir => Ok(self.vars.readdir().await),
343            TclFidKind::ProcsDir => Ok(self.procs.readdir().await),
344            _ => Err(MountError::NotDirectory(format!("{:?}", inner.kind))),
345        }
346    }
347
348    async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
349        let inner = fid
350            .downcast_ref::<TclFid>()
351            .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
352
353        let (name, qtype) = match &inner.kind {
354            TclFidKind::Root => ("tcl".to_owned(), 0x80), // QTDIR
355            TclFidKind::Eval => ("eval".to_owned(), 0),
356            TclFidKind::VarsDir => ("vars".to_owned(), 0x80),
357            TclFidKind::Var(n) => (n.clone(), 0),
358            TclFidKind::ProcsDir => ("procs".to_owned(), 0x80),
359            TclFidKind::Proc(n) => (n.clone(), 0),
360        };
361
362        Ok(Stat::unknown_qid(qtype, 0, name, 0))
363    }
364
365    async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
366}
367
368// ─────────────────────────────────────────────────────────────────────────────
369// Tests
370// ─────────────────────────────────────────────────────────────────────────────
371//
372// The command channel is internal to [`TclMount`] (constructed inside
373// [`TclMount::spawn`]). These tests drive the devfile wiring directly by
374// building a `TclMount` from an injected sender and routing the receiver to a
375// fake interpreter task, so the mount's request/reply plumbing can be
376// exercised without a real `TclShell`.
377
378#[cfg(test)]
379fn create_mount_channel() -> (
380    tokio::sync::mpsc::Sender<TclCommand>,
381    tokio::sync::mpsc::Receiver<TclCommand>,
382) {
383    tokio::sync::mpsc::channel(16)
384}
385
386#[cfg(test)]
387#[allow(clippy::unwrap_used)]
388mod tests {
389    use super::*;
390
391    /// Spawn a fake interpreter task that handles commands.
392    fn spawn_fake_interp(
393        mut rx: tokio::sync::mpsc::Receiver<TclCommand>,
394    ) -> tokio::task::JoinHandle<()> {
395        tokio::spawn(async move {
396            while let Some(cmd) = rx.recv().await {
397                match cmd {
398                    TclCommand::Eval { script, resp } => {
399                        if script == "error" {
400                            let _ = resp.send(Err("test error".into()));
401                        } else {
402                            let _ = resp.send(Ok(format!("result: {script}")));
403                        }
404                    }
405                    TclCommand::ListVars { resp } => {
406                        let _ = resp.send(vec!["x".into(), "y".into()]);
407                    }
408                    TclCommand::GetVar { name, resp } => {
409                        let val = match name.as_str() {
410                            "x" => Some("42".into()),
411                            "y" => Some("hello".into()),
412                            _ => None,
413                        };
414                        let _ = resp.send(val);
415                    }
416                    TclCommand::ListProcs { resp } => {
417                        let _ = resp.send(vec!["myproc".into()]);
418                    }
419                    TclCommand::GetProc { name, resp } => {
420                        let body = match name.as_str() {
421                            "myproc" => Some("puts hello".into()),
422                            _ => None,
423                        };
424                        let _ = resp.send(body);
425                    }
426                }
427            }
428        })
429    }
430
431    #[tokio::test]
432    async fn walk_root() {
433        let (tx, rx) = create_mount_channel();
434        let _h = spawn_fake_interp(rx);
435        let mount = TclMount::new(tx);
436        let subject = Subject::anonymous();
437
438        let fid = mount.walk(&[], &subject).await.unwrap();
439        let inner = fid.downcast_ref::<TclFid>().unwrap();
440        assert!(matches!(inner.kind, TclFidKind::Root));
441    }
442
443    #[tokio::test]
444    async fn walk_eval() {
445        let (tx, rx) = create_mount_channel();
446        let _h = spawn_fake_interp(rx);
447        let mount = TclMount::new(tx);
448        let subject = Subject::anonymous();
449
450        let fid = mount.walk(&["eval"], &subject).await.unwrap();
451        let inner = fid.downcast_ref::<TclFid>().unwrap();
452        assert!(matches!(inner.kind, TclFidKind::Eval));
453    }
454
455    #[tokio::test]
456    async fn walk_not_found() {
457        let (tx, rx) = create_mount_channel();
458        let _h = spawn_fake_interp(rx);
459        let mount = TclMount::new(tx);
460        let subject = Subject::anonymous();
461
462        let result = mount.walk(&["nonexistent"], &subject).await;
463        assert!(result.is_err());
464    }
465
466    #[tokio::test]
467    async fn eval_write_then_read() {
468        let (tx, rx) = create_mount_channel();
469        let _h = spawn_fake_interp(rx);
470        let mount = TclMount::new(tx);
471        let subject = Subject::anonymous();
472
473        let mut fid = mount.walk(&["eval"], &subject).await.unwrap();
474        mount.open(&mut fid, 2, &subject).await.unwrap();
475
476        // Write a script.
477        let written = mount.write(&fid, 0, b"expr {2+3}", &subject).await.unwrap();
478        assert_eq!(written, 10);
479
480        // Read back the result.
481        let data = mount.read(&fid, 0, 4096, &subject).await.unwrap();
482        assert_eq!(String::from_utf8(data).unwrap(), "result: expr {2+3}");
483    }
484
485    #[tokio::test]
486    async fn eval_error() {
487        let (tx, rx) = create_mount_channel();
488        let _h = spawn_fake_interp(rx);
489        let mount = TclMount::new(tx);
490        let subject = Subject::anonymous();
491
492        let mut fid = mount.walk(&["eval"], &subject).await.unwrap();
493        mount.open(&mut fid, 2, &subject).await.unwrap();
494        mount.write(&fid, 0, b"error", &subject).await.unwrap();
495
496        let data = mount.read(&fid, 0, 4096, &subject).await.unwrap();
497        assert_eq!(String::from_utf8(data).unwrap(), "error: test error");
498    }
499
500    #[tokio::test]
501    async fn readdir_root() {
502        let (tx, rx) = create_mount_channel();
503        let _h = spawn_fake_interp(rx);
504        let mount = TclMount::new(tx);
505        let subject = Subject::anonymous();
506
507        let fid = mount.walk(&[], &subject).await.unwrap();
508        let entries = mount.readdir(&fid, &subject).await.unwrap();
509        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
510        assert!(names.contains(&"eval"));
511        assert!(names.contains(&"vars"));
512        assert!(names.contains(&"procs"));
513    }
514
515    #[tokio::test]
516    async fn readdir_vars() {
517        let (tx, rx) = create_mount_channel();
518        let _h = spawn_fake_interp(rx);
519        let mount = TclMount::new(tx);
520        let subject = Subject::anonymous();
521
522        let fid = mount.walk(&["vars"], &subject).await.unwrap();
523        let entries = mount.readdir(&fid, &subject).await.unwrap();
524        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
525        assert!(names.contains(&"x"));
526        assert!(names.contains(&"y"));
527    }
528
529    #[tokio::test]
530    async fn read_var() {
531        let (tx, rx) = create_mount_channel();
532        let _h = spawn_fake_interp(rx);
533        let mount = TclMount::new(tx);
534        let subject = Subject::anonymous();
535
536        let mut fid = mount.walk(&["vars", "x"], &subject).await.unwrap();
537        mount.open(&mut fid, 0, &subject).await.unwrap();
538        let data = mount.read(&fid, 0, 4096, &subject).await.unwrap();
539        assert_eq!(String::from_utf8(data).unwrap(), "42");
540    }
541
542    #[tokio::test]
543    async fn read_var_not_found() {
544        let (tx, rx) = create_mount_channel();
545        let _h = spawn_fake_interp(rx);
546        let mount = TclMount::new(tx);
547        let subject = Subject::anonymous();
548
549        let mut fid = mount.walk(&["vars", "z"], &subject).await.unwrap();
550        mount.open(&mut fid, 0, &subject).await.unwrap();
551        let result = mount.read(&fid, 0, 4096, &subject).await;
552        assert!(result.is_err());
553    }
554
555    #[tokio::test]
556    async fn readdir_procs() {
557        let (tx, rx) = create_mount_channel();
558        let _h = spawn_fake_interp(rx);
559        let mount = TclMount::new(tx);
560        let subject = Subject::anonymous();
561
562        let fid = mount.walk(&["procs"], &subject).await.unwrap();
563        let entries = mount.readdir(&fid, &subject).await.unwrap();
564        assert_eq!(entries.len(), 1);
565        assert_eq!(entries[0].name, "myproc");
566    }
567
568    #[tokio::test]
569    async fn read_proc() {
570        let (tx, rx) = create_mount_channel();
571        let _h = spawn_fake_interp(rx);
572        let mount = TclMount::new(tx);
573        let subject = Subject::anonymous();
574
575        let mut fid = mount.walk(&["procs", "myproc"], &subject).await.unwrap();
576        mount.open(&mut fid, 0, &subject).await.unwrap();
577        let data = mount.read(&fid, 0, 4096, &subject).await.unwrap();
578        assert_eq!(String::from_utf8(data).unwrap(), "puts hello");
579    }
580
581    #[tokio::test]
582    async fn stat_directory() {
583        let (tx, rx) = create_mount_channel();
584        let _h = spawn_fake_interp(rx);
585        let mount = TclMount::new(tx);
586        let subject = Subject::anonymous();
587
588        let fid = mount.walk(&["vars"], &subject).await.unwrap();
589        let st = mount.stat(&fid, &subject).await.unwrap();
590        assert_eq!(st.qtype, 0x80); // QTDIR
591        assert_eq!(st.name, "vars");
592    }
593
594    #[tokio::test]
595    async fn stat_file() {
596        let (tx, rx) = create_mount_channel();
597        let _h = spawn_fake_interp(rx);
598        let mount = TclMount::new(tx);
599        let subject = Subject::anonymous();
600
601        let fid = mount.walk(&["eval"], &subject).await.unwrap();
602        let st = mount.stat(&fid, &subject).await.unwrap();
603        assert_eq!(st.qtype, 0);
604        assert_eq!(st.name, "eval");
605    }
606}