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 a62ebfc2a4 fix(services/ftp): return file metadata on write close so 
append works (#8740)
a62ebfc2a4 is described below

commit a62ebfc2a47e0f88c9b258bc56eafe12b8eb819c
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 06:55:59 2026 +0800

    fix(services/ftp): return file metadata on write close so append works 
(#8740)
    
    * fix(services/ftp): return file metadata on write close so append works
    
    FtpBackend advertises write_can_append, but every append write failed in
    CompleteWriter::close() because FtpWriter::close() always returned
    unknown metadata instead of the final file metadata. Open the data
    stream on first use (also covering close without writes), finalize the
    transfer, then report the target file size via SIZE. This also makes
    empty writes create the remote file, so advertise write_can_empty.
    
    * chore(services/ftp): regenerate capabilities docs for write_can_empty
    
    * fix(services/ftp): make writer close retry-safe and avoid SIZE for plain 
writes
    
    CompleteWriter keeps the inner writer on error so RetryLayer can retry
    close(). Track close progress (open, finalized, committed) so a retried
    close never re-opens the data stream or renames over the committed
    file, take the stream before flushing so a failed flush drops it, and
    declare the data stream field before the control connection so it is
    closed first on drop. Report metadata from the bytes written for
    regular writes, which also works on servers without RFC 3659 SIZE, and
    query SIZE only for append writes whose final size includes existing
    content.
    
    * fix(services/ftp): never re-open the data stream once consumed by close
    
    FTP cannot distinguish partial from complete staging content, so a
    remote-mutating close step must run at most once. Extend the close
    state machine so any failure after the data stream is consumed lands in
    a terminal Failed state: a retried close then fails permanently instead
    of issuing a second APPE over a possibly partial staging file or
    renaming it onto the target. Only a failed stream open may be retried,
    and data_stream() now errors outside the Transfer state so the stream
    can never be re-opened after consumption.
    
    * fix(services/ftp): mark close Failed before finalizing the data stream
    
    TimeoutLayer can cancel the close future mid-await, bypassing the error
    closures that marked the transfer failed. Poison the state before
    awaiting flush and finalize so both errors and cancellation leave the
    writer Failed, and only advance to Rename after the transfer is
    successfully finalized.
---
 core/services/ftp/src/backend.rs |   1 +
 core/services/ftp/src/reader.rs  |  42 +-------
 core/services/ftp/src/writer.rs  | 202 ++++++++++++++++++++++++++++++++++-----
 website/data/capabilities.json   |   1 +
 4 files changed, 186 insertions(+), 60 deletions(-)

diff --git a/core/services/ftp/src/backend.rs b/core/services/ftp/src/backend.rs
index 03e1e36878..4a27cc0697 100644
--- a/core/services/ftp/src/backend.rs
+++ b/core/services/ftp/src/backend.rs
@@ -147,6 +147,7 @@ impl Builder for FtpBuilder {
             read: true,
 
             write: true,
+            write_can_empty: true,
             write_can_multi: true,
             write_can_append: true,
 
diff --git a/core/services/ftp/src/reader.rs b/core/services/ftp/src/reader.rs
index ac3ded29a1..28542272df 100644
--- a/core/services/ftp/src/reader.rs
+++ b/core/services/ftp/src/reader.rs
@@ -147,8 +147,7 @@ impl FtpLazyWriter {
                 }
             }
 
-            let tmp_path = (!self.append).then(|| 
build_ftp_tmp_path(&self.path));
-            let w = FtpWriter::new(ftp_stream, self.path.clone(), tmp_path);
+            let w = FtpWriter::new(ftp_stream, self.path.clone(), self.append);
             self.inner = Some(w);
         }
 
@@ -156,27 +155,16 @@ impl FtpLazyWriter {
     }
 }
 
