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 8f703dabf3 fix(core): commit buffered data when StdWriter is dropped 
and validate write sink state (#8846)
8f703dabf3 is described below

commit 8f703dabf32897ff23afa70b2191c3ae035e17bb
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 22:56:06 2026 +0800

    fix(core): commit buffered data when StdWriter is dropped and validate 
write sink state (#8846)
    
    * fix(core): commit buffered data when StdWriter is dropped
    
    `StdWriter` documents that files are closed when they go out of scope, but
    `Drop` only dropped the inner writer. Data written through `std::io::Write`
    stayed in the 256 KiB `FuturesAsyncWriter` buffer and never reached the
    service, so callers that rely on drop, such as `std::io::copy` or
    `serde_json::to_writer`, silently lost it.
    
    `Drop` now closes the writer unless it is already closed and keeps ignoring
    close errors. `StdWriter::close` leaves the sink closed, so `Drop` skips the
    second close instead of closing an already closed writer.
    
    `BufferSink::start_send` also accepted items it could not keep: a closing 
sink
    discarded them on close, a sink with an in-flight write overwrote the 
pending
    item, and a sink with a buffered item dropped that item. `start_send` now
    requires an idle sink with an empty buffer, and 
`FuturesAsyncWriter::poll_write`
    rejects writes once close has started, so bytes reported as accepted can no
    longer be lost.
    
    * fix(core): skip StdWriter drop close after failed calls
    
    `StdWriter::drop` closed the inner writer whenever the sink still looked 
open.
    A failed `StdWriter::close` leaves the sink open, so `Drop` retried the 
close
    the caller had already been told failed: with `MemoryWriter` and
    `if_not_exists` that retry could store a 0-byte object, and under 
`RetryLayer`
    it could run blocking retries on the dropping thread. A failed `write` or
    `flush` was handled the same way, so `Drop` could publish a truncated object
    after the caller stopped on `?`.
    
    `StdWriter` now records a failed `close` and any failed `write` or `flush`, 
and
    `Drop` closes only a writer the caller left healthy. A later successful
    `write` or `flush` clears that error, so a recovered stream still closes and
    commits on drop. `close` itself is unchanged: calling it again still 
retries,
    and a second close still reports the sink's own error.
    
    The tests now drive an injectable `oio::Write` that counts `close` calls
    instead of inspecting internal state, and cover a successful close, a failed
    close, a failed flush, a failed write, and a write failure the caller
    recovered from.
---
 core/core/src/blocking/write/std_writer.rs        | 331 +++++++++++++++++++++-
 core/core/src/types/write/buffer_sink.rs          | 171 +++++++++++
 core/core/src/types/write/futures_async_writer.rs |  96 +++++++
 3 files changed, 593 insertions(+), 5 deletions(-)

diff --git a/core/core/src/blocking/write/std_writer.rs 
b/core/core/src/blocking/write/std_writer.rs
index 51f9be75fd..31042be980 100644
--- a/core/core/src/blocking/write/std_writer.rs
+++ b/core/core/src/blocking/write/std_writer.rs
@@ -29,9 +29,25 @@ use crate::*;
 ///
 /// Files are automatically closed when they go out of scope. Errors detected 
on closing are ignored
 /// by the implementation of Drop. Use the method `close` if these errors must 
be manually handled.
+///
+/// Drop does not close a writer whose `write`, `flush`, or `close` call 
returned an error. Closing
+/// such a writer could store data that the caller was told was not stored. 
Call `close` again to
+/// retry a failed `close`.
 pub struct StdWriter {
     handle: tokio::runtime::Handle,
     w: Option<FuturesAsyncWriter>,
+    /// Whether an attempted `close` left the sink open.
+    ///
+    /// A failed `close` leaves the sink open, so Drop must not close it 
again: the retry could
+    /// store the data the caller was told was not stored, or block the 
dropping thread on another
+    /// attempt.
+    close_failed: bool,
+    /// Whether the last `write` or `flush` call returned an error.
+    ///
+    /// Closing after a failed call can publish a truncated object, because 
bytes accepted before
+    /// the error may never have reached the service. A later successful call 
clears this flag so
+    /// a recovered writer still closes on drop.
+    has_error: bool,
 }
 
 impl StdWriter {
@@ -41,16 +57,24 @@ impl StdWriter {
         StdWriter {
             handle,
             w: Some(w.into_futures_async_write()),
+            close_failed: false,
+            has_error: false,
         }
     }
 
     /// Close the internal writer and make sure all data have been stored.
     pub fn close(&mut self) -> std::io::Result<()> {
+        // Assume the close fails until the sink confirms it, so a `close` 
that panics through this
+        // method also leaves a writer that Drop will not retry.
+        self.close_failed = true;
+
         let Some(w) = self.w.as_mut() else {
             return Err(Error::new(ErrorKind::Unexpected, "writer has been 
dropped").into());
         };
 
-        self.handle.block_on(w.close())
+        let result = self.handle.block_on(w.close());
+        self.close_failed = result.is_err();
+        result
     }
 }
 
@@ -60,7 +84,12 @@ impl Write for StdWriter {
             return Err(Error::new(ErrorKind::Unexpected, "writer has been 
dropped").into());
         };
 
-        self.handle.block_on(w.write(buf))
+        let written = self.handle.block_on(w.write(buf));
+        // An empty write transfers nothing, so it cannot prove the writer 
recovered.
+        if !buf.is_empty() {
+            self.has_error = written.is_err();
+        }
+        written
     }
 
     fn flush(&mut self) -> std::io::Result<()> {
@@ -68,15 +97,307 @@ impl Write for StdWriter {
             return Err(Error::new(ErrorKind::Unexpected, "writer has been 
dropped").into());
         };
 
-        self.handle.block_on(w.flush())
+        let flushed = self.handle.block_on(w.flush());
+        self.has_error = flushed.is_err();
+        flushed
     }
 }
 
 /// Make sure the inner writer is dropped in async context.
 impl Drop for StdWriter {
     fn drop(&mut self) {
-        if let Some(v) = self.w.take() {
-            self.handle.block_on(async move { drop(v) });
+        let Some(mut v) = self.w.take() else {
+            return;
+        };
+
+        // Only close a writer the caller left healthy. Retrying a failed 
`close`, `write`, or
+        // `flush` here could store data the caller knows is incomplete or was 
told had failed.
+        let should_close = !self.close_failed && !self.has_error;
+
+        self.handle.block_on(async move {
+            // Data that has been written but not sent yet lives in the 
writer's
+            // internal buffer, so dropping without closing would lose it. 
Close
+            // errors are ignored here, as documented for this adapter.
+            //
+            // A writer that `close` already closed is skipped: closing a 
closed
+            // writer returns an error instead of closing it again.
+            if should_close && !v.is_closed() {
+                let _ = v.close().await;
+            }
+
+            drop(v);
+        });
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use std::io;
+    use std::io::Write;
+    use std::sync::Arc;
+    use std::sync::atomic::AtomicUsize;
+    use std::sync::atomic::Ordering;
+
+    use super::*;
+    use crate::blocking;
+    use crate::raw::*;
+    use crate::services;
+
+    const PAYLOAD: &[u8] = b"hello, world";
+
+    /// Buffer capacity inside [`FuturesAsyncWriter`]. Writes that fill it 
leave data the sink still
+    /// has to send.
+    const WRITER_BUFFER_SIZE: usize = 256 * 1024;
+
+    fn new_operator() -> crate::Result<blocking::Operator> {
+        let op = Operator::new(services::Memory::default())?;
+        blocking::Operator::new(op)
+    }
+
+    /// Run a blocking write body and wait for its result.
+    async fn run_blocking<T, F>(f: F) -> std::io::Result<T>
+    where
+        F: FnOnce() -> std::io::Result<T> + Send + 'static,
+        T: Send + 'static,
+    {
+        tokio::task::spawn_blocking(f)
+            .await
+            .expect("blocking write task must complete")
+    }
+
+    /// An `oio::Write` that counts `close` calls and can inject failures.
+    struct CountingWriter {
+        close_calls: Arc<AtomicUsize>,
+        /// Number of upcoming `write` calls that fail before later calls 
succeed.
+        write_failures: usize,
+        fail_close: bool,
+    }
+
+    impl oio::Write for CountingWriter {
+        async fn write(&mut self, _: Buffer) -> Result<()> {
+            if self.write_failures > 0 {
+                self.write_failures -= 1;
+                return Err(Error::new(ErrorKind::Unexpected, "injected write 
failure"));
+            }
+
+            Ok(())
+        }
+
+        async fn close(&mut self) -> Result<Metadata> {
+            self.close_calls.fetch_add(1, Ordering::SeqCst);
+
+            if self.fail_close {
+                return Err(Error::new(ErrorKind::Unexpected, "injected close 
failure"));
+            }
+
+            Ok(MetadataBuilder::unknown().build())
+        }
+
+        async fn abort(&mut self) -> Result<()> {
+            Ok(())
+        }
+    }
+
+    /// Build a [`StdWriter`] around a [`CountingWriter`].
+    ///
+    /// Call this from a blocking context: [`StdWriter`] blocks on the runtime 
for every operation,
+    /// including `Drop`.
+    fn counting_std_writer(
+        close_calls: Arc<AtomicUsize>,
+        write_failures: usize,
+        fail_close: bool,
+    ) -> StdWriter {
+        let writer = CountingWriter {
+            close_calls,
+            write_failures,
+            fail_close,
+        };
+        let write_state = WriteState::new(Box::new(writer), None, false);
+
+        StdWriter {
+            handle: tokio::runtime::Handle::current(),
+            w: Some(FuturesAsyncWriter::new(write_state)),
+            close_failed: false,
+            has_error: false,
         }
     }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn test_drop_without_close_persists_data() {
+        let op = new_operator().expect("memory operator must be created");
+
+        let written = run_blocking(move || -> std::io::Result<Vec<u8>> {
+            let path = "test_drop_without_close_persists_data";
+            let mut w = 
op.writer(path).map_err(io::Error::from)?.into_std_write();
+            w.write_all(PAYLOAD)?;
+
+            drop(w);
+
+            Ok(op.read(path).map_err(io::Error::from)?.to_vec())
+        })
+        .await
+        .expect("blocking write must succeed");
+
+        assert_eq!(written, PAYLOAD);
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn test_drop_after_flush_persists_data() {
+        let op = new_operator().expect("memory operator must be created");
+
+        let written = run_blocking(move || -> std::io::Result<Vec<u8>> {
+            let path = "test_drop_after_flush_persists_data";
+            let mut w = 
op.writer(path).map_err(io::Error::from)?.into_std_write();
+            w.write_all(PAYLOAD)?;
+            w.flush()?;
+
+            drop(w);
+
+            Ok(op.read(path).map_err(io::Error::from)?.to_vec())
+        })
+        .await
+        .expect("blocking write must succeed");
+
+        assert_eq!(written, PAYLOAD);
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn test_drop_after_close_does_not_close_again() {
+        let close_calls = Arc::new(AtomicUsize::new(0));
+        let calls = close_calls.clone();
+
+        run_blocking(move || -> std::io::Result<()> {
+            let mut w = counting_std_writer(calls, 0, false);
+            w.write_all(PAYLOAD)?;
+            w.close()?;
+
+            drop(w);
+
+            Ok(())
+        })
+        .await
+        .expect("blocking write must succeed");
+
+        assert_eq!(
+            close_calls.load(Ordering::SeqCst),
+            1,
+            "drop must not close a writer that close already closed"
+        );
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn test_drop_after_failed_close_does_not_close_again() {
+        let close_calls = Arc::new(AtomicUsize::new(0));
+        let calls = close_calls.clone();
+
+        run_blocking(move || -> std::io::Result<()> {
+            let mut w = counting_std_writer(calls, 0, true);
+            let err = w.close().expect_err("injected close failure must 
surface");
+            assert!(err.to_string().contains("injected close failure"), 
"{err}");
+
+            drop(w);
+
+            Ok(())
+        })
+        .await
+        .expect("blocking write must succeed");
+
+        assert_eq!(
+            close_calls.load(Ordering::SeqCst),
+            1,
+            "drop must not retry a failed close"
+        );
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn test_drop_after_failed_flush_does_not_close() {
+        let close_calls = Arc::new(AtomicUsize::new(0));
+        let calls = close_calls.clone();
+
+        run_blocking(move || -> std::io::Result<()> {
+            let mut w = counting_std_writer(calls, 1, false);
+            w.write_all(PAYLOAD)?;
+            let err = w.flush().expect_err("injected write failure must 
surface");
+            assert!(err.to_string().contains("injected write failure"), 
"{err}");
+
+            drop(w);
+
+            Ok(())
+        })
+        .await
+        .expect("blocking write must succeed");
+
+        assert_eq!(
+            close_calls.load(Ordering::SeqCst),
+            0,
+            "drop must not commit after a failed flush"
+        );
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn test_drop_after_failed_write_does_not_close() {
+        let close_calls = Arc::new(AtomicUsize::new(0));
+        let calls = close_calls.clone();
+
+        run_blocking(move || -> std::io::Result<()> {
+            let mut w = counting_std_writer(calls, 1, false);
+            let chunk = vec![b'a'; WRITER_BUFFER_SIZE];
+
+            // The first write fills the adapter buffer, the second moves it 
into the sink and
+            // refills the buffer, and the third has to send the buffered data 
through the writer.
+            w.write_all(&chunk)?;
+            w.write_all(&chunk)?;
+            let err = w
+                .write_all(&chunk)
+                .expect_err("injected write failure must surface");
+            assert!(err.to_string().contains("injected write failure"), 
"{err}");
+
+            // An empty write transfers nothing, so it must not mark the 
writer healthy again.
+            assert_eq!(w.write(b"")?, 0);
+
+            drop(w);
+
+            Ok(())
+        })
+        .await
+        .expect("blocking write must succeed");
+
+        assert_eq!(
+            close_calls.load(Ordering::SeqCst),
+            0,
+            "drop must not commit a truncated object"
+        );
+    }
+
+    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+    async fn test_drop_closes_after_write_error_is_recovered() {
+        let close_calls = Arc::new(AtomicUsize::new(0));
+        let calls = close_calls.clone();
+
+        run_blocking(move || -> std::io::Result<()> {
+            let mut w = counting_std_writer(calls, 1, false);
+            let chunk = vec![b'a'; WRITER_BUFFER_SIZE];
+
+            w.write_all(&chunk)?;
+            w.write_all(&chunk)?;
+            w.write_all(&chunk)
+                .expect_err("injected write failure must surface");
+
+            // The adapter keeps the rejected buffer and sends it again, so 
this write succeeds and
+            // marks the writer healthy.
+            w.write_all(&chunk)?;
+
+            drop(w);
+
+            Ok(())
+        })
+        .await
+        .expect("blocking write must succeed");
+
+        assert_eq!(
+            close_calls.load(Ordering::SeqCst),
+            1,
+            "drop must close a writer that recovered from a failed write"
+        );
+    }
 }
diff --git a/core/core/src/types/write/buffer_sink.rs 
b/core/core/src/types/write/buffer_sink.rs
index af3f404d60..b3ae491e2c 100644
--- a/core/core/src/types/write/buffer_sink.rs
+++ b/core/core/src/types/write/buffer_sink.rs
@@ -68,6 +68,11 @@ impl BufferSink {
     pub(crate) fn is_closed(&self) -> bool {
         matches!(self.state, State::Idle(None))
     }
+
+    /// Return whether the sink is closing.
+    pub(crate) fn is_closing(&self) -> bool {
+        matches!(self.state, State::Closing(_))
+    }
 }
 
 impl futures::Sink<Buffer> for BufferSink {
@@ -85,6 +90,24 @@ impl futures::Sink<Buffer> for BufferSink {
             ));
         }
 
+        if self.is_closing() {
+            return Err(Error::new(
+                ErrorKind::Unexpected,
+                "state invalid: sink is closing",
+            ));
+        }
+
+        // `Writing` means a previous item is still in flight, and a non-empty
+        // buffer means a previous item has not been flushed yet. Overwriting 
it
+        // here would either lose that item on close or corrupt it when the
+        // in-flight write reports how many bytes it accepted.
+        if matches!(self.state, State::Writing(_)) || !self.buf.is_empty() {
+            return Err(Error::new(
+                ErrorKind::Unexpected,
+                "state invalid: sink is not ready to send, please poll_ready 
first",
+            ));
+        }
+
         self.buf = item;
         Ok(())
     }
@@ -188,13 +211,79 @@ impl futures::Sink<Buffer> for BufferSink {
 
 #[cfg(test)]
 mod tests {
+    use std::pin::Pin;
     use std::sync::Arc;
+    use std::sync::Mutex;
+    use std::sync::atomic::AtomicBool;
+    use std::sync::atomic::Ordering;
+    use std::task::Context;
+    use std::task::Poll;
 
+    use futures::Sink;
     use futures::SinkExt;
 
     use crate::raw::*;
     use crate::*;
 
+    /// A writer whose `write` and `close` stay pending until the test opens 
the
+    /// matching gate.
+    struct GatedWriter {
+        writes: Arc<Mutex<Vec<Vec<u8>>>>,
+        closed: Arc<AtomicBool>,
+        write_gate: Arc<AtomicBool>,
+        close_gate: Arc<AtomicBool>,
+    }
+
+    fn wait_for(gate: &AtomicBool) -> impl std::future::Future<Output = ()> + 
'_ {
+        futures::future::poll_fn(move |_| {
+            if gate.load(Ordering::SeqCst) {
+                Poll::Ready(())
+            } else {
+                Poll::Pending
+            }
+        })
+    }
+
+    impl oio::Write for GatedWriter {
+        async fn write(&mut self, bs: Buffer) -> Result<()> {
+            wait_for(&self.write_gate).await;
+            self.writes.lock().unwrap().push(bs.to_vec());
+            Ok(())
+        }
+
+        async fn close(&mut self) -> Result<Metadata> {
+            wait_for(&self.close_gate).await;
+            self.closed.store(true, Ordering::SeqCst);
+            Ok(MetadataBuilder::unknown().build())
+        }
+
+        async fn abort(&mut self) -> Result<()> {
+            Ok(())
+        }
+    }
+
+    /// Handles shared with a [`GatedWriter`] so tests can observe and drive 
it.
+    #[derive(Default)]
+    struct Gates {
+        writes: Arc<Mutex<Vec<Vec<u8>>>>,
+        closed: Arc<AtomicBool>,
+        write_gate: Arc<AtomicBool>,
+        close_gate: Arc<AtomicBool>,
+    }
+
+    impl Gates {
+        fn sink(&self) -> BufferSink {
+            let writer = GatedWriter {
+                writes: self.writes.clone(),
+                closed: self.closed.clone(),
+                write_gate: self.write_gate.clone(),
+                close_gate: self.close_gate.clone(),
+            };
+
+            BufferSink::new(WriteState::new(Box::new(writer), None, false))
+        }
+    }
+
     #[tokio::test]
     async fn test_sink_rejects_write_and_flush_after_close() {
         let op = Operator::via_iter(services::MEMORY_SCHEME, []).unwrap();
@@ -229,6 +318,88 @@ mod tests {
         );
     }
 
+    #[test]
+    fn test_start_send_rejects_item_while_closing() {
+        let gates = Gates::default();
+        let mut sink = gates.sink();
+        let waker = futures::task::noop_waker();
+        let mut cx = Context::from_waker(&waker);
+
+        // Nothing has been buffered, so close goes straight into closing.
+        assert!(Pin::new(&mut sink).poll_close(&mut cx).is_pending());
+
+        let err = Pin::new(&mut sink)
+            .start_send(Buffer::from("late"))
+            .expect_err("closing sink must reject items");
+        assert_eq!(err.kind(), ErrorKind::Unexpected);
+        assert!(
+            err.message().contains("sink is closing"),
+            "{}",
+            err.message()
+        );
+
+        gates.close_gate.store(true, Ordering::SeqCst);
+        assert!(Pin::new(&mut sink).poll_close(&mut cx).is_ready());
+        assert!(gates.closed.load(Ordering::SeqCst));
+        assert!(gates.writes.lock().unwrap().is_empty());
+    }
+
+    #[test]
+    fn test_start_send_rejects_item_while_writing() {
+        let gates = Gates::default();
+        let mut sink = gates.sink();
+        let waker = futures::task::noop_waker();
+        let mut cx = Context::from_waker(&waker);
+
+        Pin::new(&mut sink)
+            .start_send(Buffer::from("first"))
+            .expect("idle sink must accept the first item");
+        // Flushing moves the buffered item into the in-flight write.
+        assert!(Pin::new(&mut sink).poll_flush(&mut cx).is_pending());
+
+        let err = Pin::new(&mut sink)
+            .start_send(Buffer::from("second"))
+            .expect_err("sink with an in-flight write must reject items");
+        assert_eq!(err.kind(), ErrorKind::Unexpected);
+        assert!(
+            err.message().contains("not ready to send"),
+            "{}",
+            err.message()
+        );
+
+        gates.write_gate.store(true, Ordering::SeqCst);
+        assert!(Pin::new(&mut sink).poll_flush(&mut cx).is_ready());
+        assert_eq!(*gates.writes.lock().unwrap(), vec![b"first".to_vec()]);
+    }
+
+    #[test]
+    fn test_start_send_rejects_overwriting_buffered_item() {
+        let gates = Gates::default();
+        gates.write_gate.store(true, Ordering::SeqCst);
+        let mut sink = gates.sink();
+        let waker = futures::task::noop_waker();
+        let mut cx = Context::from_waker(&waker);
+
+        Pin::new(&mut sink)
+            .start_send(Buffer::from("first"))
+            .expect("idle sink must accept the first item");
+
+        let err = Pin::new(&mut sink)
+            .start_send(Buffer::from("second"))
+            .expect_err("sink with a buffered item must reject items");
+        assert_eq!(err.kind(), ErrorKind::Unexpected);
+        assert!(
+            err.message().contains("not ready to send"),
+            "{}",
+            err.message()
+        );
+        assert_eq!(sink.position(), 0);
+
+        assert!(Pin::new(&mut sink).poll_flush(&mut cx).is_ready());
+        assert_eq!(*gates.writes.lock().unwrap(), vec![b"first".to_vec()]);
+        assert_eq!(sink.position(), 5);
+    }
+
     #[tokio::test]
     async fn test_trait() {
         let op = Operator::via_iter(services::MEMORY_SCHEME, []).unwrap();
diff --git a/core/core/src/types/write/futures_async_writer.rs 
b/core/core/src/types/write/futures_async_writer.rs
index 6c9588a9a2..3d8e964286 100644
--- a/core/core/src/types/write/futures_async_writer.rs
+++ b/core/core/src/types/write/futures_async_writer.rs
@@ -60,6 +60,12 @@ impl FuturesAsyncWriter {
             buf: oio::FlexBuf::new(256 * 1024),
         }
     }
+
+    /// Return whether the underlying sink has been closed.
+    #[cfg(feature = "blocking")]
+    pub(crate) fn is_closed(&self) -> bool {
+        self.sink.is_closed()
+    }
 }
 
 impl AsyncWrite for FuturesAsyncWriter {
@@ -81,6 +87,15 @@ impl AsyncWrite for FuturesAsyncWriter {
             ))));
         }
 
+        // Bytes accepted here would stay in `buf` while the sink finishes
+        // closing, so they would never reach the service.
+        if this.sink.is_closing() {
+            return Poll::Ready(Err(format_std_io_error(Error::new(
+                ErrorKind::Unexpected,
+                "state invalid: sink is closing",
+            ))));
+        }
+
         loop {
             let n = this.buf.put(buf);
             if n > 0 {
@@ -136,8 +151,13 @@ impl AsyncWrite for FuturesAsyncWriter {
 
 #[cfg(test)]
 mod tests {
+    use std::pin::Pin;
     use std::sync::Arc;
     use std::sync::Mutex;
+    use std::sync::atomic::AtomicBool;
+    use std::sync::atomic::Ordering;
+    use std::task::Context;
+    use std::task::Poll;
 
     use futures::AsyncWriteExt;
 
@@ -174,6 +194,38 @@ mod tests {
         FuturesAsyncWriter::new(write_state)
     }
 
+    /// A writer whose `close` stays pending until the test releases the gate.
+    struct GatedCloseWriter {
+        writes: Arc<Mutex<Vec<Vec<u8>>>>,
+        close_started: Arc<AtomicBool>,
+        close_gate: Arc<AtomicBool>,
+    }
+
+    impl oio::Write for GatedCloseWriter {
+        async fn write(&mut self, bs: Buffer) -> Result<()> {
+            self.writes.lock().unwrap().push(bs.to_vec());
+            Ok(())
+        }
+
+        async fn close(&mut self) -> Result<Metadata> {
+            self.close_started.store(true, Ordering::SeqCst);
+            futures::future::poll_fn(|_| {
+                if self.close_gate.load(Ordering::SeqCst) {
+                    Poll::Ready(())
+                } else {
+                    Poll::Pending
+                }
+            })
+            .await;
+
+            Ok(MetadataBuilder::unknown().build())
+        }
+
+        async fn abort(&mut self) -> Result<()> {
+            Ok(())
+        }
+    }
+
     #[tokio::test]
     async fn test_flush_drives_underlying_write() {
         let writes = Arc::new(Mutex::new(Vec::new()));
@@ -231,6 +283,50 @@ mod tests {
         assert!(err.to_string().contains("sink has been closed"), "{err}");
     }
 
+    #[test]
+    fn test_poll_write_rejected_while_closing() {
+        let writes = Arc::new(Mutex::new(Vec::new()));
+        let close_started = Arc::new(AtomicBool::new(false));
+        let close_gate = Arc::new(AtomicBool::new(false));
+
+        let write_state = WriteState::new(
+            Box::new(GatedCloseWriter {
+                writes: writes.clone(),
+                close_started: close_started.clone(),
+                close_gate: close_gate.clone(),
+            }),
+            None,
+            false,
+        );
+        let mut w = FuturesAsyncWriter::new(write_state);
+
+        let waker = futures::task::noop_waker();
+        let mut cx = Context::from_waker(&waker);
+        let mut w = Pin::new(&mut w);
+
+        // The payload stays in the 256 KiB buffer until close flushes it.
+        let written = match w.as_mut().poll_write(&mut cx, b"hello") {
+            Poll::Ready(Ok(written)) => written,
+            _ => panic!("poll_write must accept the payload"),
+        };
+        assert_eq!(written, 5);
+
+        // Close sends the buffered payload and then parks in the closing 
state.
+        assert!(w.as_mut().poll_close(&mut cx).is_pending());
+        assert!(close_started.load(Ordering::SeqCst));
+
+        let err = match w.as_mut().poll_write(&mut cx, b"late") {
+            Poll::Ready(Err(err)) => err,
+            _ => panic!("poll_write must fail while the sink is closing"),
+        };
+        assert!(err.to_string().contains("sink is closing"), "{err}");
+
+        close_gate.store(true, Ordering::SeqCst);
+        assert!(w.as_mut().poll_close(&mut cx).is_ready());
+
+        assert_eq!(*writes.lock().unwrap(), vec![b"hello".to_vec()]);
+    }
+
     #[tokio::test]
     async fn test_trait() {
         let op = Operator::via_iter(services::MEMORY_SCHEME, []).unwrap();

Reply via email to