1use 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
12pub use kaish_types::backend::MountInfo;
16
17#[derive(Default)]
23pub struct VfsRouter {
24 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 pub fn new() -> Self {
39 Self {
40 mounts: BTreeMap::new(),
41 }
42 }
43
44 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 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 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 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 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 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 pub(crate) fn has_mount(&self, path: &Path) -> bool {
109 self.find_mount(path).is_ok()
110 }
111
112 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 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 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 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 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 let is_match = if mount_str == "/" {
183 true } 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 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 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 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 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 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 let path_str = path.to_string_lossy();
281 if path_str.is_empty() || path_str == "/" {
282 return Ok(DirEntry::directory("/"));
283 }
284
285 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 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 let path_str = path.to_string_lossy();
322 if path_str.is_empty() || path_str == "/" {
323 return Ok(DirEntry::directory("/"));
324 }
325
326 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 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 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 if self.mounts.is_empty() {
385 return false;
386 }
387 self.mounts.values().all(|fs| fs.read_only())
388 }
389}
390
391impl VfsRouter {
392 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 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 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 assert_eq!(
480 router.read(Path::new("/mnt/outer.txt")).await.unwrap(),
481 b"outer"
482 );
483
484 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 let data = router.read(Path::new("/scratch/new.txt")).await.unwrap();
595 assert_eq!(data, b"data");
596
597 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 #[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"]); }
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 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 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}