Skip to main content

kaish_kernel/vfs/
router.rs

1//! VFS router for mount point management.
2//!
3//! Routes filesystem operations to the appropriate backend based on path.
4
5use super::{DirEntry, Filesystem};
6use async_trait::async_trait;
7use std::collections::BTreeMap;
8use std::io;
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12// `MountInfo` now lives in kaish-types::backend (pure data, part of the
13// KernelBackend contract). Re-exported here so existing `vfs::MountInfo`
14// paths keep working.
15pub use kaish_types::backend::MountInfo;
16
17/// Routes filesystem operations to mounted backends.
18///
19/// Mount points are matched by longest prefix. For example, if `/mnt` and
20/// `/mnt/project` are both mounted, a path like `/mnt/project/src/main.rs`
21/// will be routed to the `/mnt/project` mount.
22#[derive(Default)]
23pub struct VfsRouter {
24    /// Mount points, keyed by path. Uses BTreeMap for ordered iteration.
25    mounts: BTreeMap<PathBuf, Arc<dyn Filesystem>>,
26}
27
28impl std::fmt::Debug for VfsRouter {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("VfsRouter")
31            .field("mounts", &self.mounts.keys().collect::<Vec<_>>())
32            .finish()
33    }
34}
35
36impl VfsRouter {
37    /// Create a new empty VFS router.
38    pub fn new() -> Self {
39        Self {
40            mounts: BTreeMap::new(),
41        }
42    }
43
44    /// Mount a filesystem at the given path.
45    ///
46    /// The path should be absolute (start with `/`). If a filesystem is
47    /// already mounted at this path, it will be replaced.
48    pub fn mount(&mut self, path: impl Into<PathBuf>, fs: impl Filesystem + 'static) {
49        let path = Self::normalize_mount_path(path.into());
50        self.mounts.insert(path, Arc::new(fs));
51    }
52
53    /// Mount a filesystem (already wrapped in Arc) at the given path.
54    pub fn mount_arc(&mut self, path: impl Into<PathBuf>, fs: Arc<dyn Filesystem>) {
55        let path = Self::normalize_mount_path(path.into());
56        self.mounts.insert(path, fs);
57    }
58
59    /// Unmount the filesystem at the given path.
60    ///
61    /// Returns `true` if a mount was removed, `false` if nothing was mounted there.
62    pub fn unmount(&mut self, path: impl AsRef<Path>) -> bool {
63        let path = Self::normalize_mount_path(path.as_ref().to_path_buf());
64        self.mounts.remove(&path).is_some()
65    }
66
67    /// List all current mounts.
68    pub fn list_mounts(&self) -> Vec<MountInfo> {
69        self.mounts
70            .iter()
71            .map(|(path, fs)| MountInfo {
72                path: path.clone(),
73                read_only: fs.read_only(),
74                resident_bytes: fs.resident_bytes(),
75            })
76            .collect()
77    }
78
79    /// Normalize a mount path: ensure it starts with `/` and has no trailing slash.
80    fn normalize_mount_path(path: PathBuf) -> PathBuf {
81        let s = path.to_string_lossy();
82        let s = s.trim_end_matches('/');
83        if s.is_empty() {
84            PathBuf::from("/")
85        } else if !s.starts_with('/') {
86            PathBuf::from(format!("/{}", s))
87        } else {
88            PathBuf::from(s)
89        }
90    }
91
92    /// Resolve a VFS path to a real filesystem path.
93    ///
94    /// Returns `Some(path)` if the VFS path maps to a real filesystem (like LocalFs),
95    /// or `None` if the path is in a virtual filesystem (like MemoryFs).
96    ///
97    /// This is needed for tools like `git` that must use real paths with external libraries.
98    pub fn resolve_real_path(&self, path: &Path) -> Option<PathBuf> {
99        let (fs, relative) = self.find_mount(path).ok()?;
100        fs.real_path(&relative)
101    }
102
103    /// Returns true if some registered mount covers this path.
104    ///
105    /// Used by embedder overlay backends (`VirtualOverlayBackend`) to decide
106    /// whether a path belongs to this router's mounts or should be delegated
107    /// to the embedder's own backend — without hardcoding a mount prefix.
108    pub(crate) fn has_mount(&self, path: &Path) -> bool {
109        self.find_mount(path).is_ok()
110    }
111
112    /// Returns true if some mount lives strictly *below* `dir` — i.e. `dir` is a
113    /// proper ancestor of a mount point (`has_mount_under("/v")` is true when
114    /// `/v/jobs` is mounted, even though nothing is mounted at `/v` itself).
115    ///
116    /// Distinct from `has_mount`, which is true only when `dir` is *covered* by
117    /// a mount. Together they let an overlay treat an intermediate path like
118    /// `/v` as an existing directory (the union of its child mounts) while still
119    /// delegating unclaimed leaves to the embedder's backend.
120    pub(crate) fn has_mount_under(&self, dir: &Path) -> bool {
121        let dir = Self::normalize_mount_path(dir.to_path_buf());
122        let dir_str = dir.to_string_lossy();
123        self.mounts.keys().any(|mount_path| {
124            let mount_str = mount_path.to_string_lossy();
125            if dir_str == "/" {
126                mount_str != "/"
127            } else {
128                mount_str.starts_with(&format!("{}/", dir_str))
129            }
130        })
131    }
132
133    /// Synthesize the child directory entries of `dir` from the mount roster:
134    /// the first path component below `dir` of every mount that lives under it
135    /// (`/v` over mounts `/v/jobs`, `/v/blobs` → `blobs`, `jobs`). `dir` is
136    /// expected to be a non-root ancestor with no mount of its own; root is
137    /// handled by `list_root`, which also folds in a `/` mount's real contents.
138    fn list_mount_children(&self, dir: &Path) -> Vec<DirEntry> {
139        let dir = Self::normalize_mount_path(dir.to_path_buf());
140        let prefix = format!("{}/", dir.to_string_lossy());
141        let mut seen = std::collections::HashSet::new();
142        let mut entries = Vec::new();
143        for mount_path in self.mounts.keys() {
144            let mount_str = mount_path.to_string_lossy();
145            if let Some(rest) = mount_str.strip_prefix(&prefix) {
146                let first = rest.split('/').next().unwrap_or("");
147                if !first.is_empty() && seen.insert(first.to_string()) {
148                    entries.push(DirEntry::directory(first));
149                }
150            }
151        }
152        entries.sort_by(|a, b| a.name.cmp(&b.name));
153        entries
154    }
155
156    /// The final path component, for naming a synthesized directory entry
157    /// (`/v` → `v`). Falls back to `/` for a path with no component.
158    fn path_basename(path: &Path) -> String {
159        path.file_name()
160            .map(|n| n.to_string_lossy().into_owned())
161            .unwrap_or_else(|| "/".to_string())
162    }
163
164    /// Find the mount point for a given path.
165    ///
166    /// Returns the mount and the path relative to that mount.
167    fn find_mount(&self, path: &Path) -> io::Result<(Arc<dyn Filesystem>, PathBuf)> {
168        let path_str = path.to_string_lossy();
169        let normalized = if path_str.starts_with('/') {
170            path.to_path_buf()
171        } else {
172            PathBuf::from(format!("/{}", path_str))
173        };
174
175        // Find longest matching mount point
176        let mut best_match: Option<(&PathBuf, &Arc<dyn Filesystem>)> = None;
177
178        for (mount_path, fs) in &self.mounts {
179            let mount_str = mount_path.to_string_lossy();
180
181            // Check if the path starts with this mount point
182            let is_match = if mount_str == "/" {
183                true // Root matches everything
184            } else {
185                let normalized_str = normalized.to_string_lossy();
186                normalized_str == mount_str.as_ref()
187                    || normalized_str.starts_with(&format!("{}/", mount_str))
188            };
189
190            if is_match {
191                // Keep the longest match
192                let dominated = best_match
193                    .as_ref()
194                    .is_none_or(|(bp, _)| mount_path.as_os_str().len() > bp.as_os_str().len());
195                if dominated {
196                    best_match = Some((mount_path, fs));
197                }
198            }
199        }
200
201        match best_match {
202            Some((mount_path, fs)) => {
203                // Calculate relative path
204                let mount_str = mount_path.to_string_lossy();
205                let normalized_str = normalized.to_string_lossy();
206
207                let relative = if mount_str == "/" {
208                    normalized_str.trim_start_matches('/').to_string()
209                } else {
210                    normalized_str
211                        .strip_prefix(mount_str.as_ref())
212                        .unwrap_or("")
213                        .trim_start_matches('/')
214                        .to_string()
215                };
216
217                Ok((Arc::clone(fs), PathBuf::from(relative)))
218            }
219            None => Err(io::Error::new(
220                io::ErrorKind::NotFound,
221                format!("no mount point for path: {}", path.display()),
222            )),
223        }
224    }
225}
226
227#[async_trait]
228impl Filesystem for VfsRouter {
229    #[tracing::instrument(level = "trace", skip(self), fields(path = %path.display()))]
230    async fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
231        let (fs, relative) = self.find_mount(path)?;
232        fs.read(&relative).await
233    }
234
235    #[tracing::instrument(level = "trace", skip(self), fields(path = %path.display()))]
236    async fn read_range(
237        &self,
238        path: &Path,
239        range: Option<kaish_vfs::ReadRange>,
240    ) -> io::Result<Vec<u8>> {
241        // Forward the range to the mount so range-aware backends (e.g. DevFs's
242        // /dev/zero) see the requested byte count. Falling through to the trait
243        // default would call our own `read` (whole file) and slice afterwards,
244        // which would hang or error on an infinite device.
245        let (fs, relative) = self.find_mount(path)?;
246        fs.read_range(&relative, range).await
247    }
248
249    #[tracing::instrument(level = "trace", skip(self, data), fields(path = %path.display(), size = data.len()))]
250    async fn write(&self, path: &Path, data: &[u8]) -> io::Result<()> {
251        let (fs, relative) = self.find_mount(path)?;
252        fs.write(&relative, data).await
253    }
254
255    #[tracing::instrument(level = "trace", skip(self), fields(path = %path.display()))]
256    async fn list(&self, path: &Path) -> io::Result<Vec<DirEntry>> {
257        // Special case: listing root might need to show mount points
258        let path_str = path.to_string_lossy();
259        if path_str.is_empty() || path_str == "/" {
260            return self.list_root().await;
261        }
262
263        match self.find_mount(path) {
264            Ok((fs, relative)) => fs.list(&relative).await,
265            // Not covered by a mount, but an ancestor of one (e.g. `/v` above
266            // `/v/jobs`): synthesize its child mount directories rather than 404.
267            Err(e) => {
268                if self.has_mount_under(path) {
269                    Ok(self.list_mount_children(path))
270                } else {
271                    Err(e)
272                }
273            }
274        }
275    }
276
277    #[tracing::instrument(level = "trace", skip(self), fields(path = %path.display()))]
278    async fn stat(&self, path: &Path) -> io::Result<DirEntry> {
279        // Special case: root always exists
280        let path_str = path.to_string_lossy();
281        if path_str.is_empty() || path_str == "/" {
282            return Ok(DirEntry::directory("/"));
283        }
284
285        // Check if path is a mount point itself
286        let normalized = Self::normalize_mount_path(path.to_path_buf());
287        if self.mounts.contains_key(&normalized) {
288            let name = path
289                .file_name()
290                .map(|n| n.to_string_lossy().into_owned())
291                .unwrap_or_else(|| "/".to_string());
292            return Ok(DirEntry::directory(name));
293        }
294
295        match self.find_mount(path) {
296            Ok((fs, relative)) => fs.stat(&relative).await,
297            // Intermediate ancestor of a mount (e.g. `/v` above `/v/jobs`)
298            // exists as a synthesized directory.
299            Err(e) => {
300                if self.has_mount_under(path) {
301                    Ok(DirEntry::directory(Self::path_basename(path)))
302                } else {
303                    Err(e)
304                }
305            }
306        }
307    }
308
309    async fn read_link(&self, path: &Path) -> io::Result<PathBuf> {
310        let (fs, relative) = self.find_mount(path)?;
311        fs.read_link(&relative).await
312    }
313
314    async fn symlink(&self, target: &Path, link: &Path) -> io::Result<()> {
315        let (fs, relative) = self.find_mount(link)?;
316        fs.symlink(target, &relative).await
317    }
318
319    async fn lstat(&self, path: &Path) -> io::Result<DirEntry> {
320        // Special case: root always exists
321        let path_str = path.to_string_lossy();
322        if path_str.is_empty() || path_str == "/" {
323            return Ok(DirEntry::directory("/"));
324        }
325
326        // Check if path is a mount point itself
327        let normalized = Self::normalize_mount_path(path.to_path_buf());
328        if self.mounts.contains_key(&normalized) {
329            let name = path
330                .file_name()
331                .map(|n| n.to_string_lossy().into_owned())
332                .unwrap_or_else(|| "/".to_string());
333            return Ok(DirEntry::directory(name));
334        }
335
336        match self.find_mount(path) {
337            Ok((fs, relative)) => fs.lstat(&relative).await,
338            // Intermediate ancestor of a mount (e.g. `/v` above `/v/jobs`)
339            // exists as a synthesized directory.
340            Err(e) => {
341                if self.has_mount_under(path) {
342                    Ok(DirEntry::directory(Self::path_basename(path)))
343                } else {
344                    Err(e)
345                }
346            }
347        }
348    }
349
350    async fn mkdir(&self, path: &Path) -> io::Result<()> {
351        let (fs, relative) = self.find_mount(path)?;
352        fs.mkdir(&relative).await
353    }
354
355    async fn set_mtime(&self, path: &Path, mtime: std::time::SystemTime) -> io::Result<()> {
356        let (fs, relative) = self.find_mount(path)?;
357        fs.set_mtime(&relative, mtime).await
358    }
359
360    async fn remove(&self, path: &Path) -> io::Result<()> {
361        let (fs, relative) = self.find_mount(path)?;
362        fs.remove(&relative).await
363    }
364
365    async fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
366        let (from_fs, from_relative) = self.find_mount(from)?;
367        let (to_fs, to_relative) = self.find_mount(to)?;
368
369        // Check if both paths are on the same mount by comparing Arc pointers
370        if !Arc::ptr_eq(&from_fs, &to_fs) {
371            return Err(io::Error::new(
372                io::ErrorKind::Unsupported,
373                "cannot rename across different mount points",
374            ));
375        }
376
377        from_fs.rename(&from_relative, &to_relative).await
378    }
379
380    fn read_only(&self) -> bool {
381        // Router is read-only iff every mount is. Empty router returns
382        // false — a router with no mounts isn't meaningfully read-only,
383        // and false preserves the behaviour callers saw before this change.
384        if self.mounts.is_empty() {
385            return false;
386        }
387        self.mounts.values().all(|fs| fs.read_only())
388    }
389}
390
391impl VfsRouter {
392    /// List the root directory, synthesizing entries from mount points.
393    async fn list_root(&self) -> io::Result<Vec<DirEntry>> {
394        let mut entries = Vec::new();
395        let mut seen_names = std::collections::HashSet::new();
396
397        for mount_path in self.mounts.keys() {
398            let mount_str = mount_path.to_string_lossy();
399            if mount_str == "/" {
400                // Root mount: list its contents directly
401                if let Some(fs) = self.mounts.get(mount_path)
402                    && let Ok(root_entries) = fs.list(Path::new("")).await {
403                        for entry in root_entries {
404                            if seen_names.insert(entry.name.clone()) {
405                                entries.push(entry);
406                            }
407                        }
408                    }
409            } else {
410                // Non-root mount: extract first path component
411                let first_component = mount_str
412                    .trim_start_matches('/')
413                    .split('/')
414                    .next()
415                    .unwrap_or("");
416
417                if !first_component.is_empty() && seen_names.insert(first_component.to_string()) {
418                    entries.push(DirEntry::directory(first_component));
419                }
420            }
421        }
422
423        entries.sort_by(|a, b| a.name.cmp(&b.name));
424        Ok(entries)
425    }
426}
427
428#[cfg(test)]
429mod tests {
430    use super::*;
431    use crate::vfs::MemoryFs;
432
433    #[tokio::test]
434    async fn test_basic_mount() {
435        let mut router = VfsRouter::new();
436        let scratch = MemoryFs::new();
437        scratch.write(Path::new("test.txt"), b"hello").await.unwrap();
438        router.mount("/scratch", scratch);
439
440        let data = router.read(Path::new("/scratch/test.txt")).await.unwrap();
441        assert_eq!(data, b"hello");
442    }
443
444    #[tokio::test]
445    async fn test_multiple_mounts() {
446        let mut router = VfsRouter::new();
447
448        let scratch = MemoryFs::new();
449        scratch.write(Path::new("a.txt"), b"scratch").await.unwrap();
450        router.mount("/scratch", scratch);
451
452        let data = MemoryFs::new();
453        data.write(Path::new("b.txt"), b"data").await.unwrap();
454        router.mount("/data", data);
455
456        assert_eq!(
457            router.read(Path::new("/scratch/a.txt")).await.unwrap(),
458            b"scratch"
459        );
460        assert_eq!(
461            router.read(Path::new("/data/b.txt")).await.unwrap(),
462            b"data"
463        );
464    }
465
466    #[tokio::test]
467    async fn test_nested_mount() {
468        let mut router = VfsRouter::new();
469
470        let outer = MemoryFs::new();
471        outer.write(Path::new("outer.txt"), b"outer").await.unwrap();
472        router.mount("/mnt", outer);
473
474        let inner = MemoryFs::new();
475        inner.write(Path::new("inner.txt"), b"inner").await.unwrap();
476        router.mount("/mnt/project", inner);
477
478        // /mnt/outer.txt should come from outer mount
479        assert_eq!(
480            router.read(Path::new("/mnt/outer.txt")).await.unwrap(),
481            b"outer"
482        );
483
484        // /mnt/project/inner.txt should come from inner mount
485        assert_eq!(
486            router.read(Path::new("/mnt/project/inner.txt")).await.unwrap(),
487            b"inner"
488        );
489    }
490
491    #[tokio::test]
492    async fn test_list_root() {
493        let mut router = VfsRouter::new();
494        router.mount("/scratch", MemoryFs::new());
495        router.mount("/mnt/a", MemoryFs::new());
496        router.mount("/mnt/b", MemoryFs::new());
497
498        let entries = router.list(Path::new("/")).await.unwrap();
499        let names: Vec<_> = entries.iter().map(|e| &e.name).collect();
500
501        assert!(names.contains(&&"scratch".to_string()));
502        assert!(names.contains(&&"mnt".to_string()));
503    }
504
505    #[tokio::test]
506    async fn test_unmount() {
507        let mut router = VfsRouter::new();
508
509        let fs = MemoryFs::new();
510        fs.write(Path::new("test.txt"), b"data").await.unwrap();
511        router.mount("/scratch", fs);
512
513        assert!(router.read(Path::new("/scratch/test.txt")).await.is_ok());
514
515        router.unmount("/scratch");
516
517        assert!(router.read(Path::new("/scratch/test.txt")).await.is_err());
518    }
519
520    #[tokio::test]
521    async fn test_list_mounts() {
522        let mut router = VfsRouter::new();
523        router.mount("/scratch", MemoryFs::new());
524        router.mount("/data", MemoryFs::new());
525
526        let mounts = router.list_mounts();
527        assert_eq!(mounts.len(), 2);
528
529        let paths: Vec<_> = mounts.iter().map(|m| &m.path).collect();
530        assert!(paths.contains(&&PathBuf::from("/scratch")));
531        assert!(paths.contains(&&PathBuf::from("/data")));
532    }
533
534    #[tokio::test]
535    async fn test_no_mount_error() {
536        let router = VfsRouter::new();
537        let result = router.read(Path::new("/nothing/here.txt")).await;
538        assert!(result.is_err());
539        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotFound);
540    }
541
542    #[tokio::test]
543    async fn test_root_mount() {
544        let mut router = VfsRouter::new();
545
546        let root = MemoryFs::new();
547        root.write(Path::new("at-root.txt"), b"root file").await.unwrap();
548        router.mount("/", root);
549
550        let data = router.read(Path::new("/at-root.txt")).await.unwrap();
551        assert_eq!(data, b"root file");
552    }
553
554    #[tokio::test]
555    async fn test_write_through_router() {
556        let mut router = VfsRouter::new();
557        router.mount("/scratch", MemoryFs::new());
558
559        router
560            .write(Path::new("/scratch/new.txt"), b"created")
561            .await
562            .unwrap();
563
564        let data = router.read(Path::new("/scratch/new.txt")).await.unwrap();
565        assert_eq!(data, b"created");
566    }
567
568    #[tokio::test]
569    async fn test_stat_mount_point() {
570        let mut router = VfsRouter::new();
571        router.mount("/scratch", MemoryFs::new());
572
573        let entry = router.stat(Path::new("/scratch")).await.unwrap();
574        assert!(entry.is_dir());
575    }
576
577    #[tokio::test]
578    async fn test_stat_root() {
579        let router = VfsRouter::new();
580        let entry = router.stat(Path::new("/")).await.unwrap();
581        assert!(entry.is_dir());
582    }
583
584    #[tokio::test]
585    async fn test_rename_same_mount() {
586        let mut router = VfsRouter::new();
587        let mem = MemoryFs::new();
588        mem.write(Path::new("old.txt"), b"data").await.unwrap();
589        router.mount("/scratch", mem);
590
591        router.rename(Path::new("/scratch/old.txt"), Path::new("/scratch/new.txt")).await.unwrap();
592
593        // New path exists
594        let data = router.read(Path::new("/scratch/new.txt")).await.unwrap();
595        assert_eq!(data, b"data");
596
597        // Old path doesn't exist
598        assert!(!router.exists(Path::new("/scratch/old.txt")).await);
599    }
600
601    #[tokio::test]
602    async fn test_rename_cross_mount_fails() {
603        let mut router = VfsRouter::new();
604        let mem1 = MemoryFs::new();
605        mem1.write(Path::new("file.txt"), b"data").await.unwrap();
606        router.mount("/mount1", mem1);
607        router.mount("/mount2", MemoryFs::new());
608
609        let result = router.rename(Path::new("/mount1/file.txt"), Path::new("/mount2/file.txt")).await;
610        assert!(result.is_err());
611        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Unsupported);
612    }
613
614    #[tokio::test]
615    async fn read_only_empty_router_returns_false() {
616        let router = VfsRouter::new();
617        assert!(!router.read_only());
618    }
619
620    #[cfg(feature = "localfs")]
621    #[tokio::test]
622    async fn read_only_all_read_only_mounts_returns_true() {
623        use crate::vfs::LocalFs;
624
625        let t1 = tempfile::tempdir().unwrap();
626        let t2 = tempfile::tempdir().unwrap();
627
628        let mut router = VfsRouter::new();
629        router.mount("/a", LocalFs::read_only(t1.path().to_path_buf()));
630        router.mount("/b", LocalFs::read_only(t2.path().to_path_buf()));
631
632        assert!(router.read_only());
633    }
634
635    #[cfg(feature = "localfs")]
636    #[tokio::test]
637    async fn read_only_mixed_mounts_returns_false() {
638        use crate::vfs::LocalFs;
639
640        let t1 = tempfile::tempdir().unwrap();
641
642        let mut router = VfsRouter::new();
643        router.mount("/ro", LocalFs::read_only(t1.path().to_path_buf()));
644        router.mount("/rw", MemoryFs::new());
645
646        assert!(!router.read_only());
647    }
648
649    // An intermediate directory that has no mount of its own but sits *above*
650    // one or more mounts (e.g. `/v` over `/v/jobs`, `/v/blobs`) must present as
651    // a real, listable directory synthesized from the mount roster — not the
652    // `NotFound` the bare `find_mount` returns. This is what lets a kaish shell
653    // (and SFTP over the bare router) navigate `/v` when the mounts sit at
654    // `/v/*`, and it's the router half of the `/v` overlay-tuning fix.
655    #[tokio::test]
656    async fn test_list_synthesizes_intermediate_dir() {
657        let mut router = VfsRouter::new();
658        router.mount("/v/jobs", MemoryFs::new());
659        router.mount("/v/blobs", MemoryFs::new());
660
661        let entries = router.list(Path::new("/v")).await.unwrap();
662        let names: Vec<_> = entries.iter().map(|e| e.name.as_str()).collect();
663        assert_eq!(names, vec!["blobs", "jobs"]); // sorted, synthesized from mounts
664    }
665
666    #[tokio::test]
667    async fn test_stat_intermediate_dir_is_directory() {
668        let mut router = VfsRouter::new();
669        router.mount("/v/jobs", MemoryFs::new());
670
671        assert!(router.stat(Path::new("/v")).await.unwrap().is_dir());
672        assert!(router.lstat(Path::new("/v")).await.unwrap().is_dir());
673    }
674
675    #[tokio::test]
676    async fn test_deep_intermediate_dir() {
677        let mut router = VfsRouter::new();
678        router.mount("/v/etc/rc", MemoryFs::new());
679
680        let v: Vec<_> = router.list(Path::new("/v")).await.unwrap();
681        assert_eq!(v.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), vec!["etc"]);
682        let etc: Vec<_> = router.list(Path::new("/v/etc")).await.unwrap();
683        assert_eq!(etc.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), vec!["rc"]);
684        assert!(router.stat(Path::new("/v/etc")).await.unwrap().is_dir());
685    }
686
687    #[tokio::test]
688    async fn test_has_mount_under() {
689        let mut router = VfsRouter::new();
690        router.mount("/v/jobs", MemoryFs::new());
691
692        assert!(router.has_mount_under(Path::new("/v")));
693        assert!(router.has_mount_under(Path::new("/")));
694        // The mount point itself has nothing *below* it.
695        assert!(!router.has_mount_under(Path::new("/v/jobs")));
696        assert!(!router.has_mount_under(Path::new("/other")));
697    }
698
699    #[tokio::test]
700    async fn test_nonexistent_ancestor_still_notfound() {
701        let mut router = VfsRouter::new();
702        router.mount("/v/jobs", MemoryFs::new());
703
704        // A path with no mount at or below it stays NotFound — synthesis is
705        // only for genuine ancestors of a mount.
706        assert_eq!(
707            router.list(Path::new("/nope")).await.unwrap_err().kind(),
708            io::ErrorKind::NotFound
709        );
710        assert_eq!(
711            router.stat(Path::new("/nope")).await.unwrap_err().kind(),
712            io::ErrorKind::NotFound
713        );
714    }
715}