This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-object-store-dir-delete-timestamp-and-errors in repository https://gitbox.apache.org/repos/asf/opendal.git
commit 46a14919433528df339701a560e8156b4c077105 Author: Xuanwo <[email protected]> AuthorDate: Mon Nov 23 14:56:26 2026 +0100 fix(integrations/object_store): handle directory paths, pre-epoch timestamps, and same-path errors Object store keys cannot end with '/', and object_store::path::Path drops a trailing slash. Deleting 'foo/' therefore deleted the regular file 'foo', and stat('foo/') returned its metadata. Treat trailing-slash paths as directories: deletion is a successful no-op, stat returns directory metadata for the root and NotFound otherwise. jiff truncates as_second toward zero and reports a signed subsecond, so casting a negative subsecond to u32 made chrono reject every pre-epoch timestamp with a fractional second. Convert to a floor second and a non-negative nanosecond before calling chrono. Match object_store's same-path copy and rename contract: a create-only operation reports AlreadyExists when the source exists, and a missing source reports NotFound instead of leaking IsSameFile. Route get_ranges errors through the same directory-aware mapping as get and head. --- integrations/object_store/src/lib.rs | 56 +++++++- integrations/object_store/src/service/deleter.rs | 73 ++++++++-- integrations/object_store/src/service/mod.rs | 62 +++++++++ integrations/object_store/src/store.rs | 161 ++++++++++++++++++++--- 4 files changed, 325 insertions(+), 27 deletions(-) diff --git a/integrations/object_store/src/lib.rs b/integrations/object_store/src/lib.rs index 1170ab32bc..e54ae8c23a 100644 --- a/integrations/object_store/src/lib.rs +++ b/integrations/object_store/src/lib.rs @@ -122,12 +122,60 @@ mod assert_send { fn timestamp_to_datetime(ts: opendal::raw::Timestamp) -> Option<chrono::DateTime<chrono::Utc>> { let jiff_ts = ts.into_inner(); - chrono::DateTime::<chrono::Utc>::from_timestamp( - jiff_ts.as_second(), - jiff_ts.subsec_nanosecond() as u32, - ) + // `jiff` truncates `as_second` toward zero and reports a signed subsecond, + // so pre-epoch timestamps can carry a negative nanosecond. `chrono` expects + // a non-negative nanosecond component, borrowed from the preceding second. + let mut second = jiff_ts.as_second(); + let mut nanosecond = jiff_ts.subsec_nanosecond(); + if nanosecond < 0 { + second = second.checked_sub(1)?; + nanosecond += 1_000_000_000; + } + chrono::DateTime::<chrono::Utc>::from_timestamp(second, nanosecond as u32) } fn datetime_to_timestamp(dt: chrono::DateTime<chrono::Utc>) -> Option<opendal::raw::Timestamp> { opendal::raw::Timestamp::new(dt.timestamp(), dt.timestamp_subsec_nanos() as i32).ok() } + +#[cfg(test)] +mod timestamp_tests { + use super::*; + + fn timestamp(second: i64, nanosecond: i32) -> opendal::raw::Timestamp { + opendal::raw::Timestamp::new(second, nanosecond).expect("timestamp should be valid") + } + + #[test] + fn timestamp_to_datetime_handles_negative_subseconds() { + for (second, nanosecond) in [ + (0, -999_999_999), + (0, -500_000_000), + (-1, -999_999_999), + (-1, -500_000_000), + (-2, -1), + (0, 0), + (-1, 0), + (0, 500_000_000), + (1, 999_999_999), + ] { + let total_nanoseconds = i128::from(second) * 1_000_000_000 + i128::from(nanosecond); + let expected = chrono::DateTime::<chrono::Utc>::from_timestamp( + total_nanoseconds.div_euclid(1_000_000_000) as i64, + total_nanoseconds.rem_euclid(1_000_000_000) as u32, + ) + .expect("expected datetime should be valid"); + + let actual = timestamp_to_datetime(timestamp(second, nanosecond)) + .unwrap_or_else(|| panic!("({second}, {nanosecond}) should convert")); + assert_eq!(actual, expected, "({second}, {nanosecond})"); + } + } + + #[test] + fn timestamp_to_datetime_handles_supported_range() { + for ts in [opendal::raw::Timestamp::MIN, opendal::raw::Timestamp::MAX] { + assert!(timestamp_to_datetime(ts).is_some()); + } + } +} diff --git a/integrations/object_store/src/service/deleter.rs b/integrations/object_store/src/service/deleter.rs index 4aef3c88ea..d56dfaf485 100644 --- a/integrations/object_store/src/service/deleter.rs +++ b/integrations/object_store/src/service/deleter.rs @@ -92,8 +92,19 @@ fn error_path(error: &object_store::Error) -> Option<&str> { } } +/// Object store keys cannot end with `/`, and `object_store::path::Path::from` +/// drops a trailing slash. A directory path therefore has no marker object to +/// delete, and converting it would target the same-named regular file. +fn is_directory_path(path: &str) -> bool { + path.ends_with('/') +} + impl oio::BatchDelete for ObjectStoreDeleter { async fn delete_once(&self, path: String, _: OpDelete) -> Result<()> { + if is_directory_path(&path) { + return Ok(()); + } + let object_path = ObjectStorePath::from(path); match self.store.delete(&object_path).await { Ok(()) | Err(object_store::Error::NotFound { .. }) => Ok(()), @@ -102,13 +113,16 @@ impl oio::BatchDelete for ObjectStoreDeleter { } async fn delete_batch(&self, paths: Vec<(String, OpDelete)>) -> Result<BatchDeleteResult> { - let mut remaining = paths - .into_iter() - .map(|(path, args)| { - let object_path = ObjectStorePath::from(path.as_str()); - (object_path, path, args) - }) - .collect::<VecDeque<_>>(); + let mut remaining = VecDeque::new(); + let mut result_batch = BatchDeleteResult::default(); + for (path, args) in paths { + if is_directory_path(&path) { + result_batch.succeeded.push((path, args)); + continue; + } + remaining.push_back((ObjectStorePath::from(path.as_str()), path, args)); + } + let locations = remaining .iter() .map(|(path, _, _)| Ok::<_, object_store::Error>(path.clone())) @@ -116,7 +130,6 @@ impl oio::BatchDelete for ObjectStoreDeleter { let stream = stream::iter(locations).boxed(); let results = self.store.delete_stream(stream).collect::<Vec<_>>().await; - let mut result_batch = BatchDeleteResult::default(); let mut unattributed_error = None; let mut unmatched_not_found = 0; let mut unmatched_not_found_error = None; @@ -184,6 +197,7 @@ mod tests { use async_trait::async_trait; use futures::stream::BoxStream; use object_store::local::LocalFileSystem; + use object_store::memory::InMemory; use object_store::prefix::PrefixStore; use object_store::{ CopyOptions, GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, @@ -511,6 +525,49 @@ mod tests { ); } + #[tokio::test] + async fn test_delete_directory_path_keeps_same_named_file() { + let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); + store + .put(&ObjectStorePath::from("foo"), "file".into()) + .await + .unwrap(); + store + .put(&ObjectStorePath::from("foo/child"), "child".into()) + .await + .unwrap(); + let op = Operator::new(ObjectStoreBuilder::new(store)).unwrap(); + + op.delete("foo/").await.unwrap(); + assert!(op.stat("foo").await.unwrap().is_file()); + assert!(op.stat("foo/child").await.unwrap().is_file()); + + op.delete_iter(["foo/", "missing"]).await.unwrap(); + assert!(op.stat("foo").await.unwrap().is_file()); + assert!(op.stat("foo/child").await.unwrap().is_file()); + + op.delete_iter(["foo/", "bar/"]).await.unwrap(); + assert!(op.stat("foo").await.unwrap().is_file()); + assert!(op.stat("foo/child").await.unwrap().is_file()); + } + + #[tokio::test] + async fn test_delete_directory_and_root_paths_on_local_filesystem() { + let root = tempfile::tempdir().unwrap(); + let store: Arc<dyn ObjectStore> = + Arc::new(LocalFileSystem::new_with_prefix(root.path()).unwrap()); + store + .put(&ObjectStorePath::from("foo"), "file".into()) + .await + .unwrap(); + let op = Operator::new(ObjectStoreBuilder::new(store)).unwrap(); + + op.delete("/").await.unwrap(); + op.delete("foo/").await.unwrap(); + op.delete_iter(["/", "foo/"]).await.unwrap(); + assert!(op.stat("foo").await.unwrap().is_file()); + } + #[tokio::test] async fn test_local_filesystem_missing_deletes_are_idempotent() { let root = tempfile::tempdir().unwrap(); diff --git a/integrations/object_store/src/service/mod.rs b/integrations/object_store/src/service/mod.rs index fa37b51e20..3d2fa32a7e 100644 --- a/integrations/object_store/src/service/mod.rs +++ b/integrations/object_store/src/service/mod.rs @@ -138,6 +138,19 @@ impl Service for ObjectStoreService { } async fn stat(&self, _ctx: &OperationContext, path: &str, args: OpStat) -> Result<RpStat> { + // Object stores have no directory marker objects, and + // `object_store::path::Path` drops a trailing slash. Looking up `foo/` + // would otherwise report the metadata of the regular file `foo`. + if path == "/" { + return Ok(RpStat::new(MetadataBuilder::dir().build())); + } + if path.ends_with('/') { + return Err( + Error::new(ErrorKind::NotFound, "directory has no object metadata") + .with_context("path", path), + ); + } + let path = ObjectStorePath::from(path); let opts = parse_op_stat(&args)?; let result = self @@ -423,6 +436,55 @@ mod tests { assert!(result.is_err()); } + #[tokio::test] + async fn test_object_store_stat_directory_path_without_simulation() { + let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); + let backend = ObjectStoreBuilder::new(store) + .build() + .expect("build should succeed"); + let ctx = test_ctx(); + + for path in ["file", "nested/child"] { + let mut writer = backend + .write(&ctx, path, OpWrite::default()) + .expect("write should succeed"); + writer + .write(Buffer::from("content")) + .await + .expect("write content should succeed"); + writer.close().await.expect("close should succeed"); + } + + for path in ["file/", "nested/"] { + let err = backend + .stat(&ctx, path, OpStat::default()) + .await + .expect_err("stat of a directory path must not resolve to a file"); + assert_eq!(err.kind(), ErrorKind::NotFound, "path: {path}"); + } + + let meta = backend + .stat(&ctx, "/", OpStat::default()) + .await + .expect("stat of the root should succeed"); + assert!(meta.into_metadata().is_dir()); + } + + #[tokio::test] + async fn test_object_store_stat_directory_path_with_simulation() -> anyhow::Result<()> { + let op = new_object_store_operator(); + op.write("file", "content").await?; + op.write("nested/child", "content").await?; + + assert_eq!( + op.stat("file/").await.unwrap_err().kind(), + ErrorKind::NotFound + ); + assert!(op.stat("nested/").await?.is_dir()); + assert!(op.stat("/").await?.is_dir()); + Ok(()) + } + #[tokio::test] async fn test_object_store_backend_error_handling() { let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new()); diff --git a/integrations/object_store/src/store.rs b/integrations/object_store/src/store.rs index 24ade7ba68..30fe8758a4 100644 --- a/integrations/object_store/src/store.rs +++ b/integrations/object_store/src/store.rs @@ -598,6 +598,44 @@ impl OpendalStore { }) } + /// Resolve a copy or rename whose source and destination are the same. + /// + /// `object_store` implementations report `AlreadyExists` when a create-only + /// destination exists and `NotFound` when the source is missing. OpenDAL + /// rejects the call with `IsSameFile` before either can be evaluated, so + /// inspect the source and produce the corresponding result. An overwrite + /// onto the same path keeps the object in place. + async fn check_same_path(&self, path: &Path, if_not_exists: bool) -> object_store::Result<()> { + let exists = match self + .inner + .stat(&percent_decode_path(path.as_ref())) + .into_send() + .await + { + Ok(meta) if meta.is_file() => true, + Ok(_) => { + return Err(format_object_store_error( + opendal::Error::new(ErrorKind::IsADirectory, "source is a directory"), + path.as_ref(), + )); + } + Err(err) if err.kind() == ErrorKind::NotFound => false, + Err(err) => return Err(format_object_store_error(err, path.as_ref())), + }; + + match (if_not_exists, exists) { + (true, true) => Err(format_object_store_error( + opendal::Error::new(ErrorKind::AlreadyExists, "destination already exists"), + path.as_ref(), + )), + (true, false) | (false, false) => Err(format_object_store_error( + opendal::Error::new(ErrorKind::NotFound, "source does not exist"), + path.as_ref(), + )), + (false, true) => Ok(()), + } + } + /// Copy a file from one location to another async fn copy_request( &self, @@ -605,6 +643,10 @@ impl OpendalStore { to: &Path, if_not_exists: bool, ) -> object_store::Result<()> { + if from == to { + return self.check_same_path(from, if_not_exists).await; + } + let mut copy_options = CopyOptions::default(); if if_not_exists { copy_options.if_not_exists = true; @@ -854,14 +896,18 @@ impl ObjectStore for OpendalStore { } let raw_location = percent_decode_path(location.as_ref()); - let reader = self + let options = GetOptions::default(); + let reader = match self .inner .reader_with(&raw_location) .concurrent(DEFAULT_CONCURRENT) .gap(self.get_ranges_gap) .into_send() .await - .map_err(|err| format_object_store_error(err, location.as_ref()))?; + { + Ok(reader) => reader, + Err(err) => return Err(self.format_get_error(location, &options, err).await), + }; // Avoid a stat for normal ranges. An over-EOF fetch can fail either // range validation or OpenDAL's short-read check, so normalize and @@ -874,12 +920,12 @@ impl ObjectStore for OpendalStore { ErrorKind::RangeNotSatisfied | ErrorKind::Unexpected ) => { - let metadata = self - .inner - .stat(&raw_location) - .into_send() - .await - .map_err(|err| format_object_store_error(err, location.as_ref()))?; + let metadata = match self.inner.stat(&raw_location).into_send().await { + Ok(metadata) => metadata, + Err(err) => { + return Err(self.format_get_error(location, &options, err).await); + } + }; let normalized_ranges = ranges .iter() .map(|range| { @@ -891,15 +937,16 @@ impl ObjectStore for OpendalStore { .collect::<opendal::Result<Vec<_>>>() .map_err(|err| format_object_store_error(err, location.as_ref()))?; if normalized_ranges.as_slice() == ranges { - return Err(format_object_store_error(err, location.as_ref())); + return Err(self.format_get_error(location, &options, err).await); + } + match reader.fetch(normalized_ranges).into_send().await { + Ok(buffers) => buffers, + Err(err) => { + return Err(self.format_get_error(location, &options, err).await); + } } - reader - .fetch(normalized_ranges) - .into_send() - .await - .map_err(|err| format_object_store_error(err, location.as_ref()))? } - Err(err) => return Err(format_object_store_error(err, location.as_ref())), + Err(err) => return Err(self.format_get_error(location, &options, err).await), }; Ok(buffers.into_iter().map(|buf| buf.to_bytes()).collect()) @@ -1087,6 +1134,12 @@ impl ObjectStore for OpendalStore { to: &Path, options: RenameOptions, ) -> object_store::Result<()> { + if from == to { + return self + .check_same_path(from, options.target_mode == RenameTargetMode::Create) + .await; + } + let capability = self.info().capability(); let (supports_rename, copy_mode) = match options.target_mode { RenameTargetMode::Overwrite => (capability.rename, ObjectStoreCopyMode::Overwrite), @@ -1659,6 +1712,30 @@ mod tests { } } + #[tokio::test] + async fn test_get_ranges_directory_maps_to_not_found() -> anyhow::Result<()> { + let store = OpendalStore::new(Operator::new(services::Memory::default())?); + // `Path::parse` keeps the encoded segment, and `OpendalStore` decodes + // the location before forwarding it to OpenDAL, so this resolves to + // the directory path `dir/`. + let location = Path::parse("dir%2F")?; + + assert!(matches!( + store.get(&location).await.unwrap_err(), + object_store::Error::NotFound { .. } + )); + let range = 0..1; + let err = store + .get_ranges(&location, std::slice::from_ref(&range)) + .await + .unwrap_err(); + assert!( + matches!(err, object_store::Error::NotFound { .. }), + "unexpected error: {err:?}" + ); + Ok(()) + } + #[tokio::test] async fn test_get_opts_range_contract_matches_in_memory() { let store = OpendalStore::new(Operator::new(services::Memory::default()).unwrap()); @@ -1813,6 +1890,60 @@ mod tests { Ok(()) } + #[tokio::test] + async fn test_copy_same_path_matches_object_store_contract() -> anyhow::Result<()> { + let store = OpendalStore::new(Operator::new(services::Memory::default())?); + let location = Path::from("same-path-copy"); + + assert!(matches!( + store.copy(&location, &location).await.unwrap_err(), + object_store::Error::NotFound { path, .. } if path == location.as_ref() + )); + assert!(matches!( + store.copy_if_not_exists(&location, &location).await.unwrap_err(), + object_store::Error::NotFound { path, .. } if path == location.as_ref() + )); + + let content = Bytes::from_static(b"content"); + store.put(&location, content.clone().into()).await?; + + store.copy(&location, &location).await?; + assert_eq!(store.get(&location).await?.bytes().await?, content); + assert!(matches!( + store.copy_if_not_exists(&location, &location).await.unwrap_err(), + object_store::Error::AlreadyExists { path, .. } if path == location.as_ref() + )); + assert_eq!(store.get(&location).await?.bytes().await?, content); + Ok(()) + } + + #[tokio::test] + async fn test_rename_same_path_matches_object_store_contract() -> anyhow::Result<()> { + let store = OpendalStore::new(Operator::new(services::Memory::default())?); + let location = Path::from("same-path-rename"); + + assert!(matches!( + store.rename(&location, &location).await.unwrap_err(), + object_store::Error::NotFound { path, .. } if path == location.as_ref() + )); + assert!(matches!( + store.rename_if_not_exists(&location, &location).await.unwrap_err(), + object_store::Error::NotFound { path, .. } if path == location.as_ref() + )); + + let content = Bytes::from_static(b"content"); + store.put(&location, content.clone().into()).await?; + + store.rename(&location, &location).await?; + assert_eq!(store.get(&location).await?.bytes().await?, content); + assert!(matches!( + store.rename_if_not_exists(&location, &location).await.unwrap_err(), + object_store::Error::AlreadyExists { path, .. } if path == location.as_ref() + )); + assert_eq!(store.get(&location).await?.bytes().await?, content); + Ok(()) + } + #[tokio::test] async fn test_rename_overwrite_fs() -> anyhow::Result<()> { let root =