-fn build_ftp_tmp_path(path: &str) -> String {
-    let parent = get_parent(path);
-    let tmp_name = build_tmp_path_of(path);
-
-    if parent == "/" {
-        tmp_name
-    } else {
-        format!("{parent}{tmp_name}")
-    }
-}
-
 impl oio::Write for FtpLazyWriter {
     async fn write(&mut self, bs: Buffer) -> Result<()> {
         self.inner().await?.write(bs).await
     }
 
     async fn close(&mut self) -> Result<Metadata> {
-        match &mut self.inner {
-            Some(w) => w.close().await,
-            None => Ok(MetadataBuilder::unknown().build()),
-        }
+        // Create the inner writer even when nothing was written so that
+        // closing the writer still creates or touches the remote file and
+        // reports its final metadata.
+        self.inner().await?.close().await
     }
 
     async fn abort(&mut self) -> Result<()> {
@@ -244,23 +232,3 @@ impl oio::StreamRead for FtpReader {
         Ok((rp, Box::new(stream) as Box<dyn oio::ReadStreamDyn>))
     }
 }
-
-#[cfg(test)]
-mod tests {
-    use super::build_ftp_tmp_path;
-
-    #[test]
-    fn test_build_ftp_tmp_path() {
-        for path in [
-            "example.txt",
-            "folder/example.txt",
-            "folder/subfolder/deep/example.txt",
-            ".hidden dir/.résumé #%.txt",
-        ] {
-            let tmp_path = build_ftp_tmp_path(path);
-            let (stem, suffix) = tmp_path.rsplit_once('.').unwrap();
-            assert_eq!(stem, path);
-            assert!(!suffix.is_empty() && !suffix.contains('/'), "{tmp_path}");
-        }
-    }
-}
diff --git a/core/services/ftp/src/writer.rs b/core/services/ftp/src/writer.rs
index d40341a1cb..e0be505255 100644
--- a/core/services/ftp/src/writer.rs
+++ b/core/services/ftp/src/writer.rs
@@ -25,11 +25,59 @@ use super::core::format_ftp_error;
 use opendal_core::raw::*;
 use opendal_core::*;
 
+/// How far `close` progressed on this writer.
+///
+/// Retry safety: `CompleteWriter` keeps the inner writer on error and
+/// `RetryLayer` may call `close` again after a temporary failure. FTP cannot
+/// tell apart partial and complete staging content afterwards, so every
+/// remote-mutating step must run at most once:
+///
+/// - `Transfer` is the only state that may open or consume the data stream.
+/// - Consuming the stream to finalize it leaves `Transfer` for good. If the
+///   transfer then fails or its outcome is unknown, the state becomes
+///   `Failed`, which fails `close` permanently instead of re-opening `APPE`
+///   or renaming a possibly partial staging file over the target.
+/// - `Rename` and `Report` no longer touch the data stream and are safe to
+///   retry: the staging file already holds the final content.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum CloseState {
+    /// The data stream may still be opened and written to.
+    Transfer,
+    /// The stream was consumed and finalized; a staged tmp file may still
+    /// need the rename onto the target path.
+    Rename,
+    /// The remote file is committed; only metadata reporting remains.
+    Report,
+    /// The transfer was consumed but its outcome failed or is unknown, so
+    /// the remote file may hold partial data. Terminal: `close` fails
+    /// permanently without mutating the remote file again.
+    Failed,
+    /// All steps completed; `close` returns the cached metadata.
+    Done,
+}
+
+impl CloseState {
+    /// The data stream may only be opened while the writer is still in
+    /// `Transfer`. Once the stream was consumed the remote content is out of
+    /// our control and the stream must never be re-opened.
+    fn may_open_data_stream(self) -> bool {
+        self == CloseState::Transfer
+    }
+}
+
 pub struct FtpWriter {
     target_path: String,
     tmp_path: Option<String>,
-    ftp_stream: bounded::Object<Manager>,
+    append: bool,
+    /// Declared before `ftp_stream` so the data connection is always closed
+    /// before the control connection returns to the pool.
     data_stream: Option<Box<dyn AsyncWrite + Sync + Send + Unpin + 'static>>,
+    ftp_stream: bounded::Object<Manager>,
+    /// Bytes actually sent over the data stream.
+    written: u64,
+    /// Metadata reported once the writer reached `CloseState::Done`.
+    result: Option<Metadata>,
+    state: CloseState,
 }
 
 /// # Safety
