Xuanwo commented on code in PR #9287:
URL: https://github.com/apache/opendal/pull/9287#discussion_r4721189843


##########
core/services/hf3fs/src/writer.rs:
##########
@@ -125,8 +136,12 @@ impl oio::PositionWrite for Hf3fsWriteHandle {
 
     async fn close(&self, _: u64) -> Result<Metadata> {
         let file = self.file.clone();
+        let staged = self.staged.clone();
         tokio::task::spawn_blocking(move || {
             file.file.sync_all().map_err(new_std_io_error)?;
+            if let Some(staged) = &staged {
+                staged.publish()?;
+            }
             let stat = file.file.metadata().map_err(new_std_io_error)?;

Review Comment:
   Running `file.file.metadata()` (and `stat.modified()`) after 
`staged.publish()`—and re-running `sync_all()` and `metadata()` on repeated 
`close()` calls—allows a post-link error to report failure after the target is 
already committed, and does not guarantee that repeated `close()` returns the 
same `Metadata`. In addition, a `sync_all()` failure returns without removing 
the staged file.
   
   Computing the `Metadata` after `sync_all()` and before `hard_link`, caching 
the committed `Metadata` in `StagedState::Published` (and returning it before 
calling `sync_all()`/`metadata()` again), and cleaning up the staged file on 
any pre-publication failure (`sync_all` or `metadata`) would make `hard_link` 
the sole commit point while leaving the target untouched on failure.



##########
core/services/hf3fs/src/writer.rs:
##########
@@ -139,10 +154,143 @@ impl oio::PositionWrite for Hf3fsWriteHandle {
     }
 
     async fn abort(&self) -> Result<()> {
-        Err(Error::new(
-            ErrorKind::Unsupported,
-            "3FS writes cannot be rolled back",
-        ))
+        let Some(staged) = &self.staged else {
+            return Err(Error::new(
+                ErrorKind::Unsupported,
+                "3FS writes without if_not_exists cannot be rolled back",
+            ));
+        };
+        let staged = Arc::clone(staged);
+        tokio::task::spawn_blocking(move || staged.discard())
+            .await
+            .map_err(new_task_join_error)?
+    }
+}
+
+/// The staged file of an `if_not_exists` write, which becomes visible at
+/// `target` only when `close` publishes it.
+///
+/// 3FS rejects `renameat2` flags, so publishing links the staged file to the
+/// target, which fails when the target exists, and then removes the staged
+/// name. The staged file stays in the target's directory because a hard link
+/// cannot cross filesystems.
+struct StagedFile {
+    /// staged file path
+    path: PathBuf,
+    /// target file path
+    target: PathBuf,
+    /// Held across each publish or discard attempt, so a `close` that is
+    /// cancelled and retried observes the first attempt instead of linking 
twice.
+    state: Mutex<StagedState>,
+}
+
+enum StagedState {
+    /// The staged file exists and the target is untouched.
+    Pending,
+    /// The target names the staged file.
+    Published,
+    /// The staged file was removed without publishing.
+    /// A later `close` reports this error again.
+    Discarded(Error),
+}
+
+impl StagedFile {
+    fn create(target: &Path) -> Result<Self> {
+        let name = target
+            .file_name()
+            .and_then(|name| name.to_str())
+            .ok_or_else(|| Error::new(ErrorKind::IsADirectory, "target is not 
a file path"))?;
+        // Fail fast instead of staging content that the publish must reject.
+        if target.try_exists().map_err(new_std_io_error)? {
+            return Err(Error::new(
+                ErrorKind::ConditionNotMatch,
+                "file already exists",
+            ));
+        }
+        Ok(Self {
+            path: target.with_file_name(build_tmp_path_of(name)),

Review Comment:
   `build_tmp_path_of(name)` creates `<target_name>.<random>`, which blends in 
with user filenames in the same directory and can exceed `NAME_MAX` for long 
target names. Using a fixed, recognizable same-directory prefix such as 
`.opendal-tmp-<random>` would let callers and cleanup sweeps distinguish 
staging entries unambiguously.



##########
core/services/hf3fs/src/writer.rs:
##########
@@ -139,10 +154,143 @@ impl oio::PositionWrite for Hf3fsWriteHandle {
     }
 
     async fn abort(&self) -> Result<()> {
-        Err(Error::new(
-            ErrorKind::Unsupported,
-            "3FS writes cannot be rolled back",
-        ))
+        let Some(staged) = &self.staged else {
+            return Err(Error::new(
+                ErrorKind::Unsupported,
+                "3FS writes without if_not_exists cannot be rolled back",
+            ));
+        };
+        let staged = Arc::clone(staged);
+        tokio::task::spawn_blocking(move || staged.discard())
+            .await
+            .map_err(new_task_join_error)?
+    }
+}
+
+/// The staged file of an `if_not_exists` write, which becomes visible at
+/// `target` only when `close` publishes it.
+///
+/// 3FS rejects `renameat2` flags, so publishing links the staged file to the
+/// target, which fails when the target exists, and then removes the staged
+/// name. The staged file stays in the target's directory because a hard link
+/// cannot cross filesystems.
+struct StagedFile {
+    /// staged file path
+    path: PathBuf,
+    /// target file path
+    target: PathBuf,
+    /// Held across each publish or discard attempt, so a `close` that is
+    /// cancelled and retried observes the first attempt instead of linking 
twice.
+    state: Mutex<StagedState>,
+}
+
+enum StagedState {
+    /// The staged file exists and the target is untouched.
+    Pending,
+    /// The target names the staged file.
+    Published,
+    /// The staged file was removed without publishing.
+    /// A later `close` reports this error again.
+    Discarded(Error),
+}
+
+impl StagedFile {
+    fn create(target: &Path) -> Result<Self> {
+        let name = target
+            .file_name()
+            .and_then(|name| name.to_str())
+            .ok_or_else(|| Error::new(ErrorKind::IsADirectory, "target is not 
a file path"))?;
+        // Fail fast instead of staging content that the publish must reject.
+        if target.try_exists().map_err(new_std_io_error)? {
+            return Err(Error::new(
+                ErrorKind::ConditionNotMatch,
+                "file already exists",
+            ));
+        }
+        Ok(Self {
+            path: target.with_file_name(build_tmp_path_of(name)),
+            target: target.to_path_buf(),
+            state: Mutex::new(StagedState::Pending),
+        })
+    }
+
+    /// Make the staged file visible at the target without replacing an
+    /// existing entry.
+    fn publish(&self) -> Result<()> {
+        let mut state = self.state.lock().unwrap();
+        match &*state {
+            StagedState::Published => return Ok(()),
+            StagedState::Discarded(err) => return Err(Error::new(err.kind(), 
err.message())),
+            StagedState::Pending => {}
+        }
+
+        let err = match std::fs::hard_link(&self.path, &self.target) {
+            Ok(()) => None,
+            // Another writer published the target while this write was staged.
+            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => 
Some(
+                Error::new(ErrorKind::ConditionNotMatch, "file already 
exists").set_source(err),
+            ),
+            Err(err) => Some(new_std_io_error(err)),
+        };
+        if let Some(mut err) = err {
+            // Keep the staged file when a retried close can still publish it.
+            if err.is_temporary() {
+                return Err(err);
+            }

Review Comment:
   Returning early on `err.is_temporary()` leaves the staged file in the target 
directory when callers drop the writer on error instead of retrying `close()` 
or calling `abort()`. Cleaning up the staged file and leaving the target 
untouched on all pre-publication failures (while keeping `EEXIST` -> 
`ConditionNotMatch`) would avoid leaking staging files.



##########
core/services/hf3fs/README.md:
##########
@@ -27,10 +27,14 @@ Use the client library distributed with your 3FS deployment.
 
 The service supports stat, range reads, streaming writes, create directory,
 list, delete, recursive delete, and rename. Writes create parent directories
-and replace existing files; `if_not_exists` rejects an existing file.
-Closing a writer waits for writes and synchronizes the file. Writes are not
-atomic, and failed or aborted writes can leave partial files. Append, native
-copy, presign, and rollback on abort are unsupported. Operations require a
+and replace existing files; `if_not_exists` rejects an existing file. An
+`if_not_exists` write stages data in a temporary file next to the target and
+publishes it when the writer closes; aborting it removes the temporary file,
+which is visible in listings while the write is in progress.
+Closing a writer waits for writes and synchronizes the file. Writes without

Review Comment:
   It would help callers to also note the fixed staging filename prefix (such 
as `.opendal-tmp-...`) alongside listing visibility, and mention that leftover 
staging files can remain in the target directory if post-publish cleanup fails 
or the process crashes before `close()`/`abort()` finishes.



##########
core/services/hf3fs/src/writer.rs:
##########
@@ -139,10 +154,143 @@ impl oio::PositionWrite for Hf3fsWriteHandle {
     }
 
     async fn abort(&self) -> Result<()> {
-        Err(Error::new(
-            ErrorKind::Unsupported,
-            "3FS writes cannot be rolled back",
-        ))
+        let Some(staged) = &self.staged else {
+            return Err(Error::new(
+                ErrorKind::Unsupported,
+                "3FS writes without if_not_exists cannot be rolled back",
+            ));
+        };
+        let staged = Arc::clone(staged);
+        tokio::task::spawn_blocking(move || staged.discard())
+            .await
+            .map_err(new_task_join_error)?
+    }
+}
+
+/// The staged file of an `if_not_exists` write, which becomes visible at
+/// `target` only when `close` publishes it.
+///
+/// 3FS rejects `renameat2` flags, so publishing links the staged file to the
+/// target, which fails when the target exists, and then removes the staged
+/// name. The staged file stays in the target's directory because a hard link
+/// cannot cross filesystems.
+struct StagedFile {
+    /// staged file path
+    path: PathBuf,
+    /// target file path
+    target: PathBuf,
+    /// Held across each publish or discard attempt, so a `close` that is
+    /// cancelled and retried observes the first attempt instead of linking 
twice.
+    state: Mutex<StagedState>,
+}
+
+enum StagedState {
+    /// The staged file exists and the target is untouched.
+    Pending,
+    /// The target names the staged file.
+    Published,
+    /// The staged file was removed without publishing.
+    /// A later `close` reports this error again.
+    Discarded(Error),
+}
+
+impl StagedFile {
+    fn create(target: &Path) -> Result<Self> {
+        let name = target
+            .file_name()
+            .and_then(|name| name.to_str())
+            .ok_or_else(|| Error::new(ErrorKind::IsADirectory, "target is not 
a file path"))?;
+        // Fail fast instead of staging content that the publish must reject.
+        if target.try_exists().map_err(new_std_io_error)? {
+            return Err(Error::new(
+                ErrorKind::ConditionNotMatch,
+                "file already exists",
+            ));
+        }
+        Ok(Self {
+            path: target.with_file_name(build_tmp_path_of(name)),
+            target: target.to_path_buf(),
+            state: Mutex::new(StagedState::Pending),
+        })
+    }
+
+    /// Make the staged file visible at the target without replacing an
+    /// existing entry.
+    fn publish(&self) -> Result<()> {
+        let mut state = self.state.lock().unwrap();
+        match &*state {
+            StagedState::Published => return Ok(()),
+            StagedState::Discarded(err) => return Err(Error::new(err.kind(), 
err.message())),
+            StagedState::Pending => {}
+        }
+
+        let err = match std::fs::hard_link(&self.path, &self.target) {
+            Ok(()) => None,
+            // Another writer published the target while this write was staged.
+            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => 
Some(
+                Error::new(ErrorKind::ConditionNotMatch, "file already 
exists").set_source(err),
+            ),
+            Err(err) => Some(new_std_io_error(err)),
+        };
+        if let Some(mut err) = err {
+            // Keep the staged file when a retried close can still publish it.
+            if err.is_temporary() {
+                return Err(err);
+            }
+            *state = StagedState::Discarded(Error::new(err.kind(), 
err.message()));
+            if let Err(cleanup_err) = std::fs::remove_file(&self.path)
+                && cleanup_err.kind() != std::io::ErrorKind::NotFound
+            {
+                err = err.with_context("staging_cleanup", cleanup_err);
+            }
+            return Err(err);
+        }
+        *state = StagedState::Published;
+
+        match std::fs::remove_file(&self.path) {
+            Ok(()) => Ok(()),
+            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
+            // The target is published, but the staged file is orphaned.
+            Err(err) => {
+                Err(new_std_io_error(err).with_context("service_operation", 
"RemoveStagedFile"))
+            }
+        }

Review Comment:
   Once `hard_link` succeeds, the write is already committed at the target; 
returning an error when `remove_file` fails reports failure for a committed 
object (and causes an `if_not_exists` retry to fail with `ConditionNotMatch`). 
Logging a warning on non-`NotFound` unlink failure and still returning the 
committed success would preserve commit semantics.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to