Skip to main content

hyprstream_vfs/
devfile.rs

1//! Reusable synthetic-file primitives for hand-built [`Mount`] implementations.
2//!
3//! `hyprstream-workers-tcl` and `hyprstream-workers-python` (and future
4//! language-shell crates) each hand-roll the same two shapes:
5//!
6//! - a **ctl file**: write triggers an action, the *next* read returns the
7//!   latched result (the Plan 9 ctl-file convention — see `eval` in both
8//!   crates' mounts).
9//! - a **field file**: a scalar read (optionally write) backed by live
10//!   interpreter state (`vars/<name>`, `defs/<name>`, `procs/<name>`).
11//!
12//! This module factors both into reusable, `Send + Sync` primitives so new
13//! language/device mounts don't need to re-derive the write→latch→read
14//! pattern (or its hazards — see the `unsafe *mut` cast `hyprstream-workers-tcl`
15//! used before this module existed) by hand. Modeled after Wanix's
16//! `ControlFile` / `FieldFile` devices, adapted to this crate's async
17//! [`Mount`] trait and `Box<dyn Any + Send + Sync>` [`Fid`].
18//!
19//! # Shape
20//!
21//! [`ControlFile`] and [`FieldFile`] are *descriptors*: long-lived, held by
22//! the owning `Mount` (typically behind an `Arc` or directly by value), and
23//! they hold the caller-supplied async callback(s). Per-open state — the
24//! write→read latch — lives in [`DevFileState`], a small `Fid` payload
25//! guarded by a `std::sync::Mutex` (not `parking_lot`, so this module stays
26//! wasm-portable; the lock is only ever held synchronously to clone/replace
27//! a `Vec<u8>`, never across an `.await`).
28//!
29//! Both callback shapes take and return owned bytes (`Vec<u8>` in, boxed
30//! future of `Vec<u8>`/`Result` out) rather than borrowing — this sidesteps
31//! HRTB lifetime issues with `Fn(&[u8]) -> impl Future<..> + '_` trait
32//! objects, and mirrors how both existing mounts already shuttle owned
33//! `String`/`Vec<u8>` across their command channels.
34//!
35//! # wasm32 Send-ness
36//!
37//! [`Mount`] is `#[async_trait(?Send)]` on `wasm32` and `#[async_trait]`
38//! (requiring `Send` futures) elsewhere. The callback future type here is
39//! gated the same way: `BoxFuture<'static, T>` (`Send`) off wasm32,
40//! `LocalBoxFuture<'static, T>` (no `Send` bound) on wasm32. Callers building
41//! a [`ControlFile`]/[`FieldFile`] for a native mount must produce `Send`
42//! futures (true today for both `hyprstream-workers-tcl` and
43//! `hyprstream-workers-python`, which proxy through `tokio::sync` channels).
44
45use parking_lot::Mutex;
46
47use crate::mount::{DirEntry, MountError};
48
49// ─────────────────────────────────────────────────────────────────────────────
50// Future type alias (Send off wasm32, ?Send on wasm32 — matches `Mount`)
51// ─────────────────────────────────────────────────────────────────────────────
52
53#[cfg(not(target_arch = "wasm32"))]
54/// Boxed future returned by device-file callbacks. `Send` off wasm32 to match
55/// [`Mount`]'s `#[async_trait]` (non-wasm) bound.
56pub type DevFuture<'a, T> = futures::future::BoxFuture<'a, T>;
57
58#[cfg(target_arch = "wasm32")]
59/// Boxed future returned by device-file callbacks. No `Send` bound on
60/// wasm32, matching [`Mount`]'s `#[async_trait(?Send)]` bound there.
61pub type DevFuture<'a, T> = futures::future::LocalBoxFuture<'a, T>;
62
63// ─────────────────────────────────────────────────────────────────────────────
64// DevFileState — per-fid write→latch→read buffer
65// ─────────────────────────────────────────────────────────────────────────────
66
67/// Per-fid state for a device file: a byte buffer latched by the last write
68/// (for [`ControlFile`]) or the last read (for [`FieldFile`] caching).
69///
70/// Stored as `Fid` payload (`Box<dyn Any + Send + Sync>`); `parking_lot::Mutex`
71/// gives interior mutability through the `&Fid` the [`Mount`] trait passes to
72/// `read`/`write` without the unsafe `*mut` cast `hyprstream-workers-tcl` used
73/// before this module existed.
74#[derive(Default)]
75pub struct DevFileState {
76    latched: Mutex<Vec<u8>>,
77}
78
79impl DevFileState {
80    /// Fresh, empty state (nothing written/read yet).
81    pub fn new() -> Self {
82        Self::default()
83    }
84
85    /// Replace the latched buffer.
86    pub fn latch(&self, data: Vec<u8>) {
87        *self.latched.lock() = data;
88    }
89
90    /// Clone the latched buffer (empty if nothing latched yet).
91    pub fn latched(&self) -> Vec<u8> {
92        self.latched.lock().clone()
93    }
94}
95
96/// Slice `data` at `offset`, returning at most the available remainder
97/// (9P read semantics: reading past EOF yields an empty result, not an
98/// error). `count` is accepted for symmetry with [`Mount::read`] callers
99/// but both primitives here return their full latched/rendered buffer from
100/// `offset` onward — callers needing chunked reads should slice further.
101pub fn read_from_offset(data: &[u8], offset: u64) -> Vec<u8> {
102    let start = offset as usize;
103    if start >= data.len() {
104        Vec::new()
105    } else {
106        data[start..].to_vec()
107    }
108}
109
110// ─────────────────────────────────────────────────────────────────────────────
111// ControlFile — write triggers an action, subsequent read returns the result
112// ─────────────────────────────────────────────────────────────────────────────
113
114/// A Plan 9-style ctl file: writing bytes invokes a caller-supplied async
115/// handler, whose result is latched and served on the next read.
116///
117/// Generic over the handler closure `F`. Construct with [`ControlFile::new`];
118/// the closure receives the written bytes **by value** (`Vec<u8>`, not `&[u8]`)
119/// and returns a boxed `'static` future resolving to the response bytes, or a
120/// [`MountError`] (rendered as-is — callers that want Wanix-style
121/// `"error: ..."` text on the read side should fold that into `F`'s `Ok` arm
122/// rather than returning `Err`, exactly as both `TclMount`/`PythonMount`
123/// already do for interpreter-level errors).
124///
125/// Taking owned bytes (rather than `&[u8]`) is a deliberate API choice: a
126/// `Fn(&'a [u8]) -> DevFuture<'a, _>` would need to be higher-ranked over
127/// `'a` (`for<'a> Fn(&'a [u8]) -> ...`), which closures capturing `move`d
128/// state can satisfy in principle but which the compiler frequently fails to
129/// infer for boxed closure literals in practice (the closure's `Fn` impl
130/// collapses to one concrete lifetime instead of being universally
131/// quantified). Owned input avoids the whole class of error and mirrors how
132/// both existing mounts already shuttle owned `String`/`Vec<u8>` across their
133/// command channels.
134///
135/// # Fid contract
136///
137/// Use [`ControlFile::new_fid`] in `Mount::walk` to create the per-open
138/// [`Fid`]; call [`ControlFile::handle_write`] from `Mount::write` and
139/// [`ControlFile::handle_read`] from `Mount::read`.
140pub struct ControlFile<F> {
141    handler: F,
142}
143
144impl<F> ControlFile<F>
145where
146    F: Fn(Vec<u8>) -> DevFuture<'static, Result<Vec<u8>, MountError>> + Send + Sync,
147{
148    /// Build a control file around an async handler.
149    pub fn new(handler: F) -> Self {
150        Self { handler }
151    }
152
153    /// Fresh per-fid latch state for this ctl file (nothing written yet).
154    pub fn new_fid(&self) -> DevFileState {
155        DevFileState::new()
156    }
157
158    /// Handle a `Mount::write`: run the handler over `data`, latch the
159    /// result (or an `"error: ..."`-free propagation — the error is returned
160    /// directly, NOT latched, matching `Mount::write`'s `Result` surface) into
161    /// `state`, and return the byte count written on success.
162    pub async fn handle_write(&self, state: &DevFileState, data: &[u8]) -> Result<u32, MountError> {
163        let len = data.len();
164        let result = (self.handler)(data.to_vec()).await?;
165        state.latch(result);
166        Ok(len as u32)
167    }
168
169    /// Handle a `Mount::read`: serve the latched result (empty if nothing
170    /// has been written yet), sliced from `offset`.
171    pub fn handle_read(&self, state: &DevFileState, offset: u64) -> Vec<u8> {
172        read_from_offset(&state.latched(), offset)
173    }
174}
175
176// ─────────────────────────────────────────────────────────────────────────────
177// FieldFile — scalar read (and optionally write) backed by live state
178// ─────────────────────────────────────────────────────────────────────────────
179
180/// A scalar field file: reading runs a caller-supplied async getter; writing
181/// (if a setter is supplied) runs a caller-supplied async setter. Used for
182/// `vars/<name>`, `defs/<name>`, `procs/<name>`-style leaves.
183///
184/// Unlike [`ControlFile`], a `FieldFile` does not require a write before a
185/// read — `get` is invoked directly on `Mount::read`. No per-fid latch state
186/// is needed (constructed fresh per access), keeping it stateless and cheap
187/// to build from a [`DynamicDir`] lookup.
188///
189/// `S` defaults to [`NoSetter`] (read-only field; [`FieldFile::read_only`]).
190/// [`FieldFile::read_write`] takes a real setter closure. Both shapes expose
191/// the same `handle_read`/`handle_write` methods — [`NoSetter::handle_write`]
192/// always returns [`MountError::NotSupported`], so callers don't need to
193/// special-case which constructor was used.
194pub struct FieldFile<G, S = NoSetter> {
195    get: G,
196    set: S,
197}
198
199/// A field file's write side: either [`NoSetter`] (read-only) or a real
200/// `Fn(Vec<u8>) -> DevFuture<'static, Result<(), MountError>>` closure.
201/// Sealed-by-convention — implemented here and via the blanket impl below;
202/// not meant to be implemented by downstream crates.
203#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
204#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
205pub trait FieldSetter: Send + Sync {
206    /// Apply a write, or reject it (read-only field).
207    async fn set(&self, data: Vec<u8>) -> Result<(), MountError>;
208}
209
210/// Marker type for a [`FieldFile`] with no setter (read-only field).
211pub struct NoSetter;
212
213#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
214#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
215impl FieldSetter for NoSetter {
216    async fn set(&self, _data: Vec<u8>) -> Result<(), MountError> {
217        Err(MountError::NotSupported("field is read-only".into()))
218    }
219}
220
221#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
222#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
223impl<S> FieldSetter for S
224where
225    S: Fn(Vec<u8>) -> DevFuture<'static, Result<(), MountError>> + Send + Sync,
226{
227    async fn set(&self, data: Vec<u8>) -> Result<(), MountError> {
228        (self)(data).await
229    }
230}
231
232impl<G> FieldFile<G, NoSetter>
233where
234    G: Fn() -> DevFuture<'static, Option<Vec<u8>>> + Send + Sync,
235{
236    /// Build a read-only field file. `get` returns `None` if the field no
237    /// longer exists (e.g. the variable was unset between `walk` and `read`),
238    /// surfaced as [`MountError::NotFound`].
239    pub fn read_only(get: G) -> Self {
240        Self { get, set: NoSetter }
241    }
242}
243
244impl<G, S> FieldFile<G, S>
245where
246    G: Fn() -> DevFuture<'static, Option<Vec<u8>>> + Send + Sync,
247    S: Fn(Vec<u8>) -> DevFuture<'static, Result<(), MountError>> + Send + Sync,
248{
249    /// Build a read/write field file.
250    pub fn read_write(get: G, set: S) -> Self {
251        Self { get, set }
252    }
253}
254
255impl<G, S> FieldFile<G, S>
256where
257    G: Fn() -> DevFuture<'static, Option<Vec<u8>>> + Send + Sync,
258    S: FieldSetter,
259{
260    /// Handle a `Mount::read`: run the getter, slice from `offset`.
261    pub async fn handle_read(&self, offset: u64, name: &str) -> Result<Vec<u8>, MountError> {
262        let data = (self.get)()
263            .await
264            .ok_or_else(|| MountError::NotFound(name.to_string()))?;
265        Ok(read_from_offset(&data, offset))
266    }
267
268    /// Handle a `Mount::write`: run the setter (or reject, for [`NoSetter`]).
269    pub async fn handle_write(&self, data: &[u8]) -> Result<u32, MountError> {
270        self.set.set(data.to_vec()).await?;
271        Ok(data.len() as u32)
272    }
273}
274
275// ─────────────────────────────────────────────────────────────────────────────
276// DynamicDir — a directory of FieldFile-shaped leaves listed by name
277// ─────────────────────────────────────────────────────────────────────────────
278
279/// Helper for the `vars/`, `defs/`, `procs/`-style directories both shell
280/// mounts expose: a `readdir` that lists live names and a per-name leaf read
281/// (and optional write) sourced from the same backing interpreter.
282///
283/// This is *not* a [`Mount`] itself — it's a pair of async callbacks
284/// (`list`, `get`) that a mount's `readdir`/`read` implementations delegate
285/// to for a given subtree, keeping the per-mount glue to a `match` on
286/// [`Fid`] kind. See `hyprstream-workers-tcl`'s `vars`/`procs` dirs and
287/// `hyprstream-workers-python`'s `vars`/`defs` dirs for the call sites.
288pub struct DynamicDir<L, G> {
289    list: L,
290    get: G,
291}
292
293impl<L, G> DynamicDir<L, G>
294where
295    L: Fn() -> DevFuture<'static, Vec<String>> + Send + Sync,
296    G: Fn(String) -> DevFuture<'static, Result<Option<Vec<u8>>, MountError>> + Send + Sync,
297{
298    /// Build a dynamic directory from a name-lister and a per-name getter.
299    ///
300    /// The getter returns `Result<Option<Vec<u8>>, MountError>` (not just
301    /// `Option<Vec<u8>>`) so callers can distinguish a genuine transport/
302    /// backend failure (propagated as-is) from "this name doesn't currently
303    /// resolve" (`Ok(None)`, surfaced by [`DynamicDir::read`] as
304    /// [`MountError::NotFound`]) — e.g. a `vars/<name>` lookup racing an
305    /// `unset` is `Ok(None)`, but the interpreter channel being closed is a
306    /// distinct `Err`.
307    pub fn new(list: L, get: G) -> Self {
308        Self { list, get }
309    }
310
311    /// `Mount::readdir` for this directory: one flat (non-dir) entry per
312    /// live name.
313    pub async fn readdir(&self) -> Vec<DirEntry> {
314        (self.list)()
315            .await
316            .into_iter()
317            .map(|name| DirEntry {
318                name,
319                is_dir: false,
320                size: 0,
321                stat: None,
322            })
323            .collect()
324    }
325
326    /// `Mount::read` for a `<dir>/<name>` leaf: fetch and slice from
327    /// `offset`. [`MountError::NotFound`] if the name no longer resolves;
328    /// any other error from the getter propagates unchanged.
329    pub async fn read(&self, name: &str, offset: u64) -> Result<Vec<u8>, MountError> {
330        let data = (self.get)(name.to_string())
331            .await?
332            .ok_or_else(|| MountError::NotFound(name.to_string()))?;
333        Ok(read_from_offset(&data, offset))
334    }
335}
336
337// ─────────────────────────────────────────────────────────────────────────────
338// Tests — exercise both primitives against a trivial in-memory Mount
339// ─────────────────────────────────────────────────────────────────────────────
340
341#[cfg(test)]
342#[allow(clippy::unwrap_used)]
343mod tests {
344    use super::*;
345    use crate::mount::{Fid, Mount, Stat};
346    use async_trait::async_trait;
347    use hyprstream_rpc::Subject;
348    use std::sync::Arc;
349    use tokio::sync::Mutex as AsyncMutex;
350
351    fn subj() -> Subject {
352        Subject::new("tester")
353    }
354
355    // ── ControlFile standalone tests ───────────────────────────────────────
356
357    #[tokio::test]
358    async fn control_file_write_then_read_latches_result() {
359        let ctl = ControlFile::new(|data: Vec<u8>| {
360            let s = String::from_utf8_lossy(&data).into_owned();
361            Box::pin(async move { Ok(format!("echo: {s}").into_bytes()) }) as DevFuture<'static, _>
362        });
363        let state = ctl.new_fid();
364
365        // Nothing written yet: read returns empty.
366        assert!(ctl.handle_read(&state, 0).is_empty());
367
368        let n = ctl.handle_write(&state, b"hello").await.unwrap();
369        assert_eq!(n, 5);
370
371        let out = ctl.handle_read(&state, 0);
372        assert_eq!(out, b"echo: hello");
373    }
374
375    #[tokio::test]
376    async fn control_file_offset_slices_latched_result() {
377        let ctl = ControlFile::new(|_data: Vec<u8>| {
378            Box::pin(async move { Ok(b"0123456789".to_vec()) }) as DevFuture<'static, _>
379        });
380        let state = ctl.new_fid();
381        ctl.handle_write(&state, b"x").await.unwrap();
382        assert_eq!(ctl.handle_read(&state, 5), b"56789");
383        assert_eq!(ctl.handle_read(&state, 100), b"");
384    }
385
386    #[tokio::test]
387    async fn control_file_handler_error_propagates_not_latched() {
388        let ctl = ControlFile::new(|_data: Vec<u8>| {
389            Box::pin(async move { Err(MountError::Io("boom".into())) }) as DevFuture<'static, _>
390        });
391        let state = ctl.new_fid();
392        let res = ctl.handle_write(&state, b"x").await;
393        assert!(res.is_err());
394        // Nothing latched on error.
395        assert!(ctl.handle_read(&state, 0).is_empty());
396    }
397
398    #[tokio::test]
399    async fn control_file_second_write_replaces_latch() {
400        let ctl = ControlFile::new(|data: Vec<u8>| {
401            Box::pin(async move { Ok(data) }) as DevFuture<'static, _>
402        });
403        let state = ctl.new_fid();
404        ctl.handle_write(&state, b"first").await.unwrap();
405        assert_eq!(ctl.handle_read(&state, 0), b"first");
406        ctl.handle_write(&state, b"second").await.unwrap();
407        assert_eq!(ctl.handle_read(&state, 0), b"second");
408    }
409
410    // ── FieldFile standalone tests ──────────────────────────────────────────
411
412    #[tokio::test]
413    async fn field_file_read_only_get() {
414        let field = FieldFile::read_only(|| {
415            Box::pin(async { Some(b"42".to_vec()) }) as DevFuture<'static, _>
416        });
417        let out = field.handle_read(0, "x").await.unwrap();
418        assert_eq!(out, b"42");
419    }
420
421    #[tokio::test]
422    async fn field_file_read_only_missing_is_not_found() {
423        let field = FieldFile::read_only(|| Box::pin(async { None }) as DevFuture<'static, _>);
424        let res = field.handle_read(0, "missing").await;
425        assert!(matches!(res, Err(MountError::NotFound(_))));
426    }
427
428    #[tokio::test]
429    async fn field_file_read_only_rejects_write() {
430        let field = FieldFile::read_only(|| {
431            Box::pin(async { Some(b"v".to_vec()) }) as DevFuture<'static, _>
432        });
433        let res = field.handle_write(b"new").await;
434        assert!(matches!(res, Err(MountError::NotSupported(_))));
435    }
436
437    #[tokio::test]
438    async fn field_file_read_write_round_trips_through_shared_state() {
439        let store: Arc<AsyncMutex<String>> = Arc::new(AsyncMutex::new("init".to_string()));
440
441        let get_store = store.clone();
442        let set_store = store.clone();
443        let field = FieldFile::read_write(
444            move || {
445                let store = get_store.clone();
446                Box::pin(async move { Some(store.lock().await.clone().into_bytes()) })
447                    as DevFuture<'static, _>
448            },
449            move |data: Vec<u8>| {
450                let store = set_store.clone();
451                Box::pin(async move {
452                    *store.lock().await = String::from_utf8_lossy(&data).into_owned();
453                    Ok(())
454                }) as DevFuture<'static, _>
455            },
456        );
457
458        assert_eq!(field.handle_read(0, "f").await.unwrap(), b"init");
459        let n = field.handle_write(b"updated").await.unwrap();
460        assert_eq!(n, 7);
461        assert_eq!(field.handle_read(0, "f").await.unwrap(), b"updated");
462    }
463
464    // ── DynamicDir standalone tests ─────────────────────────────────────────
465
466    #[tokio::test]
467    async fn dynamic_dir_lists_and_reads_names() {
468        let dir = DynamicDir::new(
469            || Box::pin(async { vec!["a".to_string(), "b".to_string()] }) as DevFuture<'static, _>,
470            |name: String| {
471                Box::pin(async move {
472                    Ok(match name.as_str() {
473                        "a" => Some(b"1".to_vec()),
474                        "b" => Some(b"2".to_vec()),
475                        _ => None,
476                    })
477                }) as DevFuture<'static, _>
478            },
479        );
480
481        let entries = dir.readdir().await;
482        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
483        assert_eq!(names, vec!["a", "b"]);
484        assert!(entries.iter().all(|e| !e.is_dir));
485
486        assert_eq!(dir.read("a", 0).await.unwrap(), b"1");
487        assert_eq!(dir.read("b", 0).await.unwrap(), b"2");
488        assert!(matches!(
489            dir.read("z", 0).await,
490            Err(MountError::NotFound(_))
491        ));
492    }
493
494    #[tokio::test]
495    async fn dynamic_dir_getter_error_propagates_distinct_from_not_found() {
496        // A getter `Err` (e.g. the backing channel is gone) must surface as
497        // that error, not be folded into NotFound the way `Ok(None)` is.
498        let dir = DynamicDir::new(
499            || Box::pin(async { vec!["a".to_string()] }) as DevFuture<'static, _>,
500            |_name: String| {
501                Box::pin(async { Err(MountError::Io("backend gone".into())) })
502                    as DevFuture<'static, _>
503            },
504        );
505        assert!(matches!(dir.read("a", 0).await, Err(MountError::Io(_))));
506    }
507
508    // ── End-to-end: a trivial Mount built entirely from these primitives ───
509
510    enum DemoFidKind {
511        Root,
512        Eval,
513        VarsDir,
514        Var(String),
515    }
516
517    struct DemoFid {
518        kind: DemoFidKind,
519        ctl_state: DevFileState,
520    }
521
522    type CtlHandler =
523        Box<dyn Fn(Vec<u8>) -> DevFuture<'static, Result<Vec<u8>, MountError>> + Send + Sync>;
524    type ListFn = Box<dyn Fn() -> DevFuture<'static, Vec<String>> + Send + Sync>;
525    type GetFn = Box<
526        dyn Fn(String) -> DevFuture<'static, Result<Option<Vec<u8>>, MountError>> + Send + Sync,
527    >;
528
529    /// A minimal `Mount` exercising `ControlFile` (an `eval` ctl file that
530    /// uppercases its input) and `DynamicDir` (a `vars/` dir over a fixed
531    /// in-memory map) — no language interpreter involved, just to prove the
532    /// primitives compose into a real `Mount` impl.
533    struct DemoMount {
534        ctl: ControlFile<CtlHandler>,
535        vars: DynamicDir<ListFn, GetFn>,
536    }
537
538    fn uppercase_ctl(data: Vec<u8>) -> DevFuture<'static, Result<Vec<u8>, MountError>> {
539        let s = String::from_utf8_lossy(&data).to_uppercase();
540        Box::pin(async move { Ok(s.into_bytes()) })
541    }
542
543    impl DemoMount {
544        fn new() -> Self {
545            let ctl = ControlFile::new(Box::new(uppercase_ctl) as CtlHandler);
546
547            let vars = DynamicDir::new(
548                Box::new(|| {
549                    Box::pin(async { vec!["x".to_string(), "y".to_string()] })
550                        as DevFuture<'static, _>
551                }) as ListFn,
552                Box::new(|name: String| {
553                    Box::pin(async move {
554                        Ok(match name.as_str() {
555                            "x" => Some(b"42".to_vec()),
556                            "y" => Some(b"hello".to_vec()),
557                            _ => None,
558                        })
559                    }) as DevFuture<'static, _>
560                }) as GetFn,
561            );
562
563            Self { ctl, vars }
564        }
565    }
566
567    #[async_trait]
568    impl Mount for DemoMount {
569        async fn walk(&self, components: &[&str], _caller: &Subject) -> Result<Fid, MountError> {
570            let kind = match components {
571                [] => DemoFidKind::Root,
572                ["eval"] => DemoFidKind::Eval,
573                ["vars"] => DemoFidKind::VarsDir,
574                ["vars", name] => DemoFidKind::Var((*name).to_owned()),
575                _ => return Err(MountError::NotFound(components.join("/"))),
576            };
577            Ok(Fid::new(DemoFid {
578                kind,
579                ctl_state: DevFileState::new(),
580            }))
581        }
582
583        async fn open(
584            &self,
585            _fid: &mut Fid,
586            _mode: u8,
587            _caller: &Subject,
588        ) -> Result<(), MountError> {
589            Ok(())
590        }
591
592        async fn read(
593            &self,
594            fid: &Fid,
595            offset: u64,
596            _count: u32,
597            _caller: &Subject,
598        ) -> Result<Vec<u8>, MountError> {
599            let inner = fid
600                .downcast_ref::<DemoFid>()
601                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
602            match &inner.kind {
603                DemoFidKind::Eval => Ok(self.ctl.handle_read(&inner.ctl_state, offset)),
604                DemoFidKind::Var(name) => self.vars.read(name, offset).await,
605                DemoFidKind::Root | DemoFidKind::VarsDir => {
606                    Err(MountError::IsDirectory("use readdir".into()))
607                }
608            }
609        }
610
611        async fn write(
612            &self,
613            fid: &Fid,
614            _offset: u64,
615            data: &[u8],
616            _caller: &Subject,
617        ) -> Result<u32, MountError> {
618            let inner = fid
619                .downcast_ref::<DemoFid>()
620                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
621            match &inner.kind {
622                DemoFidKind::Eval => self.ctl.handle_write(&inner.ctl_state, data).await,
623                _ => Err(MountError::NotSupported("read-only".into())),
624            }
625        }
626
627        async fn readdir(&self, fid: &Fid, _caller: &Subject) -> Result<Vec<DirEntry>, MountError> {
628            let inner = fid
629                .downcast_ref::<DemoFid>()
630                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
631            match &inner.kind {
632                DemoFidKind::Root => Ok(vec![
633                    DirEntry {
634                        name: "eval".into(),
635                        is_dir: false,
636                        size: 0,
637                        stat: None,
638                    },
639                    DirEntry {
640                        name: "vars".into(),
641                        is_dir: true,
642                        size: 0,
643                        stat: None,
644                    },
645                ]),
646                DemoFidKind::VarsDir => Ok(self.vars.readdir().await),
647                _ => Err(MountError::NotDirectory("not a directory".into())),
648            }
649        }
650
651        async fn stat(&self, fid: &Fid, _caller: &Subject) -> Result<Stat, MountError> {
652            let inner = fid
653                .downcast_ref::<DemoFid>()
654                .ok_or_else(|| MountError::InvalidArgument("bad fid".into()))?;
655            let (name, qtype) = match &inner.kind {
656                DemoFidKind::Root => ("demo".to_string(), 0x80),
657                DemoFidKind::Eval => ("eval".to_string(), 0),
658                DemoFidKind::VarsDir => ("vars".to_string(), 0x80),
659                DemoFidKind::Var(n) => (n.clone(), 0),
660            };
661            Ok(Stat {
662                qtype,
663                version: 0,
664                path: 0,
665                size: 0,
666                name,
667                mtime: 0,
668            })
669        }
670
671        async fn clunk(&self, _fid: Fid, _caller: &Subject) {}
672    }
673
674    #[tokio::test]
675    async fn demo_mount_eval_ctl_round_trip() {
676        let mount = DemoMount::new();
677        let s = subj();
678        let mut fid = mount.walk(&["eval"], &s).await.unwrap();
679        mount.open(&mut fid, 1, &s).await.unwrap();
680        mount.write(&fid, 0, b"hello", &s).await.unwrap();
681        let out = mount.read(&fid, 0, 4096, &s).await.unwrap();
682        assert_eq!(out, b"HELLO");
683    }
684
685    #[tokio::test]
686    async fn demo_mount_vars_dir_listing_and_leaves() {
687        let mount = DemoMount::new();
688        let s = subj();
689
690        let dir_fid = mount.walk(&["vars"], &s).await.unwrap();
691        let entries = mount.readdir(&dir_fid, &s).await.unwrap();
692        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
693        assert!(names.contains(&"x"));
694        assert!(names.contains(&"y"));
695
696        let x_fid = mount.walk(&["vars", "x"], &s).await.unwrap();
697        let out = mount.read(&x_fid, 0, 4096, &s).await.unwrap();
698        assert_eq!(out, b"42");
699
700        let missing = mount.walk(&["vars", "z"], &s).await.unwrap();
701        assert!(mount.read(&missing, 0, 4096, &s).await.is_err());
702    }
703
704    #[tokio::test]
705    async fn demo_mount_readdir_root() {
706        let mount = DemoMount::new();
707        let s = subj();
708        let fid = mount.walk(&[], &s).await.unwrap();
709        let entries = mount.readdir(&fid, &s).await.unwrap();
710        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
711        assert!(names.contains(&"eval"));
712        assert!(names.contains(&"vars"));
713    }
714}