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 0644ae6155 feat(services/monoiofs): support rename_with_if_not_exists 
on Linux (#9023)
0644ae6155 is described below

commit 0644ae61555aba71b99a14f0b42d6c9d0a1bc2df
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 23:30:39 2026 +0800

    feat(services/monoiofs): support rename_with_if_not_exists on Linux (#9023)
    
    Advertise Capability::rename_with_if_not_exists on Linux and use atomic
    renameat2 with RENAME_NOREPLACE via rustix when OpRename::if_not_exists()
    is set.
    
    Refs #7828.
---
 core/Cargo.lock                       |   1 +
 core/services/monoiofs/Cargo.toml     |   3 +
 core/services/monoiofs/src/backend.rs | 241 +++++++++++++++++++++++++++++++++-
 core/services/monoiofs/src/core.rs    |   1 +
 core/services/monoiofs/src/docs.md    |   8 ++
 website/data/capabilities.json        |   1 +
 6 files changed, 253 insertions(+), 2 deletions(-)

diff --git a/core/Cargo.lock b/core/Cargo.lock
index 9495ccfd17..0e0d7aab9c 100644
--- a/core/Cargo.lock
+++ b/core/Cargo.lock
@@ -8640,6 +8640,7 @@ dependencies = [
  "flume 0.12.0",
  "monoio",
  "opendal-core",
+ "rustix 1.1.6",
  "serde",
  "tempfile",
  "tokio",
diff --git a/core/services/monoiofs/Cargo.toml 
b/core/services/monoiofs/Cargo.toml
index 2d28c6a97e..86b1325ed7 100644
--- a/core/services/monoiofs/Cargo.toml
+++ b/core/services/monoiofs/Cargo.toml
@@ -44,6 +44,9 @@ monoio = { version = "0.2.4", features = [
 opendal-core = { path = "../../core", version = "0.59.5", default-features = 
false }
 serde = { workspace = true, features = ["derive"] }
 
+[target.'cfg(target_os = "linux")'.dependencies]
+rustix = { version = "1", features = ["fs"] }
+
 [dev-dependencies]
 tempfile = "3"
 tokio = { workspace = true, features = ["macros", "rt-multi-thread", "time"] }
diff --git a/core/services/monoiofs/src/backend.rs 
b/core/services/monoiofs/src/backend.rs
index d2898dbf94..9014f20287 100644
--- a/core/services/monoiofs/src/backend.rs
+++ b/core/services/monoiofs/src/backend.rs
@@ -180,17 +180,48 @@ impl Service for MonoiofsBackend {
         _ctx: &OperationContext,
         from: &str,
         to: &str,
-        _args: OpRename,
+        args: OpRename,
     ) -> Result<RpRename> {
+        #[cfg(not(target_os = "linux"))]
+        if args.if_not_exists() {
+            return Err(Error::new(
+                ErrorKind::Unsupported,
+                "Conditional rename is only supported on Linux",
+            ));
+        }
+
         let from = self.core.prepare_path(from)?;
         // ensure file exists
-        self.core
+        let meta = self
+            .core
             .dispatch({
                 let from = from.clone();
                 move || monoio::fs::metadata(from)
             })
             .await
             .map_err(new_std_io_error)?;
+
+        #[cfg(target_os = "linux")]
+        if args.if_not_exists() {
+            use rustix::fs::{CWD, RenameFlags, renameat_with};
+
+            if meta.is_dir() {
+                return Err(Error::new(
+                    ErrorKind::IsADirectory,
+                    "rename source is a directory",
+                ));
+            }
+            let to = self.core.prepare_write_path(to).await?;
+            self.core
+                .dispatch(move || async move {
+                    renameat_with(CWD, &from, CWD, &to, RenameFlags::NOREPLACE)
+                        .map_err(parse_conditional_rename_error)
+                })
+                .await?;
+            return Ok(RpRename::default());
+        }
+
+        let _ = meta;
         let to = self.core.prepare_write_path(to).await?;
         self.core
             .dispatch(move || monoio::fs::rename(from, to))
@@ -359,6 +390,25 @@ fn is_same_file(
     }
 }
 
+#[cfg(target_os = "linux")]
+fn parse_conditional_rename_error(err: rustix::io::Errno) -> Error {
+    use rustix::io::Errno;
+
+    match err {
+        Errno::EXIST | Errno::NOTEMPTY => Error::new(
+            ErrorKind::ConditionNotMatch,
+            "The destination already exists",
+        )
+        .set_source(std::io::Error::from(err)),
+        Errno::NOSYS | Errno::INVAL | Errno::OPNOTSUPP => Error::new(
+            ErrorKind::Unsupported,
+            "The kernel or filesystem does not support conditional rename",
+        )
+        .set_source(err),
+        _ => new_std_io_error(err.into()),
+    }
+}
+
 #[cfg(test)]
 mod tests {
     use std::time::Duration;
@@ -477,4 +527,191 @@ mod tests {
         assert_eq!(err.kind(), ErrorKind::NotFound);
         assert!(!temp_dir.path().join("missing_parent").exists());
     }
+
+    #[cfg(target_os = "linux")]
+    #[test]
+    fn test_conditional_rename_errno_mapping() {
+        use rustix::io::Errno;
+
+        for (errno, kind) in [
+            (Errno::EXIST, ErrorKind::ConditionNotMatch),
+            (Errno::NOTEMPTY, ErrorKind::ConditionNotMatch),
+            (Errno::NOSYS, ErrorKind::Unsupported),
+            (Errno::INVAL, ErrorKind::Unsupported),
+            (Errno::OPNOTSUPP, ErrorKind::Unsupported),
+            (Errno::NOENT, ErrorKind::NotFound),
+            (Errno::NOTDIR, ErrorKind::NotADirectory),
+            (Errno::ISDIR, ErrorKind::IsADirectory),
+        ] {
+            let err = parse_conditional_rename_error(errno);
+            assert_eq!(err.kind(), kind, "{errno:?}");
+            assert!(!err.is_temporary(), "{err:?}");
+        }
+    }
+
+    #[cfg(target_os = "linux")]
+    #[tokio::test]
+    async fn test_rename_with_if_not_exists() {
+        let temp_dir = tempfile::tempdir().unwrap();
+        let root = temp_dir.path();
+        let backend = MonoiofsBuilder::default()
+            .root(root.to_str().unwrap())
+            .build()
+            .unwrap();
+        let op = 
Operator::new(MonoiofsBuilder::default().root(root.to_str().unwrap())).unwrap();
+        assert!(op.info().capability().rename_with_if_not_exists);
+
+        // Basic success.
+        op.write("src", "source data").await.unwrap();
+        op.rename_with("src", "dst")
+            .if_not_exists(true)
+            .await
+            .unwrap();
+        assert!(!root.join("src").exists());
+        assert_eq!(std::fs::read(root.join("dst")).unwrap(), b"source data");
+
+        // Nested destination creates parent directories.
+        op.write("nested_src", "nested data").await.unwrap();
+        op.rename_with("nested_src", "a/b/nested_dst")
+            .if_not_exists(true)
+            .await
+            .unwrap();
+        assert!(!root.join("nested_src").exists());
+        assert_eq!(
+            std::fs::read(root.join("a/b/nested_dst")).unwrap(),
+            b"nested data"
+        );
+
+        // Existing destination file returns ConditionNotMatch and preserves 
both files.
+        op.write("conflict_src", "new content").await.unwrap();
+        op.write("conflict_dst", "existing content").await.unwrap();
+        let err = op
+            .rename_with("conflict_src", "conflict_dst")
+            .if_not_exists(true)
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::ConditionNotMatch, "{err:?}");
+        assert!(!err.is_temporary(), "{err:?}");
+        assert_eq!(
+            std::fs::read(root.join("conflict_src")).unwrap(),
+            b"new content"
+        );
+        assert_eq!(
+            std::fs::read(root.join("conflict_dst")).unwrap(),
+            b"existing content"
+        );
+
+        // Existing non-empty destination directory returns ConditionNotMatch 
and preserves both.
+        std::fs::create_dir(root.join("existing_dir")).unwrap();
+        std::fs::write(root.join("existing_dir/child"), b"keep").unwrap();
+        let err = op
+            .rename_with("conflict_src", "existing_dir")
+            .if_not_exists(true)
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::ConditionNotMatch, "{err:?}");
+        assert!(!err.is_temporary(), "{err:?}");
+        assert_eq!(
+            std::fs::read(root.join("conflict_src")).unwrap(),
+            b"new content"
+        );
+        assert_eq!(
+            std::fs::read(root.join("existing_dir/child")).unwrap(),
+            b"keep"
+        );
+
+        // Self-rename via Operator returns IsSameFile; direct backend call 
and hard-link alias
+        // hit RENAME_NOREPLACE and return ConditionNotMatch while preserving 
the file.
+        op.write("self_file", "self content").await.unwrap();
+        let err = op
+            .rename_with("self_file", "self_file")
+            .if_not_exists(true)
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::IsSameFile, "{err:?}");
+        let err = backend
+            .rename(
+                &OperationContext::default(),
+                "self_file",
+                "self_file",
+                OpRename::new().with_if_not_exists(true),
+            )
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::ConditionNotMatch, "{err:?}");
+        assert!(!err.is_temporary(), "{err:?}");
+        std::fs::hard_link(root.join("self_file"), 
root.join("self_hard")).unwrap();
+        let err = op
+            .rename_with("self_file", "self_hard")
+            .if_not_exists(true)
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::ConditionNotMatch, "{err:?}");
+        assert_eq!(
+            std::fs::read(root.join("self_file")).unwrap(),
+            b"self content"
+        );
+    }
+
+    #[cfg(target_os = "linux")]
+    #[tokio::test]
+    async fn test_conditional_rename_source_and_path_errors() {
+        let temp_dir = tempfile::tempdir().unwrap();
+        let root = temp_dir.path();
+        let op = 
Operator::new(MonoiofsBuilder::default().root(root.to_str().unwrap())).unwrap();
+
+        // Missing source returns NotFound without creating destination parent 
directories.
+        let err = op
+            .rename_with("missing", "ghost/dir/dst")
+            .if_not_exists(true)
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::NotFound, "{err:?}");
+        assert!(!err.is_temporary(), "{err:?}");
+        assert!(!root.join("ghost").exists());
+
+        // Directory source (with or without trailing slash) returns 
IsADirectory without creating
+        // destination parent directories.
+        std::fs::create_dir(root.join("src_dir")).unwrap();
+        std::fs::write(root.join("src_dir/child"), b"dir child").unwrap();
+        for from in ["src_dir", "src_dir/"] {
+            let err = op
+                .rename_with(from, "dir_ghost/dst")
+                .if_not_exists(true)
+                .await
+                .unwrap_err();
+            assert_eq!(err.kind(), ErrorKind::IsADirectory, "{from}: {err:?}");
+            assert!(!err.is_temporary(), "{from}: {err:?}");
+            assert!(!root.join("dir_ghost").exists());
+        }
+        assert_eq!(
+            std::fs::read(root.join("src_dir/child")).unwrap(),
+            b"dir child"
+        );
+
+        // Non-directory path components return permanent errors and preserve 
existing files.
+        std::fs::write(root.join("source"), b"source contents").unwrap();
+        std::fs::write(root.join("file"), b"parent contents").unwrap();
+        for (from, to, kind) in [
+            ("file/child", "target", ErrorKind::NotADirectory),
+            ("source", "file/child", ErrorKind::AlreadyExists),
+            ("source", "file/dir/child", ErrorKind::NotADirectory),
+        ] {
+            let err = op
+                .rename_with(from, to)
+                .if_not_exists(true)
+                .await
+                .unwrap_err();
+            assert_eq!(err.kind(), kind, "{from} -> {to}: {err:?}");
+            assert!(!err.is_temporary(), "{from} -> {to}: {err:?}");
+        }
+        assert_eq!(
+            std::fs::read(root.join("source")).unwrap(),
+            b"source contents"
+        );
+        assert_eq!(
+            std::fs::read(root.join("file")).unwrap(),
+            b"parent contents"
+        );
+    }
 }