@@ -43,29 +91,34 @@ unsafe impl Sync for FtpWriter {}
 ///
 /// After we can use data stream, we should return it directly.
 impl FtpWriter {
-    pub fn new(
-        ftp_stream: bounded::Object<Manager>,
-        target_path: String,
-        tmp_path: Option<String>,
-    ) -> Self {
+    pub fn new(ftp_stream: bounded::Object<Manager>, target_path: String, 
append: bool) -> Self {
+        let tmp_path = (!append).then(|| build_ftp_tmp_path(&target_path));
         FtpWriter {
             target_path,
             tmp_path,
-            ftp_stream,
+            append,
             data_stream: None,
+            ftp_stream,
+            written: 0,
+            result: None,
+            state: CloseState::Transfer,
         }
     }
-}
-
-impl oio::Write for FtpWriter {
-    async fn write(&mut self, mut bs: Buffer) -> Result<()> {
-        let path = if let Some(tmp_path) = &self.tmp_path {
-            tmp_path
-        } else {
-            &self.target_path
-        };
 
+    /// Open the data stream on first use so that empty writes and appends
+    /// still create the remote file once the stream is finalized.
+    async fn data_stream(
+        &mut self,
+    ) -> Result<&mut Box<dyn AsyncWrite + Sync + Send + Unpin + 'static>> {
         if self.data_stream.is_none() {
+            if !self.state.may_open_data_stream() {
+                return Err(Error::new(
+                    ErrorKind::Unexpected,
+                    "ftp data stream is already finalized",
+                )
+                .with_operation("FtpWriter::data_stream"));
+            }
+            let path = self.tmp_path.as_ref().unwrap_or(&self.target_path);
             self.data_stream = Some(Box::new(
                 self.ftp_stream
                     .append_with_stream(path)
@@ -74,16 +127,25 @@ impl oio::Write for FtpWriter {
             ));
         }
 
+        Ok(self
+            .data_stream
+            .as_mut()
+            .expect("ftp data stream must be initialized"))
+    }
+}
+
+impl oio::Write for FtpWriter {
+    async fn write(&mut self, mut bs: Buffer) -> Result<()> {
         while bs.has_remaining() {
             let n = self
-                .data_stream
-                .as_mut()
-                .unwrap()
+                .data_stream()
+                .await?
                 .write(bs.chunk())
                 .await
                 .map_err(|err| {
                     Error::new(ErrorKind::Unexpected, "copy from ftp 
stream").set_source(err)
                 })?;
+            self.written += n as u64;
             bs.advance(n);
         }
 
@@ -91,26 +153,77 @@ impl oio::Write for FtpWriter {
     }
 
     async fn close(&mut self) -> Result<Metadata> {
-        let data_stream = self.data_stream.take();
-        if let Some(mut data_stream) = data_stream {
+        // The transfer was already consumed and its outcome failed or is
+        // unknown; the remote file may hold partial data. Fail permanently
+        // so a retried close can never commit it.
+        if self.state == CloseState::Failed {
+            return Err(Error::new(
+                ErrorKind::Unexpected,
+                "ftp write transfer already failed; the remote file may hold 
partial data",
+            )
+            .with_operation("FtpWriter::close"));
+        }
+
+        if self.state == CloseState::Transfer {
+            // Opening the stream covers closing without any write. A failed
+            // open is the only step a retry may repeat, since the stream was
+            // never consumed at this point.
+            self.data_stream().await?;
+            // Take the stream before flushing so a failed flush drops the
+            // data connection instead of leaving it open.
+            let mut data_stream = self
+                .data_stream
+                .take()
+                .expect("ftp data stream must be initialized");
+            // Consuming the stream is the point of no return: any error or
+            // future cancellation from now on leaves the remote content
+            // unknown, so stay Failed until the transfer is finalized.
+            self.state = CloseState::Failed;
             data_stream.flush().await.map_err(|err| {
                 Error::new(ErrorKind::Unexpected, "flush data stream 
failed").set_source(err)
             })?;
-
             self.ftp_stream
                 .finalize_put_stream(data_stream)
                 .await
                 .map_err(format_ftp_error)?;
+            self.state = CloseState::Rename;
+        }
 
+        if self.state == CloseState::Rename {
             if let Some(tmp_path) = &self.tmp_path {
                 self.ftp_stream
                     .rename(tmp_path, &self.target_path)
                     .await
                     .map_err(format_ftp_error)?;
+                self.tmp_path = None;
             }
+            self.state = CloseState::Report;
         }
 
-        Ok(MetadataBuilder::unknown().build())
+        if self.state == CloseState::Report {
+            // An append's final size includes pre-existing content, so query
+            // it from the server; a regular write reports the bytes sent
+            // through this stream, which also works on servers without
+            // RFC 3659 SIZE.
+            let metadata = if self.append {
+                let size = self
+                    .ftp_stream
+                    .size(&self.target_path)
+                    .await
+                    .map_err(format_ftp_error)?;
+                MetadataBuilder::file(size as u64).build()
+            } else {
+                MetadataBuilder::file(self.written).build()
+            };
+            self.result = Some(metadata);
+            self.state = CloseState::Done;
+        }
+
+        debug_assert_eq!(self.state, CloseState::Done);
+        Ok(self
+            .result
+            .clone()
+            .expect("ftp writer must have reported metadata"))
     }
 
     async fn abort(&mut self) -> Result<()> {
@@ -120,3 +233,46 @@ impl oio::Write for FtpWriter {
         ))
     }
 }
+
+fn build_ftp_tmp_path(path: &str) -> String {
+    let parent = get_parent(path);
+    let tmp_name = build_tmp_path_of(path);
+
+    if parent == "/" {
+        tmp_name
+    } else {
+        format!("{parent}{tmp_name}")
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_build_ftp_tmp_path() {
+        for path in [
+            "example.txt",
+            "folder/example.txt",
+            "folder/subfolder/deep/example.txt",
+            ".hidden dir/.résumé #%.txt",
+        ] {
+            let tmp_path = build_ftp_tmp_path(path);
+            let (stem, suffix) = tmp_path.rsplit_once('.').unwrap();
+            assert_eq!(stem, path);
+            assert!(!suffix.is_empty() && !suffix.contains('/'), "{tmp_path}");
+        }
+    }
+
+    /// Once the data stream was consumed, the remote content is out of our
+    /// control: the stream must never be re-opened, and a failed or finished
+    /// close must not be able to mutate the remote file again.
+    #[test]
+    fn only_transfer_may_open_data_stream() {
+        assert!(CloseState::Transfer.may_open_data_stream());
+        assert!(!CloseState::Rename.may_open_data_stream());
+        assert!(!CloseState::Report.may_open_data_stream());
+        assert!(!CloseState::Failed.may_open_data_stream());
+        assert!(!CloseState::Done.may_open_data_stream());
+    }
+}
diff --git a/website/data/capabilities.json b/website/data/capabilities.json
index 2b255f66f5..16ab27226a 100644
--- a/website/data/capabilities.json
+++ b/website/data/capabilities.json
@@ -1160,6 +1160,7 @@
         "stat": true,
         "write": true,
         "write_can_append": true,
+        "write_can_empty": true,
         "write_can_multi": true
       }
     },

Reply via email to