Skip to main content

hyprstream_core/services/
fs.rs

1//! Reusable synthetic 9P filesystem for services.
2//!
3//! Services that expose a synthetic file tree (model status, tool schemas, etc.)
4//! construct a `SyntheticTree` at startup, register nodes, and delegate 9P
5//! operations to it. The tree handles fid allocation, walk resolution,
6//! open/read/write dispatch, and idle fid reaping.
7//!
8//! This is the synthetic counterpart to the registry's real-filesystem 9P handler.
9//! No real files — all content is generated by closures.
10
11use std::collections::{HashMap, VecDeque};
12use std::future::Future;
13use std::pin::Pin;
14use std::sync::atomic::{AtomicU32, AtomicU64, Ordering::Relaxed};
15use std::sync::Arc;
16
17use dashmap::DashMap;
18use parking_lot::Mutex;
19
20use crate::services::types::{DEFAULT_IOUNIT, QTDIR, QTFILE};
21use hyprstream_vfs::DirEntry;
22
23// ─────────────────────────────────────────────────────────────────────────────
24// Synthetic node types
25// ─────────────────────────────────────────────────────────────────────────────
26
27/// A node in the synthetic file tree.
28pub enum SyntheticNode {
29    /// Static directory with fixed children.
30    Dir {
31        children: HashMap<String, SyntheticNode>,
32    },
33    /// Directory whose children are computed dynamically (e.g., model list).
34    DynamicDir {
35        list: Box<dyn Fn() -> Vec<DirEntry> + Send + Sync>,
36        /// Resolve a child name to a subtree (called after walk finds a dynamic entry).
37        resolve: Box<dyn Fn(&str) -> Option<SyntheticNode> + Send + Sync>,
38    },
39    /// Read-only file whose content is generated on read.
40    ReadFile(Box<dyn Fn() -> Vec<u8> + Send + Sync>),
41    /// Control file: write input, read response. Mutations go here (Plan9 ctl pattern).
42    /// The handler receives the caller's `Subject` so it can enforce per-caller authorization.
43    CtlFile {
44        handler:
45            Box<dyn Fn(&[u8], &hyprstream_rpc::Subject) -> Result<Vec<u8>, String> + Send + Sync>,
46    },
47    /// Status file backed by `tokio::sync::watch`. Always returns the latest value.
48    /// Stores the Sender so receivers can be cloned per-fid at walk time.
49    /// Uses `bytes::Bytes` for O(1) reference-counted clone on the read path.
50    WatchFile(tokio::sync::watch::Sender<bytes::Bytes>),
51    /// Completion file backed by `tokio::sync::OnceCell`. First reader resolves;
52    /// all subsequent readers get the cached value.
53    OneshotFile(Arc<OneshotState>),
54    /// Async ctl file with an async handler. Used for operations that need `.await`
55    /// (e.g., forwarding to remote services). Must resolve as `ResolvedNode::Static`
56    /// to avoid holding DashMap guards across await points.
57    AsyncCtlFile {
58        handler: Box<
59            dyn Fn(
60                    Vec<u8>,
61                    hyprstream_rpc::Subject,
62                ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, String>> + Send>>
63                + Send
64                + Sync,
65        >,
66    },
67}
68
69/// State for a `OneshotFile` node.
70///
71/// Cancellation-safe: only successful results are cached in the `OnceCell`.
72/// If the sender is dropped before sending, `read()` returns an error but does
73/// not poison the file — a new sender could be wired up (though in practice
74/// oneshot channels are single-use).
75pub struct OneshotState {
76    cell: tokio::sync::OnceCell<bytes::Bytes>,
77    rx: tokio::sync::Mutex<Option<tokio::sync::oneshot::Receiver<bytes::Bytes>>>,
78}
79
80impl OneshotState {
81    /// Create a new OneshotState. The returned oneshot Sender resolves the file.
82    pub fn new() -> (Arc<Self>, tokio::sync::oneshot::Sender<bytes::Bytes>) {
83        let (tx, rx) = tokio::sync::oneshot::channel();
84        let state = Arc::new(Self {
85            cell: tokio::sync::OnceCell::new(),
86            rx: tokio::sync::Mutex::new(Some(rx)),
87        });
88        (state, tx)
89    }
90
91    /// Read the value. First caller takes the receiver and awaits it;
92    /// all subsequent callers get the cached result.
93    ///
94    /// Only `Ok` values are cached. Errors (sender dropped) are transient —
95    /// the `OnceCell` remains uninitialised so a future call could still succeed
96    /// if the receiver is somehow replaced (not typical for oneshot, but
97    /// prevents permanent poisoning).
98    pub async fn read(&self) -> Result<bytes::Bytes, String> {
99        // Fast path: already resolved.
100        if let Some(data) = self.cell.get() {
101            return Ok(data.clone());
102        }
103
104        // Slow path: take the receiver (brief lock, not held across await).
105        let rx = {
106            let mut guard = self.rx.lock().await;
107            guard.take()
108        };
109        match rx {
110            Some(rx) => match rx.await {
111                Ok(data) => {
112                    // Cache the successful result. If another task raced us,
113                    // set() returns Err but the value is already cached — fine.
114                    let _ = self.cell.set(data.clone());
115                    Ok(data)
116                }
117                Err(_) => Err("oneshot sender dropped".to_owned()),
118            },
119            None => {
120                // Receiver already taken by another caller — check if they cached a result.
121                match self.cell.get() {
122                    Some(data) => Ok(data.clone()),
123                    None => Err("oneshot pending — another reader is resolving".to_owned()),
124                }
125            }
126        }
127    }
128}
129
130// ─────────────────────────────────────────────────────────────────────────────
131// Qid generation for synthetic nodes
132// ─────────────────────────────────────────────────────────────────────────────
133
134/// Synthetic Qid: deterministic FNV-1a hash of the path string as the inode,
135/// with a constant version.
136///
137/// Advisory identity hint only — `version` is constant (no change-detection)
138/// and `path` is non-cryptographic and changes on rename. No authz may key on
139/// this. See the qid-soundness invariant on `hyprstream_vfs::Stat`; the
140/// content-CID-derived qid lands in #387.
141#[derive(Clone, Debug)]
142pub struct SyntheticQid {
143    pub qtype: u8,
144    pub version: u32,
145    pub path: u64,
146}
147
148impl SyntheticQid {
149    pub fn dir(path_str: &str) -> Self {
150        Self {
151            qtype: QTDIR,
152            version: 1,
153            path: hash_path(path_str),
154        }
155    }
156
157    pub fn file(path_str: &str) -> Self {
158        Self {
159            qtype: QTFILE,
160            version: 1,
161            path: hash_path(path_str),
162        }
163    }
164}
165
166fn hash_path(path: &str) -> u64 {
167    // FNV-1a 64-bit hash — fast, deterministic, no crypto dependency.
168    let mut h: u64 = 0xcbf29ce484222325;
169    for b in path.as_bytes() {
170        h ^= *b as u64;
171        h = h.wrapping_mul(0x100000001b3);
172    }
173    h
174}
175
176// ─────────────────────────────────────────────────────────────────────────────
177// Fid table
178// ─────────────────────────────────────────────────────────────────────────────
179
180/// What a fid's node resolves to (for read/write dispatch).
181enum ResolvedNode {
182    /// Path into the static tree — resolve at read time via resolve_node.
183    Static(Vec<String>),
184    /// A dynamically-resolved node cached at walk time.
185    Dynamic(SyntheticNode),
186}
187
188enum FidState {
189    Walked {
190        resolved: ResolvedNode,
191        qid: SyntheticQid,
192    },
193    Opened {
194        resolved: ResolvedNode,
195        qid: SyntheticQid,
196        mode: u8,
197        /// Buffer for ctl file responses (written by handler, drained by read).
198        response_buf: Mutex<VecDeque<u8>>,
199    },
200}
201
202struct FidEntry {
203    state: FidState,
204    owner: String,
205    last_accessed: AtomicU64,
206}
207
208/// Fid table for synthetic filesystem. Per-client fid counts and idle reaping.
209pub struct SyntheticFidTable {
210    next_fid: AtomicU32,
211    fids: DashMap<u32, FidEntry>,
212    client_counts: DashMap<String, AtomicU32>,
213}
214
215impl Default for SyntheticFidTable {
216    fn default() -> Self {
217        Self::new()
218    }
219}
220
221impl SyntheticFidTable {
222    pub fn new() -> Self {
223        Self {
224            next_fid: AtomicU32::new(1),
225            fids: DashMap::new(),
226            client_counts: DashMap::new(),
227        }
228    }
229
230    fn alloc_fid(&self, owner: &str) -> Result<u32, &'static str> {
231        use std::sync::atomic::Ordering::{AcqRel, Acquire};
232        let count = self
233            .client_counts
234            .entry(owner.to_owned())
235            .or_insert_with(|| AtomicU32::new(0));
236        // Atomic check-and-increment to prevent exceeding per-client limit on ARM.
237        if count
238            .fetch_update(AcqRel, Acquire, |c| {
239                if c >= crate::services::types::MAX_FIDS_PER_CLIENT {
240                    None
241                } else {
242                    Some(c + 1)
243                }
244            })
245            .is_err()
246        {
247            return Err("too many open fids");
248        }
249        if self.fids.len() as u32 >= crate::services::types::MAX_FIDS_GLOBAL {
250            count.fetch_sub(1, AcqRel);
251            return Err("global fid limit reached");
252        }
253        // Retry on collision using atomic entry() to avoid TOCTOU.
254        for _ in 0..1000 {
255            let fid = self.next_fid.fetch_add(1, Relaxed);
256            if fid == 0 {
257                continue;
258            } // 0 is reserved for root
259            if let dashmap::mapref::entry::Entry::Vacant(_) = self.fids.entry(fid) {
260                // Fid is available — caller will insert via insert_at().
261                return Ok(fid);
262            }
263        }
264        count.fetch_sub(1, AcqRel);
265        Err("fid allocation failed after retries")
266    }
267
268    fn insert(&self, fid: u32, entry: FidEntry) {
269        self.fids.insert(fid, entry);
270    }
271
272    fn get_verified(
273        &self,
274        fid: u32,
275        owner: &str,
276    ) -> Result<dashmap::mapref::one::Ref<'_, u32, FidEntry>, &'static str> {
277        let entry = self.fids.get(&fid).ok_or("fid not found")?;
278        if entry.owner != owner {
279            return Err("fid not owned by caller");
280        }
281        entry.last_accessed.store(now_secs(), Relaxed);
282        Ok(entry)
283    }
284
285    fn take(&self, fid: u32, owner: &str) -> Result<FidEntry, &'static str> {
286        // Atomic remove-if-owned to avoid TOCTOU between remove and ownership check.
287        let removed = self.fids.remove_if(&fid, |_, entry| entry.owner == owner);
288        match removed {
289            Some((_, entry)) => Ok(entry),
290            None => {
291                // Either fid doesn't exist or wrong owner.
292                if self.fids.contains_key(&fid) {
293                    Err("fid not owned by caller")
294                } else {
295                    Err("fid not found")
296                }
297            }
298        }
299    }
300
301    fn remove(&self, fid: u32, owner: &str) {
302        if let Some((_, entry)) = self.fids.remove(&fid) {
303            if entry.owner == owner {
304                if let Some(count) = self.client_counts.get(&entry.owner) {
305                    count.fetch_sub(1, Relaxed);
306                }
307            } else {
308                // Wrong owner — put it back.
309                self.fids.insert(fid, entry);
310            }
311        }
312    }
313
314    /// Reap fids idle for more than `max_idle_secs`.
315    pub fn reap(&self, max_idle_secs: u64) {
316        let now = now_secs();
317        self.fids.retain(|_fid, entry| {
318            let idle = now.saturating_sub(entry.last_accessed.load(Relaxed));
319            if idle > max_idle_secs {
320                if let Some(count) = self.client_counts.get(&entry.owner) {
321                    count.fetch_sub(1, Relaxed);
322                }
323                false
324            } else {
325                true
326            }
327        });
328    }
329}
330
331fn now_secs() -> u64 {
332    std::time::SystemTime::now()
333        .duration_since(std::time::UNIX_EPOCH)
334        .unwrap_or_default()
335        .as_secs()
336}
337
338// ─────────────────────────────────────────────────────────────────────────────
339// SyntheticTree
340// ─────────────────────────────────────────────────────────────────────────────
341
342/// A synthetic 9P file tree backed by closures.
343///
344/// Services construct a tree at startup, then delegate 9P walk/open/read/write
345/// operations to it. All state is in the fid table; the tree itself is immutable
346/// after construction.
347pub struct SyntheticTree {
348    root: SyntheticNode,
349    fid_table: SyntheticFidTable,
350}
351
352impl SyntheticTree {
353    pub fn new(root: SyntheticNode) -> Self {
354        Self {
355            root,
356            fid_table: SyntheticFidTable::new(),
357        }
358    }
359
360    /// Walk path components from root.
361    ///
362    /// If `newfid` is Some and > 0, uses the client-chosen fid (9P protocol).
363    /// If `newfid` is None or 0, auto-allocates a server-side fid.
364    pub fn walk(
365        &self,
366        wnames: &[String],
367        owner: &str,
368        newfid: Option<u32>,
369    ) -> Result<(u32, SyntheticQid), String> {
370        let fid = match newfid {
371            Some(f) if f > 0 => {
372                // Client-chosen fid — check not already in use, count against limits.
373                if self.fid_table.fids.contains_key(&f) {
374                    return Err("fid already in use".to_owned());
375                }
376                use std::sync::atomic::Ordering::{AcqRel, Acquire};
377                let count = self
378                    .fid_table
379                    .client_counts
380                    .entry(owner.to_owned())
381                    .or_insert_with(|| AtomicU32::new(0));
382                if count
383                    .fetch_update(AcqRel, Acquire, |c| {
384                        if c >= crate::services::types::MAX_FIDS_PER_CLIENT {
385                            None
386                        } else {
387                            Some(c + 1)
388                        }
389                    })
390                    .is_err()
391                {
392                    return Err("too many open fids".to_owned());
393                }
394                f
395            }
396            _ => self.fid_table.alloc_fid(owner).map_err(str::to_owned)?,
397        };
398
399        let (qid, resolved) = if wnames.is_empty() {
400            (SyntheticQid::dir("/"), ResolvedNode::Static(vec![]))
401        } else {
402            self.resolve_walk(wnames)?
403        };
404
405        self.fid_table.insert(
406            fid,
407            FidEntry {
408                state: FidState::Walked {
409                    resolved,
410                    qid: qid.clone(),
411                },
412                owner: owner.to_owned(),
413                last_accessed: AtomicU64::new(now_secs()),
414            },
415        );
416
417        Ok((fid, qid))
418    }
419
420    /// Open a walked fid for I/O.
421    pub fn open(&self, fid: u32, mode: u8, owner: &str) -> Result<(SyntheticQid, u32), String> {
422        let entry = self.fid_table.take(fid, owner)?;
423        match entry.state {
424            FidState::Walked { resolved, qid } => {
425                let new_entry = FidEntry {
426                    state: FidState::Opened {
427                        resolved,
428                        qid: qid.clone(),
429                        mode,
430                        response_buf: Mutex::new(VecDeque::new()),
431                    },
432                    owner: entry.owner,
433                    last_accessed: AtomicU64::new(now_secs()),
434                };
435                self.fid_table.insert(fid, new_entry);
436                Ok((qid, DEFAULT_IOUNIT))
437            }
438            FidState::Opened { .. } => {
439                self.fid_table.insert(fid, entry);
440                Err("fid already open".to_owned())
441            }
442        }
443    }
444
445    /// Read from an opened fid.
446    ///
447    /// For Static resolved nodes, the DashMap guard is dropped before calling
448    /// the content-generation closure to avoid holding shard locks during I/O.
449    /// For Dynamic nodes (captured closures), the guard is held — closures
450    /// MUST be non-blocking (in-memory operations only).
451    pub fn read(&self, fid: u32, offset: u64, count: u32, owner: &str) -> Result<Vec<u8>, String> {
452        // First, check for buffered ctl response data (quick path, minimal lock scope).
453        {
454            let entry = self.fid_table.get_verified(fid, owner)?;
455            if let FidState::Opened { response_buf, .. } = &entry.state {
456                let mut buf = response_buf.lock();
457                if !buf.is_empty() {
458                    let n = std::cmp::min(count as usize, buf.len());
459                    let data: Vec<u8> = buf.drain(..n).collect();
460                    return Ok(data);
461                }
462            } else {
463                return Err("fid not open".to_owned());
464            }
465        } // DashMap guard dropped here.
466
467        // For Static paths, extract the path and drop the guard before resolving.
468        let entry = self.fid_table.get_verified(fid, owner)?;
469        let resolved = match &entry.state {
470            FidState::Opened { resolved, .. } => resolved,
471            _ => return Err("fid not open".to_owned()),
472        };
473
474        match resolved {
475            ResolvedNode::Static(path) => {
476                let path_clone = path.clone();
477                drop(entry); // Release DashMap guard before calling closures.
478                let node = self.resolve_node(&path_clone);
479                self.read_from_node(node, offset, count)
480            }
481            ResolvedNode::Dynamic(node) => {
482                // Guard held — closures must be non-blocking.
483                self.read_from_node(Some(node), offset, count)
484            }
485        }
486    }
487
488    fn read_from_node(
489        &self,
490        node: Option<&SyntheticNode>,
491        offset: u64,
492        count: u32,
493    ) -> Result<Vec<u8>, String> {
494        match node {
495            Some(SyntheticNode::ReadFile(gen)) => {
496                let content = gen();
497                let start = std::cmp::min(offset as usize, content.len());
498                let end = std::cmp::min(start + count as usize, content.len());
499                Ok(content[start..end].to_vec())
500            }
501            Some(SyntheticNode::Dir { children }) => {
502                if offset > 0 {
503                    return Ok(vec![]);
504                }
505                Ok(encode_dir_entries(
506                    &children
507                        .keys()
508                        .map(|k| DirEntry {
509                            name: k.clone(),
510                            is_dir: matches!(
511                                children.get(k),
512                                Some(SyntheticNode::Dir { .. } | SyntheticNode::DynamicDir { .. })
513                            ),
514                            size: 0,
515                            stat: None,
516                        })
517                        .collect::<Vec<_>>(),
518                    count,
519                ))
520            }
521            Some(SyntheticNode::DynamicDir { list, .. }) => {
522                if offset > 0 {
523                    return Ok(vec![]);
524                }
525                Ok(encode_dir_entries(&list(), count))
526            }
527            Some(SyntheticNode::CtlFile { .. }) | Some(SyntheticNode::AsyncCtlFile { .. }) => {
528                Ok(vec![])
529            }
530            Some(SyntheticNode::WatchFile(sender)) => {
531                // Borrow the latest value from the watch channel — instant, no await.
532                // NOTE: For Dynamic nodes this runs under a DashMap guard. That's acceptable
533                // because `sender.borrow()` is non-blocking (returns a `Ref` immediately)
534                // and `Bytes::clone()` is O(1) (reference count bump). The Ref is dropped
535                // before returning. No contention risk.
536                let data = sender.borrow().clone();
537                let start = std::cmp::min(offset as usize, data.len());
538                let end = std::cmp::min(start + count as usize, data.len());
539                Ok(data[start..end].to_vec())
540            }
541            // OneshotFile requires async — cannot be read on the sync path.
542            Some(SyntheticNode::OneshotFile(_)) => {
543                Err("OneshotFile requires async read (use Mount trait)".to_owned())
544            }
545            None => Err("path not found in tree".to_owned()),
546        }
547    }
548
549    /// Read directory entries as structured data (for Mount bridge).
550    pub fn readdir_entries(&self, fid: u32, owner: &str) -> Result<Vec<DirEntry>, String> {
551        let entry = self.fid_table.get_verified(fid, owner)?;
552        let resolved = match &entry.state {
553            FidState::Opened { resolved, .. } => resolved,
554            _ => return Err("fid not open".to_owned()),
555        };
556
557        match resolved {
558            ResolvedNode::Static(path) => {
559                let path_clone = path.clone();
560                drop(entry);
561                let node = self.resolve_node(&path_clone);
562                self.readdir_from_node(node)
563            }
564            ResolvedNode::Dynamic(node) => self.readdir_from_node(Some(node)),
565        }
566    }
567
568    fn readdir_from_node(&self, node: Option<&SyntheticNode>) -> Result<Vec<DirEntry>, String> {
569        match node {
570            Some(SyntheticNode::Dir { children }) => Ok(children
571                .keys()
572                .map(|k| DirEntry {
573                    name: k.clone(),
574                    is_dir: matches!(
575                        children.get(k),
576                        Some(SyntheticNode::Dir { .. } | SyntheticNode::DynamicDir { .. })
577                    ),
578                    size: 0,
579                    stat: None,
580                })
581                .collect()),
582            Some(SyntheticNode::DynamicDir { list, .. }) => Ok(list()),
583            _ => Err("not a directory".to_owned()),
584        }
585    }
586
587    /// Maximum ctl response buffer size per fid (256 KB).
588    const MAX_RESPONSE_BUF: usize = 256 * 1024;
589
590    /// Write to an opened fid.
591    ///
592    /// For ctl files, the handler closure is invoked and the response is buffered
593    /// for subsequent reads. Response buffer is capped at MAX_RESPONSE_BUF.
594    pub fn write(
595        &self,
596        fid: u32,
597        _offset: u64,
598        data: &[u8],
599        owner: &str,
600        subject: &hyprstream_rpc::Subject,
601    ) -> Result<u32, String> {
602        let entry = self.fid_table.get_verified(fid, owner)?;
603        match &entry.state {
604            FidState::Opened {
605                resolved,
606                mode,
607                response_buf,
608                ..
609            } => {
610                let base_mode = *mode & 0x03;
611                if base_mode != hyprstream_vfs::OWRITE && base_mode != hyprstream_vfs::ORDWR {
612                    return Err("fid not open for writing".to_owned());
613                }
614                let node = match resolved {
615                    ResolvedNode::Static(path) => self.resolve_node(path),
616                    ResolvedNode::Dynamic(node) => Some(node),
617                };
618                match node {
619                    Some(SyntheticNode::CtlFile { handler }) => {
620                        let result = handler(data, subject)?;
621                        let written = data.len() as u32;
622                        let mut buf = response_buf.lock();
623                        // Clear old response on new write (Plan9 convention: each write is a new command).
624                        buf.clear();
625                        let cap = Self::MAX_RESPONSE_BUF.min(result.len());
626                        buf.extend(&result[..cap]);
627                        Ok(written)
628                    }
629                    _ => Err("path not writable".to_owned()),
630                }
631            }
632            _ => Err("fid not open".to_owned()),
633        }
634    }
635
636    /// Stat a walked or opened fid.
637    pub fn stat(&self, fid: u32, owner: &str) -> Result<(SyntheticQid, String), String> {
638        let entry = self.fid_table.get_verified(fid, owner)?;
639        let qid = match &entry.state {
640            FidState::Walked { qid, .. } | FidState::Opened { qid, .. } => qid.clone(),
641        };
642        // Extract name from the qid path hash — not ideal, but we don't store the path anymore
643        // for dynamic nodes. Return empty name for now; callers that need the name should
644        // track it separately.
645        Ok((qid, String::new()))
646    }
647
648    /// Release a fid.
649    pub fn clunk(&self, fid: u32, owner: &str) {
650        self.fid_table.remove(fid, owner);
651    }
652
653    /// Reap idle fids (call periodically from a background task).
654    pub fn reap(&self, max_idle_secs: u64) {
655        self.fid_table.reap(max_idle_secs);
656    }
657
658    // ── Internal ────────────────────────────────────────────────────────────
659
660    /// Resolve a walk, returning a Qid and a ResolvedNode for the fid.
661    /// Static paths get `ResolvedNode::Static` (resolved at read time).
662    /// Paths through DynamicDir get `ResolvedNode::Dynamic` (cached subtree).
663    fn resolve_walk(&self, components: &[String]) -> Result<(SyntheticQid, ResolvedNode), String> {
664        let mut current = &self.root;
665        let mut static_path = Vec::new();
666
667        for (i, name) in components.iter().enumerate() {
668            match current {
669                SyntheticNode::Dir { children } => {
670                    if let Some(child) = children.get(name) {
671                        static_path.push(name.clone());
672                        current = child;
673                    } else {
674                        return Err(format!("not found: {}", components[..=i].join("/")));
675                    }
676                }
677                SyntheticNode::DynamicDir { list, resolve } => {
678                    let entries = list();
679                    if !entries.iter().any(|e| e.name == *name) {
680                        return Err(format!("not found in dynamic dir: {}", name));
681                    }
682
683                    // Resolve the child and walk remaining components through it.
684                    let remaining = &components[i + 1..];
685                    return self.resolve_dynamic_leaf(resolve.as_ref(), name, remaining);
686                }
687                _ => {
688                    return Err(format!("not a directory: {}", components[..i].join("/")));
689                }
690            }
691        }
692
693        // Walked all static components.
694        let full_path = static_path.join("/");
695        let qid = match current {
696            SyntheticNode::Dir { .. } | SyntheticNode::DynamicDir { .. } => {
697                SyntheticQid::dir(&full_path)
698            }
699            _ => SyntheticQid::file(&full_path),
700        };
701        Ok((qid, ResolvedNode::Static(static_path)))
702    }
703
704    /// Resolve a leaf node through a dynamic dir by walking remaining components
705    /// through a freshly-resolved subtree, returning the leaf as an owned Dynamic node.
706    fn resolve_dynamic_leaf(
707        &self,
708        resolve: &dyn Fn(&str) -> Option<SyntheticNode>,
709        parent_name: &str,
710        remaining: &[String],
711    ) -> Result<(SyntheticQid, ResolvedNode), String> {
712        let subtree = resolve(parent_name).ok_or("cannot resolve dynamic child")?;
713
714        // Walk remaining components through the subtree.
715        let mut current = subtree;
716        for (i, name) in remaining.iter().enumerate() {
717            match current {
718                SyntheticNode::Dir { mut children } => {
719                    current = children
720                        .remove(name)
721                        .ok_or_else(|| format!("not found: {}", name))?;
722                }
723                _ => return Err(format!("not a directory at: {}", remaining[..i].join("/"))),
724            }
725        }
726
727        let full_path = remaining.join("/");
728        let qid = match &current {
729            SyntheticNode::Dir { .. } | SyntheticNode::DynamicDir { .. } => {
730                SyntheticQid::dir(&full_path)
731            }
732            _ => SyntheticQid::file(&full_path),
733        };
734        Ok((qid, ResolvedNode::Dynamic(current)))
735    }
736
737    fn resolve_node<'a>(&'a self, path: &[String]) -> Option<&'a SyntheticNode> {
738        let mut current = &self.root;
739        for name in path {
740            match current {
741                SyntheticNode::Dir { children } => {
742                    current = children.get(name)?;
743                }
744                _ => return None,
745            }
746        }
747        Some(current)
748    }
749}
750
751/// Encode directory entries in the 9P wire format used by the registry.
752fn encode_dir_entries(entries: &[DirEntry], max_bytes: u32) -> Vec<u8> {
753    let mut wire = Vec::new();
754    for entry in entries {
755        let name_bytes = entry.name.as_bytes();
756        let entry_size = 4 + name_bytes.len() + 1 + 8; // name_len + name + is_dir + size
757        if wire.len() + entry_size > max_bytes as usize {
758            break;
759        }
760        wire.extend_from_slice(&(name_bytes.len() as u32).to_le_bytes());
761        wire.extend_from_slice(name_bytes);
762        wire.push(if entry.is_dir { 1 } else { 0 });
763        wire.extend_from_slice(&entry.size.to_le_bytes());
764    }
765    wire
766}
767
768// ─────────────────────────────────────────────────────────────────────────────
769// Mount implementation — bridges SyntheticTree to the VFS crate
770// ─────────────────────────────────────────────────────────────────────────────
771
772#[async_trait::async_trait]
773impl hyprstream_vfs::Mount for SyntheticTree {
774    async fn walk(
775        &self,
776        components: &[&str],
777        caller: &hyprstream_rpc::Subject,
778    ) -> Result<hyprstream_vfs::Fid, hyprstream_vfs::MountError> {
779        let wnames: Vec<String> = components.iter().map(|s| (*s).to_owned()).collect();
780        let owner = caller.to_string();
781        let (fid, _qid) = self
782            .walk(&wnames, &owner, None)
783            .map_err(hyprstream_vfs::MountError::NotFound)?;
784        Ok(hyprstream_vfs::Fid::new(fid))
785    }
786
787    async fn open(
788        &self,
789        fid: &mut hyprstream_vfs::Fid,
790        mode: u8,
791        caller: &hyprstream_rpc::Subject,
792    ) -> Result<(), hyprstream_vfs::MountError> {
793        let fid_u32 = *fid.downcast_ref::<u32>().ok_or_else(|| {
794            hyprstream_vfs::MountError::InvalidArgument("invalid fid type".into())
795        })?;
796        let owner = caller.to_string();
797        self.open(fid_u32, mode, &owner)
798            .map_err(hyprstream_vfs::MountError::Io)?;
799        Ok(())
800    }
801
802    async fn read(
803        &self,
804        fid: &hyprstream_vfs::Fid,
805        offset: u64,
806        count: u32,
807        caller: &hyprstream_rpc::Subject,
808    ) -> Result<Vec<u8>, hyprstream_vfs::MountError> {
809        let fid_u32 = *fid.downcast_ref::<u32>().ok_or_else(|| {
810            hyprstream_vfs::MountError::InvalidArgument("invalid fid type".into())
811        })?;
812        let owner = caller.to_string();
813
814        // Check for OneshotFile — requires async read. Extract the Arc<OneshotState>
815        // from the DashMap guard before awaiting to avoid holding !Send guard across .await.
816        {
817            let entry = self
818                .fid_table
819                .get_verified(fid_u32, &owner)
820                .map_err(|e| hyprstream_vfs::MountError::Io(e.to_owned()))?;
821            if let FidState::Opened { resolved, .. } = &entry.state {
822                let node = match resolved {
823                    ResolvedNode::Static(path) => self.resolve_node(path),
824                    ResolvedNode::Dynamic(node) => Some(node),
825                };
826                if let Some(SyntheticNode::OneshotFile(state)) = node {
827                    let state = Arc::clone(state);
828                    drop(entry); // Drop DashMap guard before await.
829                    let data = state.read().await.map_err(hyprstream_vfs::MountError::Io)?;
830                    let start = std::cmp::min(offset as usize, data.len());
831                    let end = std::cmp::min(start + count as usize, data.len());
832                    return Ok(data[start..end].to_vec());
833                }
834            }
835        }
836
837        // Non-async path (ReadFile, WatchFile, Dir, CtlFile response buffer, etc.)
838        self.read(fid_u32, offset, count, &owner)
839            .map_err(hyprstream_vfs::MountError::Io)
840    }
841
842    async fn write(
843        &self,
844        fid: &hyprstream_vfs::Fid,
845        offset: u64,
846        data: &[u8],
847        caller: &hyprstream_rpc::Subject,
848    ) -> Result<u32, hyprstream_vfs::MountError> {
849        let fid_u32 = *fid.downcast_ref::<u32>().ok_or_else(|| {
850            hyprstream_vfs::MountError::InvalidArgument("invalid fid type".into())
851        })?;
852        let owner = caller.to_string();
853
854        // Check for AsyncCtlFile — requires async handler. Extract handler, drop guard, await.
855        {
856            let entry = self
857                .fid_table
858                .get_verified(fid_u32, &owner)
859                .map_err(|e| hyprstream_vfs::MountError::Io(e.to_owned()))?;
860            if let FidState::Opened { resolved, mode, .. } = &entry.state {
861                let base_mode = *mode & 0x03;
862                if base_mode != hyprstream_vfs::OWRITE && base_mode != hyprstream_vfs::ORDWR {
863                    return Err(hyprstream_vfs::MountError::Io(
864                        "fid not open for writing".to_owned(),
865                    ));
866                }
867                let node = match resolved {
868                    ResolvedNode::Static(path) => self.resolve_node(path),
869                    ResolvedNode::Dynamic(node) => Some(node),
870                };
871                if let Some(SyntheticNode::AsyncCtlFile { handler }) = node {
872                    let fut = handler(data.to_vec(), caller.clone());
873                    let written = data.len() as u32;
874                    drop(entry); // Release DashMap guard before await.
875                    let result = fut.await.map_err(hyprstream_vfs::MountError::Io)?;
876                    // Re-acquire guard to write response buffer. If the fid was
877                    // clunked during the await, the handler already ran (side-effect
878                    // committed) but nobody will read the response — return Ok(written)
879                    // since the write itself succeeded.
880                    if let Ok(entry) = self.fid_table.get_verified(fid_u32, &owner) {
881                        if let FidState::Opened { response_buf, .. } = &entry.state {
882                            let mut buf = response_buf.lock();
883                            buf.clear();
884                            let cap = Self::MAX_RESPONSE_BUF.min(result.len());
885                            buf.extend(&result[..cap]);
886                        }
887                    }
888                    return Ok(written);
889                }
890            }
891        }
892
893        // Non-async path (sync CtlFile, etc.)
894        self.write(fid_u32, offset, data, &owner, caller)
895            .map_err(hyprstream_vfs::MountError::Io)
896    }
897
898    async fn readdir(
899        &self,
900        fid: &hyprstream_vfs::Fid,
901        caller: &hyprstream_rpc::Subject,
902    ) -> Result<Vec<hyprstream_vfs::DirEntry>, hyprstream_vfs::MountError> {
903        let fid_u32 = *fid.downcast_ref::<u32>().ok_or_else(|| {
904            hyprstream_vfs::MountError::InvalidArgument("invalid fid type".into())
905        })?;
906        let entries = self
907            .readdir_entries(fid_u32, &caller.to_string())
908            .map_err(hyprstream_vfs::MountError::Io)?;
909        Ok(entries)
910    }
911
912    async fn stat(
913        &self,
914        fid: &hyprstream_vfs::Fid,
915        caller: &hyprstream_rpc::Subject,
916    ) -> Result<hyprstream_vfs::Stat, hyprstream_vfs::MountError> {
917        let fid_u32 = *fid.downcast_ref::<u32>().ok_or_else(|| {
918            hyprstream_vfs::MountError::InvalidArgument("invalid fid type".into())
919        })?;
920        let (qid, name) = self
921            .stat(fid_u32, &caller.to_string())
922            .map_err(hyprstream_vfs::MountError::Io)?;
923        Ok(hyprstream_vfs::Stat {
924            qtype: qid.qtype,
925            // SyntheticQid version is a constant (no change-detection); path is
926            // fnv64 of the path string (non-cryptographic, rename-mutable). Both
927            // are threaded for surface soundness — see the qid invariant on
928            // `hyprstream_vfs::Stat`. A content-CID qid lands in #387.
929            version: qid.version,
930            path: qid.path,
931            size: 0,
932            name,
933            mtime: 0,
934        })
935    }
936
937    async fn clunk(&self, fid: hyprstream_vfs::Fid, caller: &hyprstream_rpc::Subject) {
938        if let Some(fid_u32) = fid.downcast_ref::<u32>() {
939            self.clunk(*fid_u32, &caller.to_string());
940        }
941    }
942}
943
944// ─────────────────────────────────────────────────────────────────────────────
945// Tests
946// ─────────────────────────────────────────────────────────────────────────────
947
948#[cfg(test)]
949#[allow(clippy::unwrap_used, clippy::expect_used)]
950mod tests {
951    use super::*;
952    use crate::services::types::OREAD;
953    use hyprstream_vfs::OWRITE;
954
955    fn make_tree() -> SyntheticTree {
956        let mut children = HashMap::new();
957        children.insert(
958            "status".to_owned(),
959            SyntheticNode::ReadFile(Box::new(|| b"loaded\n".to_vec())),
960        );
961        children.insert(
962            "ctl".to_owned(),
963            SyntheticNode::CtlFile {
964                handler: Box::new(|data, _subject| {
965                    let cmd = String::from_utf8_lossy(data);
966                    Ok(format!("ok: {}", cmd.trim()).into_bytes())
967                }),
968            },
969        );
970
971        let mut root_children = HashMap::new();
972        root_children.insert("test-model".to_owned(), SyntheticNode::Dir { children });
973
974        SyntheticTree::new(SyntheticNode::Dir {
975            children: root_children,
976        })
977    }
978
979    #[test]
980    fn walk_and_read_file() {
981        let tree = make_tree();
982        let (fid, qid) = tree
983            .walk(&["test-model".into(), "status".into()], "alice", None)
984            .unwrap();
985        assert_eq!(qid.qtype, QTFILE);
986        tree.open(fid, OREAD, "alice").unwrap();
987        let data = tree.read(fid, 0, 1024, "alice").unwrap();
988        assert_eq!(data, b"loaded\n");
989        tree.clunk(fid, "alice");
990    }
991
992    #[test]
993    fn walk_root_and_readdir() {
994        let tree = make_tree();
995        let (fid, qid) = tree.walk(&[], "alice", None).unwrap();
996        assert_eq!(qid.qtype, QTDIR);
997        tree.open(fid, OREAD, "alice").unwrap();
998        let data = tree.read(fid, 0, 4096, "alice").unwrap();
999        assert!(!data.is_empty()); // Should contain "test-model" entry.
1000        tree.clunk(fid, "alice");
1001    }
1002
1003    #[test]
1004    fn ctl_write_then_read() {
1005        let tree = make_tree();
1006        let (fid, _) = tree
1007            .walk(&["test-model".into(), "ctl".into()], "alice", None)
1008            .unwrap();
1009        tree.open(fid, OWRITE, "alice").unwrap();
1010        let written = tree
1011            .write(
1012                fid,
1013                0,
1014                b"load",
1015                "alice",
1016                &hyprstream_rpc::Subject::new("alice"),
1017            )
1018            .unwrap();
1019        assert_eq!(written, 4);
1020        // Read the response.
1021        let resp = tree.read(fid, 0, 1024, "alice").unwrap();
1022        assert_eq!(resp, b"ok: load");
1023        tree.clunk(fid, "alice");
1024    }
1025
1026    #[test]
1027    fn fid_ownership_enforced() {
1028        let tree = make_tree();
1029        let (fid, _) = tree
1030            .walk(&["test-model".into(), "status".into()], "alice", None)
1031            .unwrap();
1032        assert!(tree.open(fid, OREAD, "bob").is_err());
1033        tree.clunk(fid, "alice");
1034    }
1035
1036    #[test]
1037    fn walk_not_found() {
1038        let tree = make_tree();
1039        assert!(tree.walk(&["nonexistent".into()], "alice", None).is_err());
1040    }
1041
1042    #[test]
1043    fn stat_returns_qid() {
1044        let tree = make_tree();
1045        let (fid, _) = tree
1046            .walk(&["test-model".into(), "status".into()], "alice", None)
1047            .unwrap();
1048        let (qid, _name) = tree.stat(fid, "alice").unwrap();
1049        assert_eq!(qid.qtype, QTFILE);
1050        tree.clunk(fid, "alice");
1051    }
1052
1053    #[test]
1054    fn dynamic_dir() {
1055        let tree = SyntheticTree::new(SyntheticNode::DynamicDir {
1056            list: Box::new(|| {
1057                vec![
1058                    DirEntry {
1059                        name: "model-a".into(),
1060                        is_dir: true,
1061                        size: 0,
1062                        stat: None,
1063                    },
1064                    DirEntry {
1065                        name: "model-b".into(),
1066                        is_dir: true,
1067                        size: 0,
1068                        stat: None,
1069                    },
1070                ]
1071            }),
1072            resolve: Box::new(|_name| {
1073                let mut children = HashMap::new();
1074                children.insert(
1075                    "status".to_owned(),
1076                    SyntheticNode::ReadFile(Box::new(|| b"loaded\n".to_vec())),
1077                );
1078                Some(SyntheticNode::Dir { children })
1079            }),
1080        });
1081
1082        // Walk into dynamic dir root.
1083        let (fid, qid) = tree.walk(&[], "alice", None).unwrap();
1084        assert_eq!(qid.qtype, QTDIR);
1085        tree.open(fid, OREAD, "alice").unwrap();
1086        let data = tree.read(fid, 0, 4096, "alice").unwrap();
1087        assert!(!data.is_empty());
1088        tree.clunk(fid, "alice");
1089
1090        // Walk to a dynamic child's file.
1091        let (fid2, qid2) = tree
1092            .walk(&["model-a".into(), "status".into()], "alice", None)
1093            .unwrap();
1094        assert_eq!(qid2.qtype, QTFILE);
1095        tree.open(fid2, OREAD, "alice").unwrap();
1096        let content = tree.read(fid2, 0, 1024, "alice").unwrap();
1097        assert_eq!(content, b"loaded\n");
1098        tree.clunk(fid2, "alice");
1099    }
1100
1101    // ── VFS integration tests ───────────────────────────────────────────────
1102
1103    #[tokio::test]
1104    async fn vfs_cat_reads_synthetic_file() {
1105        use hyprstream_vfs::{Namespace, Subject};
1106        use std::sync::Arc;
1107
1108        let tree = make_tree();
1109        let mut ns = Namespace::new();
1110        ns.mount("/srv/model", Arc::new(tree)).unwrap();
1111
1112        let caller = Subject::new("alice");
1113        let data = ns
1114            .cat("/srv/model/test-model/status", &caller)
1115            .await
1116            .unwrap();
1117        assert_eq!(data, b"loaded\n");
1118    }
1119
1120    #[tokio::test]
1121    async fn vfs_ctl_writes_and_reads_response() {
1122        use hyprstream_vfs::{Namespace, Subject};
1123        use std::sync::Arc;
1124
1125        let tree = make_tree();
1126        let mut ns = Namespace::new();
1127        ns.mount("/srv/model", Arc::new(tree)).unwrap();
1128
1129        let caller = Subject::new("alice");
1130
1131        // ctl: write command + read response in one fid lifecycle.
1132        let resp = ns
1133            .ctl("/srv/model/test-model/ctl", b"load", &caller)
1134            .await
1135            .unwrap();
1136        assert_eq!(resp, b"ok: load");
1137    }
1138
1139    #[tokio::test]
1140    async fn vfs_ls_lists_directory() {
1141        use hyprstream_vfs::{Namespace, Subject};
1142        use std::sync::Arc;
1143
1144        let tree = make_tree();
1145        let mut ns = Namespace::new();
1146        ns.mount("/srv/model", Arc::new(tree)).unwrap();
1147
1148        let caller = Subject::new("alice");
1149        let entries = ns.ls("/srv/model/test-model", &caller).await.unwrap();
1150        let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
1151        assert!(names.contains(&"status"));
1152        assert!(names.contains(&"ctl"));
1153    }
1154
1155    #[tokio::test]
1156    async fn vfs_dynamic_dir_with_namespace() {
1157        use hyprstream_vfs::{Namespace, Subject};
1158        use std::sync::Arc;
1159
1160        // Build a dynamic tree (like the model service would).
1161        let tree = SyntheticTree::new(SyntheticNode::DynamicDir {
1162            list: Box::new(|| {
1163                vec![DirEntry {
1164                    name: "qwen3:main".into(),
1165                    is_dir: true,
1166                    size: 0,
1167                    stat: None,
1168                }]
1169            }),
1170            resolve: Box::new(|_name| {
1171                let mut children = HashMap::new();
1172                children.insert(
1173                    "status".to_owned(),
1174                    SyntheticNode::ReadFile(Box::new(|| b"loaded\n".to_vec())),
1175                );
1176                children.insert(
1177                    "defaults".to_owned(),
1178                    SyntheticNode::ReadFile(Box::new(|| b"{\"temperature\": 0.7}\n".to_vec())),
1179                );
1180                children.insert(
1181                    "ctl".to_owned(),
1182                    SyntheticNode::CtlFile {
1183                        handler: Box::new(|data, _subject| {
1184                            let cmd = String::from_utf8_lossy(data);
1185                            Ok(format!("ctl: {}\n", cmd.trim()).into_bytes())
1186                        }),
1187                    },
1188                );
1189                Some(SyntheticNode::Dir { children })
1190            }),
1191        });
1192
1193        let mut ns = Namespace::new();
1194        ns.mount("/srv/model", Arc::new(tree)).unwrap();
1195
1196        let caller = Subject::new("alice");
1197
1198        // Read model status through the VFS.
1199        let status = ns
1200            .cat("/srv/model/qwen3:main/status", &caller)
1201            .await
1202            .unwrap();
1203        assert_eq!(status, b"loaded\n");
1204
1205        // Read model defaults.
1206        let defaults = ns
1207            .cat("/srv/model/qwen3:main/defaults", &caller)
1208            .await
1209            .unwrap();
1210        assert!(defaults.starts_with(b"{\"temperature\""));
1211
1212        // Write to ctl and read response (single fid lifecycle).
1213        let resp = ns
1214            .ctl("/srv/model/qwen3:main/ctl", b"load", &caller)
1215            .await
1216            .unwrap();
1217        assert_eq!(resp, b"ctl: load\n");
1218    }
1219
1220    #[tokio::test]
1221    async fn vfs_tenant_isolation() {
1222        use hyprstream_vfs::{Namespace, Subject};
1223        use std::sync::Arc;
1224
1225        let tree = make_tree();
1226        let mut ns = Namespace::new();
1227        ns.mount("/srv/model", Arc::new(tree)).unwrap();
1228
1229        let alice = Subject::new("alice");
1230        let bob = Subject::new("bob");
1231
1232        // Both tenants can read (cat does walk+open+read+clunk atomically).
1233        let data_a = ns
1234            .cat("/srv/model/test-model/status", &alice)
1235            .await
1236            .unwrap();
1237        let data_b = ns.cat("/srv/model/test-model/status", &bob).await.unwrap();
1238        assert_eq!(data_a, data_b);
1239        assert_eq!(data_a, b"loaded\n");
1240    }
1241
1242    #[tokio::test]
1243    async fn vfs_namespace_fork_isolation() {
1244        use hyprstream_vfs::{Namespace, Subject};
1245        use std::sync::Arc;
1246
1247        let tree = make_tree();
1248        let mut ns = Namespace::new();
1249        ns.mount("/srv/model", Arc::new(tree)).unwrap();
1250        ns.mount(
1251            "/srv/worker",
1252            Arc::new(SyntheticTree::new(SyntheticNode::Dir {
1253                children: HashMap::new(),
1254            })),
1255        )
1256        .unwrap();
1257
1258        let caller = Subject::new("alice");
1259
1260        // Fork and restrict.
1261        let mut sandbox = ns.fork();
1262        let _ = sandbox.unmount("/srv/worker");
1263
1264        // Parent can access both.
1265        assert!(ns
1266            .cat("/srv/model/test-model/status", &caller)
1267            .await
1268            .is_ok());
1269        assert!(ns.ls("/srv/worker", &caller).await.is_ok());
1270
1271        // Child can access model but not worker.
1272        assert!(sandbox
1273            .cat("/srv/model/test-model/status", &caller)
1274            .await
1275            .is_ok());
1276        assert!(sandbox.ls("/srv/worker", &caller).await.is_err());
1277    }
1278
1279    // ── Phase 3: Channel-backed variant tests ─────────────────────────────
1280
1281    #[tokio::test]
1282    async fn watch_file_returns_latest_value() {
1283        use hyprstream_vfs::{Namespace, Subject};
1284
1285        let (tx, _rx) = tokio::sync::watch::channel(bytes::Bytes::from_static(b"initial"));
1286        let mut children = HashMap::new();
1287        children.insert("status".to_owned(), SyntheticNode::WatchFile(tx.clone()));
1288        let tree = SyntheticTree::new(SyntheticNode::Dir { children });
1289
1290        let mut ns = Namespace::new();
1291        ns.mount("/srv", Arc::new(tree)).unwrap();
1292        let caller = Subject::new("alice");
1293
1294        // Read initial value.
1295        let data = ns.cat("/srv/status", &caller).await.unwrap();
1296        assert_eq!(data, b"initial");
1297
1298        // Update via sender.
1299        tx.send(bytes::Bytes::from_static(b"updated")).unwrap();
1300
1301        // Read updated value.
1302        let data = ns.cat("/srv/status", &caller).await.unwrap();
1303        assert_eq!(data, b"updated");
1304    }
1305
1306    #[tokio::test]
1307    async fn oneshot_file_resolves_once() {
1308        use hyprstream_vfs::{Namespace, Subject};
1309
1310        let (state, sender) = OneshotState::new();
1311        let mut children = HashMap::new();
1312        children.insert("result".to_owned(), SyntheticNode::OneshotFile(state));
1313        let tree = SyntheticTree::new(SyntheticNode::Dir { children });
1314
1315        let mut ns = Namespace::new();
1316        ns.mount("/srv", Arc::new(tree)).unwrap();
1317        let caller = Subject::new("alice");
1318
1319        // Send the value.
1320        sender.send(bytes::Bytes::from_static(b"done")).unwrap();
1321
1322        // First read resolves the oneshot.
1323        let data = ns.cat("/srv/result", &caller).await.unwrap();
1324        assert_eq!(data, b"done");
1325
1326        // Second read returns the same cached value.
1327        let data = ns.cat("/srv/result", &caller).await.unwrap();
1328        assert_eq!(data, b"done");
1329    }
1330
1331    #[tokio::test]
1332    async fn async_ctl_file_round_trip() {
1333        use hyprstream_vfs::{Namespace, Subject};
1334
1335        let mut children = HashMap::new();
1336        children.insert(
1337            "ctl".to_owned(),
1338            SyntheticNode::AsyncCtlFile {
1339                handler: Box::new(|data, _subject| {
1340                    Box::pin(async move {
1341                        let cmd = String::from_utf8_lossy(&data);
1342                        Ok(format!("async: {}", cmd.trim()).into_bytes())
1343                    })
1344                }),
1345            },
1346        );
1347        let tree = SyntheticTree::new(SyntheticNode::Dir { children });
1348
1349        let mut ns = Namespace::new();
1350        ns.mount("/srv", Arc::new(tree)).unwrap();
1351        let caller = Subject::new("alice");
1352
1353        let resp = ns.ctl("/srv/ctl", b"ping", &caller).await.unwrap();
1354        assert_eq!(resp, b"async: ping");
1355    }
1356}