This is an automated email from the ASF dual-hosted git repository.

Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git


The following commit(s) were added to refs/heads/main by this push:
     new 5d36377d77 fix(services/hdfs,smb): normalize paths and validate SMB 
rename source (#9020)
5d36377d77 is described below

commit 5d36377d775093549894c9be81b80d18101768e3
Author: Xuanwo <[email protected]>
AuthorDate: Wed Nov 25 14:14:01 2026 +0800

    fix(services/hdfs,smb): normalize paths and validate SMB rename source 
(#9020)
    
    * fix(services/hdfs,services/smb): fix writer lifecycle, listing paths, 
copy retries, rename validation, and config handling
    
    * fix(services/hdfs,services/smb): check metadata before hdfs delete, make 
close retryable, and harden tests
    
    * fix(services/hdfs,smb): narrow fixes to reproduced failures
    
    Retain HDFS path normalization for a configured atomic write directory
    and directory listing without a trailing slash. Keep SMB listing path
    separators and validate the rename source before creating destination
    parents, closing the source after either outcome.
    
    Restore the original writer, configuration, and copy retry behavior
    outside these fixes.
    
    With the repository fixtures (Hadoop 3.2.1 and Samba 4.23.8), PR base
    063bf0dc55d2d20fd6e2cddb9b98ac666288e11d panics in public HDFS writer and
    list operations, joins SMB child paths without a separator, and creates a
    destination parent for a missing rename source. The HDFS cases pass on
    PR head 1c12da519c5815d1e8d81eea740a3d28804ab380 and on this revision.
    The HDFS regression verifies payload publication and cleanup of the
    configured temporary directory. The Samba fixture verifies the listing
    and rename results. A separate smbstatus check verifies the source
    handle is released after both parent creation failure and a conditional
    rename collision.
---
 core/services/hdfs/src/backend.rs |  5 ++-
 core/services/hdfs/src/lister.rs  | 32 ++++++++++++-
 core/services/hdfs/tests/paths.rs | 95 +++++++++++++++++++++++++++++++++++++++
 core/services/smb/src/backend.rs  | 34 +++++++-------
 core/services/smb/src/lister.rs   | 64 ++++++++++++++++++++------
 core/services/smb/tests/samba.rs  | 69 ++++++++++++++++++++++++++++
 6 files changed, 269 insertions(+), 30 deletions(-)

diff --git a/core/services/hdfs/src/backend.rs 
b/core/services/hdfs/src/backend.rs
index a97eef36a2..1c616e17a7 100644
--- a/core/services/hdfs/src/backend.rs
+++ b/core/services/hdfs/src/backend.rs
@@ -142,7 +142,10 @@ impl Builder for HdfsBuilder {
             client.create_dir(&root).map_err(new_std_io_error)?
         }
 
-        let atomic_write_dir = self.config.atomic_write_dir;
+        let mut atomic_write_dir = self.config.atomic_write_dir;
+        if let Some(dir) = atomic_write_dir.as_mut().filter(|dir| 
!dir.is_empty()) {
+            *dir = normalize_root(dir);
+        }
 
         // If atomic write dir is not exist, we must create it.
         if let Some(d) = &atomic_write_dir
diff --git a/core/services/hdfs/src/lister.rs b/core/services/hdfs/src/lister.rs
index 963096103e..d1e493a8d1 100644
--- a/core/services/hdfs/src/lister.rs
+++ b/core/services/hdfs/src/lister.rs
@@ -27,6 +27,16 @@ pub struct HdfsLister {
     current_path: Option<String>,
 }
 
+fn normalize_dir_entry_path(path: &str) -> String {
+    if path.is_empty() || path == "/" {
+        "/".to_string()
+    } else if path.ends_with('/') {
+        path.to_string()
+    } else {
+        format!("{path}/")
+    }
+}
+
 impl HdfsLister {
     pub fn new(root: &str, rd: hdrs::Readdir, path: &str) -> Self {
         Self {
@@ -34,7 +44,7 @@ impl HdfsLister {
 
             rd,
 
-            current_path: Some(path.to_string()),
+            current_path: Some(normalize_dir_entry_path(path)),
         }
     }
 }
@@ -66,3 +76,23 @@ impl oio::List for HdfsLister {
         Ok(Some(entry))
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn normalize_dir_entry_path_ensures_trailing_slash() {
+        assert_eq!(normalize_dir_entry_path(""), "/");
+        assert_eq!(normalize_dir_entry_path("/"), "/");
+        assert_eq!(normalize_dir_entry_path("sub/"), "sub/");
+        assert_eq!(normalize_dir_entry_path("sub"), "sub/");
+        assert_eq!(normalize_dir_entry_path("a/b"), "a/b/");
+
+        let entry = oio::Entry::new(
+            &normalize_dir_entry_path("sub"),
+            MetadataBuilder::dir().build(),
+        );
+        assert_eq!(entry.path(), "sub/");
+    }
+}
diff --git a/core/services/hdfs/tests/paths.rs 
b/core/services/hdfs/tests/paths.rs
new file mode 100644
index 0000000000..618e1b9e50
--- /dev/null
+++ b/core/services/hdfs/tests/paths.rs
@@ -0,0 +1,95 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use opendal_core::Operator;
+use opendal_service_hdfs::Hdfs;
+
+fn fixture(test: &str) -> (Hdfs, String) {
+    let name_node = std::env::var("OPENDAL_HDFS_NAME_NODE").unwrap();
+    let root = std::env::var("OPENDAL_HDFS_ROOT").unwrap();
+    let root = format!(
+        "{}/{test}-{}",
+        root.trim_end_matches('/'),
+        std::process::id()
+    );
+    (Hdfs::default().name_node(&name_node), root)
+}
+
+async fn atomic_write_with_dir(test: &str, omit_leading_slash: bool) {
+    let (builder, root) = fixture(test);
+    let temporary_dir = format!("{root}/temporary");
+    let configured_dir = if omit_leading_slash {
+        temporary_dir.trim_start_matches('/')
+    } else {
+        &temporary_dir
+    };
+    let op = 
Operator::new(builder.root(&root).atomic_write_dir(configured_dir)).unwrap();
+    let mut writer = op.writer("target.txt").await.unwrap();
+    writer.write("atomic payload").await.unwrap();
+
+    assert!(!op.exists("target.txt").await.unwrap());
+    let entries = op.list("temporary/").await.unwrap();
+    assert_eq!(
+        entries
+            .iter()
+            .filter(|entry| entry.metadata().is_file())
+            .count(),
+        1
+    );
+    writer.close().await.unwrap();
+
+    assert_eq!(
+        op.read("target.txt").await.unwrap().to_vec(),
+        b"atomic payload"
+    );
+    assert_paths(op.list("temporary/").await.unwrap(), &["temporary/"]);
+    op.delete_with("/").recursive(true).await.unwrap();
+}
+
+#[tokio::test]
+#[ignore = "requires the HDFS cluster from 
fixtures/hdfs/docker-compose-hdfs-cluster.yml"]
+async fn atomic_write_dir_without_trailing_slash() {
+    atomic_write_with_dir("atomic-absolute", false).await;
+}
+
+#[tokio::test]
+#[ignore = "requires the HDFS cluster from 
fixtures/hdfs/docker-compose-hdfs-cluster.yml"]
+async fn atomic_write_dir_without_leading_or_trailing_slash() {
+    atomic_write_with_dir("atomic-unrooted", true).await;
+}
+
+fn assert_paths(entries: Vec<opendal_core::Entry>, expected: &[&str]) {
+    let mut paths = entries.iter().map(|entry| 
entry.path()).collect::<Vec<_>>();
+    paths.sort_unstable();
+    assert_eq!(paths, expected);
+}
+
+#[tokio::test]
+#[ignore = "requires the HDFS cluster from 
fixtures/hdfs/docker-compose-hdfs-cluster.yml"]
+async fn list_directory_without_trailing_slash() {
+    let (builder, root) = fixture("list-noslash");
+    let op = Operator::new(builder.root(&root)).unwrap();
+    op.create_dir("sub/child/").await.unwrap();
+    op.write("sub/file.txt", "data").await.unwrap();
+    op.write("sub/child/nested.txt", "nested").await.unwrap();
+
+    for path in ["sub", "sub/"] {
+        let entries = op.list(path).await.unwrap();
+        assert_paths(entries, &["sub/", "sub/child/", "sub/file.txt"]);
+    }
+    op.delete_with("/").recursive(true).await.unwrap();
+}
diff --git a/core/services/smb/src/backend.rs b/core/services/smb/src/backend.rs
index 1897bd17f8..ef46492b72 100644
--- a/core/services/smb/src/backend.rs
+++ b/core/services/smb/src/backend.rs
@@ -277,9 +277,6 @@ impl Service for SmbBackend {
     ) -> Result<RpRename> {
         let source = self.core.path(from)?;
         let target = self.core.path(to)?;
-        if let Some((parent, _)) = to.rsplit_once('/') {
-            self.core.create_dir(parent).await?;
-        }
         let client = self.core.client().await?;
         let args = 
FileCreateArgs::make_open_existing(FileAccessMask::new().with_delete(true));
         let resource = client
@@ -305,22 +302,29 @@ impl Service for SmbBackend {
                 ));
             }
         };
-        let result = file
-            .set_info(FileRenameInformation {
+        let result = async {
+            if let Some((parent, _)) = to.rsplit_once('/') {
+                self.core.create_dir(parent).await?;
+            }
+            file.set_info(FileRenameInformation {
                 replace_if_exists: (!op.if_not_exists()).into(),
                 root_directory: 0,
                 file_name: target.path().unwrap_or_default().into(),
             })
-            .await;
-        file.close().await.map_err(parse_smb_error)?;
-        result.map_err(|error| {
-            let error = parse_smb_error(error);
-            if op.if_not_exists() && error.kind() == ErrorKind::AlreadyExists {
-                Error::new(ErrorKind::ConditionNotMatch, "file already 
exists").set_source(error)
-            } else {
-                error
-            }
-        })?;
+            .await
+            .map_err(|error| {
+                let error = parse_smb_error(error);
+                if op.if_not_exists() && error.kind() == 
ErrorKind::AlreadyExists {
+                    Error::new(ErrorKind::ConditionNotMatch, "file already 
exists")
+                        .set_source(error)
+                } else {
+                    error
+                }
+            })
+        }
+        .await;
+        let close_result = file.close().await.map_err(parse_smb_error);
+        result.and(close_result)?;
         Ok(RpRename::default())
     }
 
diff --git a/core/services/smb/src/lister.rs b/core/services/smb/src/lister.rs
index a6ca0bb762..de5e551fd1 100644
--- a/core/services/smb/src/lister.rs
+++ b/core/services/smb/src/lister.rs
@@ -98,19 +98,7 @@ impl SmbLister {
                 if name == ".." {
                     continue;
                 }
-                let prefix = if path == "/" { "" } else { path.as_str() };
-                let mut entry_path = if name == "." {
-                    if prefix.is_empty() {
-                        "/".to_string()
-                    } else {
-                        prefix.to_string()
-                    }
-                } else {
-                    format!("{prefix}{name}")
-                };
-                if entry.file_attributes.directory() && 
!entry_path.ends_with('/') {
-                    entry_path.push('/');
-                }
+                let entry_path = format_entry_path(&path, &name, 
entry.file_attributes.directory());
                 let metadata = to_metadata(
                     entry.file_attributes,
                     entry.end_of_file,
@@ -140,6 +128,32 @@ impl SmbLister {
     }
 }
 
+fn format_entry_path(dir_path: &str, name: &str, is_dir: bool) -> String {
+    let prefix = if dir_path.is_empty() || dir_path == "/" {
+        ""
+    } else {
+        dir_path.trim_end_matches('/')
+    };
+
+    let mut entry_path = if name == "." {
+        if prefix.is_empty() {
+            "/".to_string()
+        } else {
+            format!("{prefix}/")
+        }
+    } else if prefix.is_empty() {
+        name.to_string()
+    } else {
+        format!("{prefix}/{name}")
+    };
+
+    if is_dir && !entry_path.ends_with('/') {
+        entry_path.push('/');
+    }
+
+    entry_path
+}
+
 impl oio::List for SmbLister {
     async fn next(&mut self) -> Result<Option<oio::Entry>> {
         if self.receiver.is_none() {
@@ -161,3 +175,27 @@ impl oio::List for SmbLister {
             .transpose()
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn format_entry_path_normalizes_root_and_dir_separators() {
+        assert_eq!(format_entry_path("/", ".", true), "/");
+        assert_eq!(format_entry_path("/", "file.txt", false), "file.txt");
+        assert_eq!(format_entry_path("/", "child", true), "child/");
+
+        assert_eq!(format_entry_path("sub/", ".", true), "sub/");
+        assert_eq!(format_entry_path("sub/", "file.txt", false), 
"sub/file.txt");
+        assert_eq!(format_entry_path("sub/", "child", true), "sub/child/");
+
+        assert_eq!(format_entry_path("sub", ".", true), "sub/");
+        assert_eq!(format_entry_path("sub", "file.txt", false), 
"sub/file.txt");
+        assert_eq!(format_entry_path("sub", "child", true), "sub/child/");
+
+        assert_eq!(format_entry_path("a/b", ".", true), "a/b/");
+        assert_eq!(format_entry_path("a/b", "file.txt", false), 
"a/b/file.txt");
+        assert_eq!(format_entry_path("a/b", "child", true), "a/b/child/");
+    }
+}
diff --git a/core/services/smb/tests/samba.rs b/core/services/smb/tests/samba.rs
index 0f39adb870..a15889d0c8 100644
--- a/core/services/smb/tests/samba.rs
+++ b/core/services/smb/tests/samba.rs
@@ -15,12 +15,19 @@
 // specific language governing permissions and limitations
 // under the License.
 
+use std::time::Duration;
+
 use futures::AsyncReadExt;
 use futures::TryStreamExt;
+use opendal_core::Builder;
 use opendal_core::Configurator;
 use opendal_core::ErrorKind;
+use opendal_core::OperationContext;
 use opendal_core::Operator;
 use opendal_core::OperatorRegistry;
+use opendal_core::raw::OpList;
+use opendal_core::raw::Service;
+use opendal_core::raw::oio::List;
 use opendal_service_smb::SmbConfig;
 use opendal_service_smb::register_smb_service;
 
@@ -211,3 +218,65 @@ fn resources_can_be_dropped_after_runtime_shutdown() {
     drop(writer);
     drop(op);
 }
+
+#[tokio::test]
+#[ignore = "requires the Samba fixture and OPENDAL_SMB_* configuration"]
+async fn list_without_trailing_slash_preserves_separator() {
+    tokio::time::timeout(Duration::from_secs(5), async {
+        let cfg = config("list-no-slash");
+        let op = Operator::new(cfg.clone().into_builder()).unwrap();
+        op.write("sub/file.txt", "data").await.unwrap();
+        op.write("sub/child/nested.txt", "nested").await.unwrap();
+
+        let op_entries = op.list("sub").await.unwrap();
+        assert!(op_entries.iter().any(|entry| entry.path() == "sub/"));
+
+        let service = cfg.into_builder().build().unwrap();
+        let mut lister = service
+            .list(&OperationContext::default(), "sub", OpList::default())
+            .unwrap();
+        let mut paths = Vec::new();
+        while let Some(entry) = lister.next().await.unwrap() {
+            paths.push(entry.path().to_string());
+        }
+        paths.sort();
+        assert_eq!(paths, vec!["sub/", "sub/child/", "sub/file.txt"]);
+
+        op.delete("sub/child/nested.txt").await.unwrap();
+        op.delete("sub/child/").await.unwrap();
+        op.delete("sub/file.txt").await.unwrap();
+        op.delete("sub/").await.unwrap();
+        op.delete("/").await.unwrap();
+    })
+    .await
+    .expect("list_without_trailing_slash_preserves_separator timed out");
+}
+
+#[tokio::test]
+#[ignore = "requires the Samba fixture and OPENDAL_SMB_* configuration"]
+async fn rename_does_not_create_destination_parent_when_source_invalid() {
+    tokio::time::timeout(Duration::from_secs(5), async {
+        let op = 
Operator::new(config("rename-parent").into_builder()).unwrap();
+        op.create_dir("/").await.unwrap();
+
+        let err = op
+            .rename("missing", "new-parent/nested/target")
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::NotFound);
+        assert!(!op.exists("new-parent/").await.unwrap());
+
+        op.create_dir("existing-dir/").await.unwrap();
+        let err = op
+            .rename("existing-dir", "dir-parent/target")
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::IsADirectory);
+        assert!(!op.exists("dir-parent/").await.unwrap());
+
+        op.delete("existing-dir/").await.unwrap();
+        op.delete("/").await.unwrap();
+    })
+    .await
+    .expect("rename_does_not_create_destination_parent_when_source_invalid 
timed out");
+}

Reply via email to