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 2a2d56221d feat(services/fs): support if_not_exists staged writes on 
non-Linux (#8739)
2a2d56221d is described below

commit 2a2d56221dd3166cd3919a7e9cbbe1c451c5a45c
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 06:22:14 2026 +0800

    feat(services/fs): support if_not_exists staged writes on non-Linux (#8739)
    
    Previously, writes with if_not_exists under atomic_write_dir only committed
    without replacing the destination on Linux through RENAME_NOREPLACE; other
    platforms rejected the combination as unsupported, and the fail-fast
    destination check at writer creation had been dropped.
    
    Publish staged conditional writes through std::fs::hard_link on non-Linux
    platforms, which atomically fails with AlreadyExists when the destination is
    already present instead of replacing it. Restore the early destination check
    in FsWriter::create so conditional writes fail fast instead of staging
    content that the commit must reject. On failure the staging file is still
    removed, and a failed publish cleans up the staged file.
---
 core/services/fs/src/backend.rs            |  15 ++--
 core/services/fs/src/core.rs               |  34 ++++++++
 core/services/fs/src/docs.md               |  11 +--
 core/services/fs/src/writer.rs             |  23 +++---
 core/services/fs/tests/write_conditions.rs | 123 ++++++++++++++++++++++-------
 dev/src/generate/capabilities_docs.rs      |   4 +-
 website/data/capabilities.json             |   2 +-
 7 files changed, 153 insertions(+), 59 deletions(-)

diff --git a/core/services/fs/src/backend.rs b/core/services/fs/src/backend.rs
index 65dd84175b..2ffe397b58 100644
--- a/core/services/fs/src/backend.rs
+++ b/core/services/fs/src/backend.rs
@@ -55,7 +55,10 @@ impl FsBuilder {
     /// # Notes
     ///
     /// - Append to an existing file normally writes directly to the file.
-    /// - Writes with `if_not_exists` require Linux support for 
`RENAME_NOREPLACE`.
+    /// - Staged writes with `if_not_exists` publish without replacing an
+    ///   existing destination, through `RENAME_NOREPLACE` on Linux and through
+    ///   a hard link elsewhere. Both need the staging directory and the
+    ///   destination on the same filesystem.
     pub fn atomic_write_dir(mut self, dir: &str) -> Self {
         if !dir.is_empty() {
             self.config.atomic_write_dir = Some(dir.to_string());
@@ -161,8 +164,7 @@ impl Builder for FsBuilder {
                     write_can_empty: true,
                     write_can_append: !direct_io,
                     write_can_multi: true,
-                    write_with_if_not_exists: atomic_write_dir.is_none()
-                        || cfg!(target_os = "linux"),
+                    write_with_if_not_exists: true,
                     #[cfg(unix)]
                     write_with_user_metadata: true,
 
@@ -245,13 +247,6 @@ impl Service for FsBackend {
             ));
         }
 
-        if op.if_not_exists() && 
!self.core.capability.write_with_if_not_exists {
-            return Err(Error::new(
-                ErrorKind::Unsupported,
-                "if_not_exists with atomic_write_dir is only supported on 
Linux",
-            ));
-        }
-
         Ok(FsLazyWriter::new(
             self.core.clone(),
             ctx.executor().clone(),
diff --git a/core/services/fs/src/core.rs b/core/services/fs/src/core.rs
index e6a52d0061..5961169c28 100644
--- a/core/services/fs/src/core.rs
+++ b/core/services/fs/src/core.rs
@@ -261,6 +261,40 @@ impl FsCore {
 #[cfg(unix)]
 const XATTR_USER_PREFIX: &str = "user.";
 
+/// Publish a staged write at `to` without replacing an existing entry.
+///
+/// Returns `ConditionNotMatch` when the destination already exists.
+pub(super) fn publish_staged_file(from: &Path, to: &Path) -> Result<()> {
+    #[cfg(target_os = "linux")]
+    {
+        rename_noreplace(from, to)
+    }
+
+    #[cfg(not(target_os = "linux"))]
+    {
+        // Non-Linux systems lack a rename that fails on an existing
+        // destination. Linking the staged file to `to` creates the destination
+        // atomically and fails with `AlreadyExists` when it is already
+        // present, on both POSIX and Windows. Hard links require both paths on
+        // one filesystem, which the atomic publish already requires for its
+        // rename.
+        std::fs::hard_link(from, to)
+            .map_err(|err| 
parse_error(ErrorContext::new(ServiceOperation("Rename")), err))?;
+
+        match std::fs::remove_file(from) {
+            // A concurrent cleanup or an unusual filesystem may have removed
+            // the staging entry already; the destination is still published.
+            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
+            // The destination was published, but the staging file is orphaned
+            // now. Report it instead of leaking it silently.
+            Err(err) => {
+                Err(new_std_io_error(err).with_context("service_operation", 
"RemoveStagedFile"))
+            }
+            Ok(()) => Ok(()),
+        }
+    }
+}
+
 #[cfg(target_os = "linux")]
 pub(super) fn rename_noreplace(from: &Path, to: &Path) -> Result<()> {
     use rustix::fs::{CWD, RenameFlags, renameat_with};
diff --git a/core/services/fs/src/docs.md b/core/services/fs/src/docs.md
index fe4b31b31f..b371efbe20 100644
--- a/core/services/fs/src/docs.md
+++ b/core/services/fs/src/docs.md
@@ -29,11 +29,12 @@ for an existing destination when committing the staged 
file. If the destination
 exists, the write returns [`opendal_core::ErrorKind::ConditionNotMatch`] and
 preserves the existing file. This also applies when `append(true)` is set.
 
-Staged conditional writes require Linux and kernel and filesystem support for
-`RENAME_NOREPLACE`. OpenDAL returns [`opendal_core::ErrorKind::Unsupported`]
-when that support is unavailable. The staging directory and the destination
-must be on the same filesystem. Without `atomic_write_dir`, conditional writes
-use exclusive file creation on all supported platforms.
+On Linux, the conditional commit uses `RENAME_NOREPLACE` and returns
+[`opendal_core::ErrorKind::Unsupported`] when the kernel or filesystem lacks
+it. Other platforms publish the staged file through a hard link that
+atomically fails on an existing destination. The staging directory and the
+destination must be on the same filesystem. Without `atomic_write_dir`,
+conditional writes use exclusive file creation on all supported platforms.
 
 ## List
 
diff --git a/core/services/fs/src/writer.rs b/core/services/fs/src/writer.rs
index 3d75e5995d..a15a3745e5 100644
--- a/core/services/fs/src/writer.rs
+++ b/core/services/fs/src/writer.rs
@@ -27,9 +27,7 @@ use bytes::Buf;
 use bytes::Bytes;
 use tokio::io::AsyncWriteExt;
 
-#[cfg(target_os = "linux")]
-use super::core::rename_noreplace;
-use super::core::{ErrorContext, FsCore, parse_error};
+use super::core::{ErrorContext, FsCore, parse_error, publish_staged_file};
 #[cfg(target_os = "linux")]
 use super::direct_io::DirectIoAlignment;
 use opendal_core::raw::*;
@@ -156,7 +154,6 @@ pub struct FsWriter {
     target_path: PathBuf,
     /// The staging path for a write that publishes the file on close.
     temp_path: Option<PathBuf>,
-    #[cfg(target_os = "linux")]
     if_not_exists: bool,
     f: tokio::fs::File,
     #[cfg(target_os = "linux")]
@@ -180,12 +177,20 @@ impl FsWriter {
 
         let mut temp_path = None;
         if let Some(atomic_write_dir) = &core.atomic_write_dir {
-            // Only an unconditional append may write to an existing file in 
place.
-            let append_in_place = op.append()
-                && !op.if_not_exists()
+            // Fail fast on an existing destination instead of staging content
+            // that the conditional commit must reject.
+            let target_exists = (op.if_not_exists() || op.append())
                 && tokio::fs::try_exists(&target_path)
                     .await
                     .map_err(new_std_io_error)?;
+            if op.if_not_exists() && target_exists {
+                return Err(Error::new(
+                    ErrorKind::ConditionNotMatch,
+                    "file already exists, doesn't match the condition 
if_not_exists",
+                ));
+            }
+            // Only an unconditional append may write to an existing file in 
place.
+            let append_in_place = op.append() && target_exists;
             if !append_in_place {
                 temp_path = Some(
                     core.ensure_write_abs_path(atomic_write_dir, 
&build_tmp_path_of(path))
@@ -243,7 +248,6 @@ impl FsWriter {
         Ok(Self {
             target_path,
             temp_path,
-            #[cfg(target_os = "linux")]
             if_not_exists: op.if_not_exists(),
             f,
             #[cfg(target_os = "linux")]
@@ -258,12 +262,11 @@ impl FsWriter {
             return Ok(());
         };
 
-        #[cfg(target_os = "linux")]
         if self.if_not_exists {
             let temp_path = temp_path.clone();
             let target_path = self.target_path.clone();
             return tokio::task::spawn_blocking(move || {
-                rename_noreplace(&temp_path, &target_path).map_err(|err| {
+                publish_staged_file(&temp_path, &target_path).map_err(|err| {
                     // The staged file is discarded, so this close cannot be 
retried.
                     let err = err.set_permanent();
                     match std::fs::remove_file(&temp_path) {
diff --git a/core/services/fs/tests/write_conditions.rs 
b/core/services/fs/tests/write_conditions.rs
index 53947a226d..ae3a31cf18 100644
--- a/core/services/fs/tests/write_conditions.rs
+++ b/core/services/fs/tests/write_conditions.rs
@@ -17,19 +17,27 @@
 
 use opendal_core::{ErrorKind, Operator};
 use opendal_service_fs::Fs;
+use tempfile::TempDir;
+
+fn atomic_fs_operator(root: &TempDir, staging: &TempDir) -> Operator {
+    Operator::new(
+        Fs::default()
+            .root(root.path().to_str().unwrap())
+            .atomic_write_dir(staging.path().to_str().unwrap()),
+    )
+    .unwrap()
+}
+
+fn staging_is_empty(staging: &TempDir) -> bool {
+    std::fs::read_dir(staging.path()).unwrap().next().is_none()
+}
 
-#[cfg(target_os = "linux")]
 #[tokio::test]
 async fn staged_conditional_writers_do_not_overwrite_each_other() {
     for append in [false, true] {
         let root = tempfile::tempdir().unwrap();
         let staging = tempfile::tempdir().unwrap();
-        let op = Operator::new(
-            Fs::default()
-                .root(root.path().to_str().unwrap())
-                .atomic_write_dir(staging.path().to_str().unwrap()),
-        )
-        .unwrap();
+        let op = atomic_fs_operator(&root, &staging);
         assert!(op.info().capability().write_with_if_not_exists);
         let mut first = op
             .writer_with("data")
@@ -55,35 +63,90 @@ async fn 
staged_conditional_writers_do_not_overwrite_each_other() {
             ErrorKind::ConditionNotMatch
         );
         assert_eq!(op.read("data").await.unwrap().to_bytes(), "first writer");
-        assert!(std::fs::read_dir(staging.path()).unwrap().next().is_none());
+        assert!(staging_is_empty(&staging));
     }
 }
 
 #[tokio::test]
 async fn staged_conditional_write_preserves_existing_file() {
+    for append in [false, true] {
+        let root = tempfile::tempdir().unwrap();
+        let staging = tempfile::tempdir().unwrap();
+        std::fs::write(root.path().join("data"), b"original").unwrap();
+        let op = atomic_fs_operator(&root, &staging);
+        assert!(op.info().capability().write_with_if_not_exists);
+
+        let err = op
+            .write_with("data", "replacement")
+            .if_not_exists(true)
+            .append(append)
+            .await
+            .unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::ConditionNotMatch);
+        assert_eq!(op.read("data").await.unwrap().to_bytes(), "original");
+        assert!(staging_is_empty(&staging));
+    }
+}
+
+#[tokio::test]
+async fn 
staged_conditional_write_fails_when_destination_appears_before_commit() {
+    for append in [false, true] {
+        let root = tempfile::tempdir().unwrap();
+        let staging = tempfile::tempdir().unwrap();
+        let op = atomic_fs_operator(&root, &staging);
+
+        // The destination does not exist when the conditional writer opens,
+        // so the check must happen while publishing the staged file.
+        let mut writer = op
+            .writer_with("data")
+            .if_not_exists(true)
+            .append(append)
+            .await
+            .unwrap();
+        writer.write("staged content").await.unwrap();
+
+        op.write_with("data", "concurrent winner").await.unwrap();
+
+        let err = writer.close().await.unwrap_err();
+        assert_eq!(err.kind(), ErrorKind::ConditionNotMatch);
+        assert_eq!(
+            op.read("data").await.unwrap().to_bytes(),
+            "concurrent winner"
+        );
+        assert!(staging_is_empty(&staging));
+    }
+}
+
+#[tokio::test]
+async fn staged_conditional_write_creates_missing_destination() {
+    for append in [false, true] {
+        let root = tempfile::tempdir().unwrap();
+        let staging = tempfile::tempdir().unwrap();
+        let op = atomic_fs_operator(&root, &staging);
+
+        let mut writer = op
+            .writer_with("data")
+            .if_not_exists(true)
+            .append(append)
+            .await
+            .unwrap();
+        writer.write("staged content").await.unwrap();
+        writer.close().await.unwrap();
+
+        assert_eq!(op.read("data").await.unwrap().to_bytes(), "staged 
content");
+        assert!(staging_is_empty(&staging));
+    }
+}
+
+#[tokio::test]
+async fn staged_unconditional_write_replaces_existing_destination() {
     let root = tempfile::tempdir().unwrap();
     let staging = tempfile::tempdir().unwrap();
     std::fs::write(root.path().join("data"), b"original").unwrap();
-    let op = Operator::new(
-        Fs::default()
-            .root(root.path().to_str().unwrap())
-            .atomic_write_dir(staging.path().to_str().unwrap()),
-    )
-    .unwrap();
-
-    let supported = cfg!(target_os = "linux");
-    assert_eq!(op.info().capability().write_with_if_not_exists, supported);
-    let err = op
-        .write_with("data", "replacement")
-        .if_not_exists(true)
-        .await
-        .unwrap_err();
-    let expected = if supported {
-        ErrorKind::ConditionNotMatch
-    } else {
-        ErrorKind::Unsupported
-    };
-    assert_eq!(err.kind(), expected);
-    assert_eq!(op.read("data").await.unwrap().to_bytes(), "original");
-    assert!(std::fs::read_dir(staging.path()).unwrap().next().is_none());
+    let op = atomic_fs_operator(&root, &staging);
+
+    op.write_with("data", "replacement").await.unwrap();
+
+    assert_eq!(op.read("data").await.unwrap().to_bytes(), "replacement");
+    assert!(staging_is_empty(&staging));
 }
diff --git a/dev/src/generate/capabilities_docs.rs 
b/dev/src/generate/capabilities_docs.rs
index 53b47ff86e..a319901688 100644
--- a/dev/src/generate/capabilities_docs.rs
+++ b/dev/src/generate/capabilities_docs.rs
@@ -1158,9 +1158,7 @@ mod tests {
         );
         assert_eq!(
             fs_srv.native.get("write_with_if_not_exists"),
-            Some(&NativeBoolDoc::Conditional(
-                "When `atomic_write_dir` is not set or on Linux".to_string()
-            ))
+            Some(&NativeBoolDoc::Supported(true))
         );
         assert_eq!(
             fs_srv.native.get("write_with_user_metadata"),
diff --git a/website/data/capabilities.json b/website/data/capabilities.json
index ecd8148509..2b255f66f5 100644
--- a/website/data/capabilities.json
+++ b/website/data/capabilities.json
@@ -1144,7 +1144,7 @@
         "write_can_append": "When `direct_io` is disabled",
         "write_can_empty": true,
         "write_can_multi": true,
-        "write_with_if_not_exists": "When `atomic_write_dir` is not set or on 
Linux",
+        "write_with_if_not_exists": true,
         "write_with_user_metadata": "Unix only"
       }
     },

Reply via email to