diff --git a/vortex-io/src/filesystem/glob.rs b/vortex-io/src/filesystem/glob.rs index 030bf4f56d1..b7a87a3b7ac 100644 --- a/vortex-io/src/filesystem/glob.rs +++ b/vortex-io/src/filesystem/glob.rs @@ -40,7 +40,13 @@ impl dyn FileSystem + '_ { let glob_pattern = glob::Pattern::new(pattern) .map_err(|e| vortex_err!("Invalid glob pattern '{}': {}", pattern, e))?; - let listing_prefix = glob_list_prefix(pattern).trim_end_matches('/'); + let raw_prefix = glob_list_prefix(pattern); + let trimmed_prefix = raw_prefix.trim_end_matches('/'); + let listing_prefix = if trimmed_prefix.is_empty() && !raw_prefix.is_empty() { + "/" + } else { + trimmed_prefix + }; tracing::debug!( "Performing glob with pattern '{}' and listing prefix '{}'", @@ -92,6 +98,7 @@ mod tests { use async_trait::async_trait; use futures::TryStreamExt; + use parking_lot::Mutex; use vortex_error::vortex_panic; use super::*; @@ -249,4 +256,70 @@ mod tests { fn test_validate_glob_escaped_bracket() { assert!(validate_glob("path\\[test].txt").is_err()); } + + #[derive(Debug)] + struct RecordingListFileSystem { + recorded_prefixes: Mutex>, + paths: Vec<&'static str>, + } + + #[async_trait] + impl FileSystem for RecordingListFileSystem { + fn list(&self, prefix: &str) -> BoxStream<'_, VortexResult> { + self.recorded_prefixes.lock().push(prefix.to_string()); + let items: Vec<_> = self + .paths + .iter() + .filter(|p| { + if prefix.is_empty() { + !p.starts_with('/') + } else { + p.starts_with(prefix) + } + }) + .map(|p| { + Ok(FileListing { + path: (*p).to_string(), + size: Some(1), + }) + }) + .collect(); + stream::iter(items).boxed() + } + + async fn head(&self, _path: &str) -> VortexResult> { + vortex_panic!("head() should not be called") + } + + async fn open_read(&self, _path: &str) -> VortexResult> { + vortex_panic!("open_read() should not be called") + } + + async fn delete(&self, _path: &str) -> VortexResult<()> { + vortex_panic!("delete() should not be called") + } + } + + #[tokio::test] + async fn test_glob_preserves_root_slash_and_empty_listing_prefix() -> VortexResult<()> { + let fs = RecordingListFileSystem { + recorded_prefixes: Mutex::new(Vec::new()), + paths: vec![ + "/data-01/part.vortex", + "/other/skip.txt", + "a.vortex", + "notes.txt", + ], + }; + let fs_dyn: &dyn FileSystem = &fs; + + let abs: Vec<_> = fs_dyn.glob("/data-*/part.vortex")?.try_collect().await?; + let rel: Vec<_> = fs_dyn.glob("*.vortex")?.try_collect().await?; + assert_eq!(abs.len(), 1); + assert_eq!(abs[0].path, "/data-01/part.vortex"); + assert_eq!(rel.len(), 1); + assert_eq!(rel[0].path, "a.vortex"); + assert_eq!(*fs.recorded_prefixes.lock(), vec!["/", ""]); + Ok(()) + } } diff --git a/vortex-io/src/filesystem/prefix.rs b/vortex-io/src/filesystem/prefix.rs index d96f54cd9bb..9985e4ae925 100644 --- a/vortex-io/src/filesystem/prefix.rs +++ b/vortex-io/src/filesystem/prefix.rs @@ -25,8 +25,13 @@ pub struct PrefixFileSystem { impl PrefixFileSystem { pub fn new(inner: FileSystemRef, prefix: String) -> Self { - // Normalize to always have a trailing slash for clean concatenation. - let prefix = format!("{}/", prefix.trim_matches('/')); + // Leave empty prefixes empty so relative keys stay relative; normalize non-empty + // prefixes to a single trailing slash (preserving "/" for the filesystem root). + let prefix = if prefix.is_empty() { + String::new() + } else { + format!("{}/", prefix.trim_matches('/')) + }; Self { inner, prefix } } } @@ -83,3 +88,88 @@ impl dyn FileSystem + 'static { Arc::new(PrefixFileSystem::new(self, prefix)) } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use async_trait::async_trait; + use futures::TryStreamExt; + use futures::executor::block_on; + use futures::stream; + use parking_lot::Mutex; + use rstest::rstest; + use vortex_buffer::ByteBuffer; + use vortex_error::VortexResult; + + use super::*; + + #[derive(Debug, Default)] + struct RecordingFs { + calls: Mutex>, + } + + #[async_trait] + impl FileSystem for RecordingFs { + fn list(&self, prefix: &str) -> BoxStream<'_, VortexResult> { + self.calls.lock().push(("list", prefix.to_owned())); + stream::iter([Ok(FileListing { + path: format!("{prefix}a.vortex"), + size: Some(3), + })]) + .boxed() + } + + async fn head(&self, path: &str) -> VortexResult> { + self.calls.lock().push(("head", path.to_owned())); + Ok(Some(FileListing { + path: path.to_owned(), + size: Some(3), + })) + } + + async fn open_read(&self, path: &str) -> VortexResult> { + self.calls.lock().push(("open_read", path.to_owned())); + Ok(Arc::new(ByteBuffer::empty())) + } + + async fn delete(&self, path: &str) -> VortexResult<()> { + self.calls.lock().push(("delete", path.to_owned())); + Ok(()) + } + } + + #[rstest] + #[case::empty("", "", "a.vortex")] + #[case::root("/", "/", "/a.vortex")] + #[case::multi_root("///", "/", "/a.vortex")] + #[case::plain("data/v1", "data/v1/", "data/v1/a.vortex")] + #[case::slashed("///data/v1///", "data/v1/", "data/v1/a.vortex")] + fn test_prefix_delegation( + #[case] raw: &str, + #[case] expected_list: &str, + #[case] expected_key: &str, + ) -> VortexResult<()> { + block_on(async { + let inner = Arc::new(RecordingFs::default()); + let prefixed = (Arc::clone(&inner) as FileSystemRef).with_prefix(raw.to_owned()); + + let listed = prefixed.list("").try_collect::>().await?; + assert_eq!(listed[0].path, "a.vortex"); + assert_eq!(prefixed.head("a.vortex").await?.unwrap().path, "a.vortex"); + prefixed.open_read("/a.vortex").await?; + prefixed.delete("a.vortex").await?; + + assert_eq!( + inner.calls.lock().as_slice(), + [ + ("list", expected_list.to_owned()), + ("head", expected_key.to_owned()), + ("open_read", expected_key.to_owned()), + ("delete", expected_key.to_owned()), + ] + ); + Ok(()) + }) + } +} diff --git a/vortex-io/src/std_file/filesystem.rs b/vortex-io/src/std_file/filesystem.rs index 9c71be47516..6fe2520a218 100644 --- a/vortex-io/src/std_file/filesystem.rs +++ b/vortex-io/src/std_file/filesystem.rs @@ -38,16 +38,22 @@ impl StdFileSystem { } } -fn walk(dir: &Path, out: &mut Vec) -> io::Result<()> { +fn walk(dir: &Path, strip_dot: bool, out: &mut Vec) -> io::Result<()> { for entry in fs::read_dir(dir)? { let entry = entry?; let file_type = entry.file_type()?; if file_type.is_dir() { - walk(&entry.path(), out)?; + walk(&entry.path(), strip_dot, out)?; } else { let metadata = entry.metadata()?; + let entry_path = entry.path(); + let path = if strip_dot { + entry_path.strip_prefix(".").unwrap_or(&entry_path) + } else { + &entry_path + }; out.push(FileListing { - path: entry.path().to_string_lossy().into_owned(), + path: path.to_string_lossy().into_owned(), size: Some(metadata.len()), }); } @@ -58,10 +64,14 @@ fn walk(dir: &Path, out: &mut Vec) -> io::Result<()> { #[async_trait] impl FileSystem for StdFileSystem { fn list(&self, prefix: &str) -> BoxStream<'_, VortexResult> { - let dir = PathBuf::from(prefix); + let (dir, strip_dot) = if prefix.is_empty() { + (PathBuf::from("."), true) + } else { + (PathBuf::from(prefix), false) + }; let listing = self.handle.spawn_blocking(move || { let mut out = Vec::new(); - walk(&dir, &mut out)?; + walk(&dir, strip_dot, &mut out)?; Ok::<_, io::Error>(out) }); stream::once(listing) @@ -105,3 +115,40 @@ impl FileSystem for StdFileSystem { Ok(()) } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use futures::TryStreamExt; + use vortex_error::VortexResult; + + use super::*; + use crate::filesystem::FileSystemRef; + use crate::runtime::BlockingRuntime; + use crate::runtime::current::CurrentThreadRuntime; + + #[test] + fn test_std_fs_empty_prefix_list_strips_dot() -> VortexResult<()> { + let runtime = CurrentThreadRuntime::new(); + let fs_ref: FileSystemRef = Arc::new(StdFileSystem::new(runtime.handle())); + + runtime.block_on(async { + let listed = fs_ref.list("").try_collect::>().await?; + assert!( + listed + .iter() + .all(|l| !l.path.starts_with("./") && !l.path.starts_with(".\\")) + ); + let cargo_toml = fs_ref.head("Cargo.toml").await?.unwrap(); + let nested = Path::new("src") + .join("lib.rs") + .to_string_lossy() + .into_owned(); + let lib_rs = fs_ref.head(&nested).await?.unwrap(); + assert!(listed.contains(&cargo_toml)); + assert!(listed.contains(&lib_rs)); + Ok(()) + }) + } +}