Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 74 additions & 1 deletion vortex-io/src/filesystem/glob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
"/"
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
} else {
trimmed_prefix
};

tracing::debug!(
"Performing glob with pattern '{}' and listing prefix '{}'",
Expand Down Expand Up @@ -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::*;
Expand Down Expand Up @@ -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<Vec<String>>,
paths: Vec<&'static str>,
}

#[async_trait]
impl FileSystem for RecordingListFileSystem {
fn list(&self, prefix: &str) -> BoxStream<'_, VortexResult<FileListing>> {
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<Option<FileListing>> {
vortex_panic!("head() should not be called")
}

async fn open_read(&self, _path: &str) -> VortexResult<Arc<dyn VortexReadAt>> {
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",
],
};
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
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(())
}
}
94 changes: 92 additions & 2 deletions vortex-io/src/filesystem/prefix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
} else {
format!("{}/", prefix.trim_matches('/'))
};
Self { inner, prefix }
}
}
Expand Down Expand Up @@ -83,3 +88,88 @@ impl dyn FileSystem + 'static {
Arc::new(PrefixFileSystem::new(self, prefix))
}
}

#[cfg(test)]
mod tests {
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
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<Vec<(&'static str, String)>>,
}

#[async_trait]
impl FileSystem for RecordingFs {
fn list(&self, prefix: &str) -> BoxStream<'_, VortexResult<FileListing>> {
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<Option<FileListing>> {
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<Arc<dyn VortexReadAt>> {
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::<Vec<_>>().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(())
})
}
}
57 changes: 52 additions & 5 deletions vortex-io/src/std_file/filesystem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,22 @@ impl StdFileSystem {
}
}

fn walk(dir: &Path, out: &mut Vec<FileListing>) -> io::Result<()> {
fn walk(dir: &Path, strip_dot: bool, out: &mut Vec<FileListing>) -> 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()),
});
}
Expand All @@ -58,10 +64,14 @@ fn walk(dir: &Path, out: &mut Vec<FileListing>) -> io::Result<()> {
#[async_trait]
impl FileSystem for StdFileSystem {
fn list(&self, prefix: &str) -> BoxStream<'_, VortexResult<FileListing>> {
let dir = PathBuf::from(prefix);
let (dir, strip_dot) = if prefix.is_empty() {
(PathBuf::from("."), true)
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
} 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)
Expand Down Expand Up @@ -105,3 +115,40 @@ impl FileSystem for StdFileSystem {
Ok(())
}
}

#[cfg(test)]
mod tests {
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
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::<Vec<_>>().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));
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
assert!(listed.contains(&lib_rs));
Ok(())
})
}
}
Loading