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::traits::{DirEntry, EntryType, Filesystem, Metadata};
6use async_trait::async_trait;
7use std::collections::BTreeMap;
8use std::io;
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12/// Information about a mount point.
13#[derive(Debug, Clone)]
14pub struct MountInfo {
15    /// The mount path (e.g., "/mnt/project").
16    pub path: PathBuf,
17    /// Whether this mount is read-only.
18    pub read_only: bool,
19}
20
21/// Routes filesystem operations to mounted backends.
22///
23/// Mount points are matched by longest prefix. For example, if `/mnt` and
24/// `/mnt/project` are both mounted, a path like `/mnt/project/src/main.rs`
25/// will be routed to the `/mnt/project` mount.
26#[derive(Default)]
27pub struct VfsRouter {
28    /// Mount points, keyed by path. Uses BTreeMap for ordered iteration.
29    mounts: BTreeMap<PathBuf, Arc<dyn Filesystem>>,
30}
31
32impl std::fmt::Debug for VfsRouter {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        f.debug_struct("VfsRouter")
35            .field("mounts", &self.mounts.keys().collect::<Vec<_>>())
36            .finish()
37    }
38}
39
40impl VfsRouter {
41    /// Create a new empty VFS router.
42    pub fn new() -> Self {
43        Self {
44            mounts: BTreeMap::new(),
45        }
46    }
47
48    /// Mount a filesystem at the given path.
49    ///
50    /// The path should be absolute (start with `/`). If a filesystem is
51    /// already mounted at this path, it will be replaced.
52    pub fn mount(&mut self, path: impl Into<PathBuf>, fs: impl Filesystem + 'static) {
53        let path = Self::normalize_mount_path(path.into());
54        self.mounts.insert(path, Arc::new(fs));
55    }
56
57    /// Mount a filesystem (already wrapped in Arc) at the given path.
58    pub fn mount_arc(&mut self, path: impl Into<PathBuf>, fs: Arc<dyn Filesystem>) {
59        let path = Self::normalize_mount_path(path.into());
60        self.mounts.insert(path, fs);
61    }
62
63    /// Unmount the filesystem at the given path.
64    ///
65    /// Returns `true` if a mount was removed, `false` if nothing was mounted there.
66    pub fn unmount(&mut self, path: impl AsRef<Path>) -> bool {
67        let path = Self::normalize_mount_path(path.as_ref().to_path_buf());
68        self.mounts.remove(&path).is_some()
69    }
70
71    /// List all current mounts.
72    pub fn list_mounts(&self) -> Vec<MountInfo> {
73        self.mounts
74            .iter()
75            .map(|(path, fs)| MountInfo {
76                path: path.clone(),
77                read_only: fs.read_only(),
78            })
79            .collect()
80    }
81
82    /// Normalize a mount path: ensure it starts with `/` and has no trailing slash.
83    fn normalize_mount_path(path: PathBuf) -> PathBuf {
84        let s = path.to_string_lossy();
85        let s = s.trim_end_matches('/');
86        if s.is_empty() {
87            PathBuf::from("/")
88        } else if !s.starts_with('/') {
89            PathBuf::from(format!("/{}", s))
90        } else {
91            PathBuf::from(s)
92        }
93    }
94
95    /// Resolve a VFS path to a real filesystem path.
96    ///
97    /// Returns `Some(path)` if the VFS path maps to a real filesystem (like LocalFs),
98    /// or `None` if the path is in a virtual filesystem (like MemoryFs).
99    ///
100    /// This is needed for tools like `git` that must use real paths with external libraries.
101    pub fn resolve_real_path(&self, path: &Path) -> Option<PathBuf> {
102        let (fs, relative) = self.find_mount(path).ok()?;
103        fs.real_path(&relative)
104    }
105
106    /// Find the mount point for a given path.
107    ///
108    /// Returns the mount and the path relative to that mount.
109    fn find_mount(&self, path: &Path) -> io::Result<(Arc<dyn Filesystem>, PathBuf)> {
110        let path_str = path.to_string_lossy();
111        let normalized = if path_str.starts_with('/') {
112            path.to_path_buf()
113        } else {
114            PathBuf::from(format!("/{}", path_str))
115        };
116
117        // Find longest matching mount point
118        let mut best_match: Option<(&PathBuf, &Arc<dyn Filesystem>)> = None;
119
120        for (mount_path, fs) in &self.mounts {
121            let mount_str = mount_path.to_string_lossy();
122
123            // Check if the path starts with this mount point
124            let is_match = if mount_str == "/" {
125                true // Root matches everything
126            } else {
127                let normalized_str = normalized.to_string_lossy();
128                normalized_str == mount_str.as_ref()
129                    || normalized_str.starts_with(&format!("{}/", mount_str))
130            };
131
132            if is_match {
133                // Keep the longest match
134                let dominated = best_match
135                    .as_ref()
136                    .is_none_or(|(bp, _)| mount_path.as_os_str().len() > bp.as_os_str().len());
137                if dominated {
138                    best_match = Some((mount_path, fs));
139                }
140            }
141        }
142
143        match best_match {
144            Some((mount_path, fs)) => {
145                // Calculate relative path
146                let mount_str = mount_path.to_string_lossy();
147                let normalized_str = normalized.to_string_lossy();
148
149                let relative = if mount_str == "/" {
150                    normalized_str.trim_start_matches('/').to_string()
151                } else {
152                    normalized_str
153                        .strip_prefix(mount_str.as_ref())
154                        .unwrap_or("")
155                        .trim_start_matches('/')
156                        .to_string()
157                };
158
159                Ok((Arc::clone(fs), PathBuf::from(relative)))
160            }
161            None => Err(io::Error::new(
162                io::ErrorKind::NotFound,
163                format!("no mount point for path: {}", path.display()),
164            )),
165        }
166    }
167}
168
169#[async_trait]
170impl Filesystem for VfsRouter {
171    async fn read(&self, path: &Path) -> io::Result<Vec<u8>> {
172        let (fs, relative) = self.find_mount(path)?;
173        fs.read(&relative).await
174    }
175
176    async fn write(&self, path: &Path, data: &[u8]) -> io::Result<()> {
177        let (fs, relative) = self.find_mount(path)?;
178        fs.write(&relative, data).await
179    }
180
181    async fn list(&self, path: &Path) -> io::Result<Vec<DirEntry>> {
182        // Special case: listing root might need to show mount points
183        let path_str = path.to_string_lossy();
184        if path_str.is_empty() || path_str == "/" {
185            return self.list_root().await;
186        }
187
188        let (fs, relative) = self.find_mount(path)?;
189        fs.list(&relative).await
190    }
191
192    async fn stat(&self, path: &Path) -> io::Result<Metadata> {
193        // Special case: root always exists
194        let path_str = path.to_string_lossy();
195        if path_str.is_empty() || path_str == "/" {
196            return Ok(Metadata {
197                is_dir: true,
198                is_file: false,
199                is_symlink: false,
200                size: 0,
201                modified: None,
202            });
203        }
204
205        // Check if path is a mount point itself
206        let normalized = Self::normalize_mount_path(path.to_path_buf());
207        if self.mounts.contains_key(&normalized) {
208            return Ok(Metadata {
209                is_dir: true,
210                is_file: false,
211                is_symlink: false,
212                size: 0,
213                modified: None,
214            });
215        }
216
217        let (fs, relative) = self.find_mount(path)?;
218        fs.stat(&relative).await
219    }
220
221    async fn read_link(&self, path: &Path) -> io::Result<PathBuf> {
222        let (fs, relative) = self.find_mount(path)?;
223        fs.read_link(&relative).await
224    }
225
226    async fn symlink(&self, target: &Path, link: &Path) -> io::Result<()> {
227        let (fs, relative) = self.find_mount(link)?;
228        fs.symlink(target, &relative).await
229    }
230
231    async fn lstat(&self, path: &Path) -> io::Result<Metadata> {
232        // Special case: root always exists
233        let path_str = path.to_string_lossy();
234        if path_str.is_empty() || path_str == "/" {
235            return Ok(Metadata {
236                is_dir: true,
237                is_file: false,
238                is_symlink: false,
239                size: 0,
240                modified: None,
241            });
242        }
243
244        // Check if path is a mount point itself
245        let normalized = Self::normalize_mount_path(path.to_path_buf());
246        if self.mounts.contains_key(&normalized) {
247            return Ok(Metadata {
248                is_dir: true,
249                is_file: false,
250                is_symlink: false,
251                size: 0,
252                modified: None,
253            });
254        }
255
256        let (fs, relative) = self.find_mount(path)?;
257        fs.lstat(&relative).await
258    }
259
260    async fn mkdir(&self, path: &Path) -> io::Result<()> {
261        let (fs, relative) = self.find_mount(path)?;
262        fs.mkdir(&relative).await
263    }
264
265    async fn remove(&self, path: &Path) -> io::Result<()> {
266        let (fs, relative) = self.find_mount(path)?;
267        fs.remove(&relative).await
268    }
269
270    async fn rename(&self, from: &Path, to: &Path) -> io::Result<()> {
271        let (from_fs, from_relative) = self.find_mount(from)?;
272        let (to_fs, to_relative) = self.find_mount(to)?;
273
274        // Check if both paths are on the same mount by comparing Arc pointers
275        if !Arc::ptr_eq(&from_fs, &to_fs) {
276            return Err(io::Error::new(
277                io::ErrorKind::Unsupported,
278                "cannot rename across different mount points",
279            ));
280        }
281
282        from_fs.rename(&from_relative, &to_relative).await
283    }
284
285    fn read_only(&self) -> bool {
286        // Router itself isn't read-only; individual mounts might be
287        false
288    }
289}
290
291impl VfsRouter {
292    /// List the root directory, synthesizing entries from mount points.
293    async fn list_root(&self) -> io::Result<Vec<DirEntry>> {
294        let mut entries = Vec::new();
295        let mut seen_names = std::collections::HashSet::new();
296
297        for mount_path in self.mounts.keys() {
298            let mount_str = mount_path.to_string_lossy();
299            if mount_str == "/" {
300                // Root mount: list its contents directly
301                if let Some(fs) = self.mounts.get(mount_path)
302                    && let Ok(root_entries) = fs.list(Path::new("")).await {
303                        for entry in root_entries {
304                            if seen_names.insert(entry.name.clone()) {
305                                entries.push(entry);
306                            }
307                        }
308                    }
309            } else {
310                // Non-root mount: extract first path component
311                let first_component = mount_str
312                    .trim_start_matches('/')
313                    .split('/')
314                    .next()
315                    .unwrap_or("");
316
317                if !first_component.is_empty() && seen_names.insert(first_component.to_string()) {
318                    entries.push(DirEntry {
319                        name: first_component.to_string(),
320                        entry_type: EntryType::Directory,
321                        size: 0,
322                        symlink_target: None,
323                    });
324                }
325            }
326        }
327
328        entries.sort_by(|a, b| a.name.cmp(&b.name));
329        Ok(entries)
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336    use crate::vfs::MemoryFs;
337
338    #[tokio::test]
339    async fn test_basic_mount() {
340        let mut router = VfsRouter::new();
341        let scratch = MemoryFs::new();
342        scratch.write(Path::new("test.txt"), b"hello").await.unwrap();
343        router.mount("/scratch", scratch);
344
345        let data = router.read(Path::new("/scratch/test.txt")).await.unwrap();
346        assert_eq!(data, b"hello");
347    }
348
349    #[tokio::test]
350    async fn test_multiple_mounts() {
351        let mut router = VfsRouter::new();
352
353        let scratch = MemoryFs::new();
354        scratch.write(Path::new("a.txt"), b"scratch").await.unwrap();
355        router.mount("/scratch", scratch);
356
357        let data = MemoryFs::new();
358        data.write(Path::new("b.txt"), b"data").await.unwrap();
359        router.mount("/data", data);
360
361        assert_eq!(
362            router.read(Path::new("/scratch/a.txt")).await.unwrap(),
363            b"scratch"
364        );
365        assert_eq!(
366            router.read(Path::new("/data/b.txt")).await.unwrap(),
367            b"data"
368        );
369    }
370
371    #[tokio::test]
372    async fn test_nested_mount() {
373        let mut router = VfsRouter::new();
374
375        let outer = MemoryFs::new();
376        outer.write(Path::new("outer.txt"), b"outer").await.unwrap();
377        router.mount("/mnt", outer);
378
379        let inner = MemoryFs::new();
380        inner.write(Path::new("inner.txt"), b"inner").await.unwrap();
381        router.mount("/mnt/project", inner);
382
383        // /mnt/outer.txt should come from outer mount
384        assert_eq!(
385            router.read(Path::new("/mnt/outer.txt")).await.unwrap(),
386            b"outer"
387        );
388
389        // /mnt/project/inner.txt should come from inner mount
390        assert_eq!(
391            router.read(Path::new("/mnt/project/inner.txt")).await.unwrap(),
392            b"inner"
393        );
394    }
395
396    #[tokio::test]
397    async fn test_list_root() {
398        let mut router = VfsRouter::new();
399        router.mount("/scratch", MemoryFs::new());
400        router.mount("/mnt/a", MemoryFs::new());
401        router.mount("/mnt/b", MemoryFs::new());
402
403        let entries = router.list(Path::new("/")).await.unwrap();
404        let names: Vec<_> = entries.iter().map(|e| &e.name).collect();
405
406        assert!(names.contains(&&"scratch".to_string()));
407        assert!(names.contains(&&"mnt".to_string()));
408    }
409
410    #[tokio::test]
411    async fn test_unmount() {
412        let mut router = VfsRouter::new();
413
414        let fs = MemoryFs::new();
415        fs.write(Path::new("test.txt"), b"data").await.unwrap();
416        router.mount("/scratch", fs);
417
418        assert!(router.read(Path::new("/scratch/test.txt")).await.is_ok());
419
420        router.unmount("/scratch");
421
422        assert!(router.read(Path::new("/scratch/test.txt")).await.is_err());
423    }
424
425    #[tokio::test]
426    async fn test_list_mounts() {
427        let mut router = VfsRouter::new();
428        router.mount("/scratch", MemoryFs::new());
429        router.mount("/data", MemoryFs::new());
430
431        let mounts = router.list_mounts();
432        assert_eq!(mounts.len(), 2);
433
434        let paths: Vec<_> = mounts.iter().map(|m| &m.path).collect();
435        assert!(paths.contains(&&PathBuf::from("/scratch")));
436        assert!(paths.contains(&&PathBuf::from("/data")));
437    }
438
439    #[tokio::test]
440    async fn test_no_mount_error() {
441        let router = VfsRouter::new();
442        let result = router.read(Path::new("/nothing/here.txt")).await;
443        assert!(result.is_err());
444        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::NotFound);
445    }
446
447    #[tokio::test]
448    async fn test_root_mount() {
449        let mut router = VfsRouter::new();
450
451        let root = MemoryFs::new();
452        root.write(Path::new("at-root.txt"), b"root file").await.unwrap();
453        router.mount("/", root);
454
455        let data = router.read(Path::new("/at-root.txt")).await.unwrap();
456        assert_eq!(data, b"root file");
457    }
458
459    #[tokio::test]
460    async fn test_write_through_router() {
461        let mut router = VfsRouter::new();
462        router.mount("/scratch", MemoryFs::new());
463
464        router
465            .write(Path::new("/scratch/new.txt"), b"created")
466            .await
467            .unwrap();
468
469        let data = router.read(Path::new("/scratch/new.txt")).await.unwrap();
470        assert_eq!(data, b"created");
471    }
472
473    #[tokio::test]
474    async fn test_stat_mount_point() {
475        let mut router = VfsRouter::new();
476        router.mount("/scratch", MemoryFs::new());
477
478        let meta = router.stat(Path::new("/scratch")).await.unwrap();
479        assert!(meta.is_dir);
480    }
481
482    #[tokio::test]
483    async fn test_stat_root() {
484        let router = VfsRouter::new();
485        let meta = router.stat(Path::new("/")).await.unwrap();
486        assert!(meta.is_dir);
487    }
488
489    #[tokio::test]
490    async fn test_rename_same_mount() {
491        let mut router = VfsRouter::new();
492        let mem = MemoryFs::new();
493        mem.write(Path::new("old.txt"), b"data").await.unwrap();
494        router.mount("/scratch", mem);
495
496        router.rename(Path::new("/scratch/old.txt"), Path::new("/scratch/new.txt")).await.unwrap();
497
498        // New path exists
499        let data = router.read(Path::new("/scratch/new.txt")).await.unwrap();
500        assert_eq!(data, b"data");
501
502        // Old path doesn't exist
503        assert!(!router.exists(Path::new("/scratch/old.txt")).await);
504    }
505
506    #[tokio::test]
507    async fn test_rename_cross_mount_fails() {
508        let mut router = VfsRouter::new();
509        let mem1 = MemoryFs::new();
510        mem1.write(Path::new("file.txt"), b"data").await.unwrap();
511        router.mount("/mount1", mem1);
512        router.mount("/mount2", MemoryFs::new());
513
514        let result = router.rename(Path::new("/mount1/file.txt"), Path::new("/mount2/file.txt")).await;
515        assert!(result.is_err());
516        assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Unsupported);
517    }
518}