diff --git a/core/services/monoiofs/src/core.rs 
b/core/services/monoiofs/src/core.rs
index 97b530f6d0..280a9eaa55 100644
--- a/core/services/monoiofs/src/core.rs
+++ b/core/services/monoiofs/src/core.rs
@@ -78,6 +78,7 @@ impl MonoiofsCore {
 
                 delete: true,
                 rename: true,
+                rename_with_if_not_exists: cfg!(target_os = "linux"),
                 create_dir: true,
                 copy: true,
                 shared: true,
diff --git a/core/services/monoiofs/src/docs.md 
b/core/services/monoiofs/src/docs.md
index b26e50f8f6..e5a4bc2b73 100644
--- a/core/services/monoiofs/src/docs.md
+++ b/core/services/monoiofs/src/docs.md
@@ -15,6 +15,14 @@ Depending on its configuration and the backing system, this 
service can expose:
 Inspect the effective capability set with [`opendal_core::Operator::info`] and
 [`opendal_core::OperatorInfo::capability`] after building an operator.
 
+## Rename
+
+On Linux, `rename_with(...).if_not_exists(true)` atomically moves the source
+only when the destination is absent. If the destination exists, the operation
+returns [`opendal_core::ErrorKind::ConditionNotMatch`] and preserves both 
files.
+The option requires kernel and filesystem support for `RENAME_NOREPLACE`.
+Otherwise, the operation returns [`opendal_core::ErrorKind::Unsupported`].
+
 ## Configuration
 
 Use [`crate::MonoiofsConfig`] for serializable configuration and this builder's
diff --git a/website/data/capabilities.json b/website/data/capabilities.json
index 07ed34859f..616c4bdd84 100644
--- a/website/data/capabilities.json
+++ b/website/data/capabilities.json
@@ -1675,6 +1675,7 @@
         "delete": true,
         "read": true,
         "rename": true,
+        "rename_with_if_not_exists": "Linux only",
         "shared": true,
         "stat": true,
         "write": true,

Reply via email to