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 4ab3c1250f refactor(core): use explicit Closed state in BufferSink
(#8915)
4ab3c1250f is described below
commit 4ab3c1250fb4e8706d4dc8c5bf1d373adc7f067b
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 03:11:22 2026 +0800
refactor(core): use explicit Closed state in BufferSink (#8915)
Replace BufferSink's split State::Idle(Option<WriteState>) representation
with State::Idle(WriteState) and an explicit State::Closed variant, mirroring
FuturesDeleteSink from #8865.
Add take_idle_writer for hand-off into in-flight write and close futures,
match State exhaustively across start_send, poll_flush, and poll_close without
.expect() or unreachable!(), preserve close retry semantics on error, and
update the State Sync safety comment.
Add unit tests for close retry followed by closed rejection and for
rejecting poll_flush while a close is in flight.
---
core/core/src/types/write/buffer_sink.rs | 262 ++++++++++++++++++++-----------
1 file changed, 173 insertions(+), 89 deletions(-)
diff --git a/core/core/src/types/write/buffer_sink.rs
b/core/core/src/types/write/buffer_sink.rs
index b3ae491e2c..1c40136fe5 100644
--- a/core/core/src/types/write/buffer_sink.rs
+++ b/core/core/src/types/write/buffer_sink.rs
@@ -35,14 +35,21 @@ pub struct BufferSink {
}
enum State {
- Idle(Option<WriteState>),
+ /// The sink is idle and owns the writer.
+ Idle(WriteState),
+ /// A write request is in flight and owns the writer.
Writing(BoxedStaticFuture<(WriteState, Result<usize>)>),
+ /// A close request is in flight and owns the writer.
Closing(BoxedStaticFuture<(WriteState, Result<Metadata>)>),
+ /// The sink has been closed and accepts no more items.
+ Closed,
}
/// # Safety
///
-/// FuturesReader only exposes `&mut self` to the outside world, so it's safe
to be `Sync`.
+/// `BufferSink` only accesses the writer or in-flight futures stored in
`State`
+/// through `&mut self` (or `Pin<&mut Self>`). Methods taking `&self` only
+/// inspect the enum tag, so `State` is safe to be `Sync`.
unsafe impl Sync for State {}
impl BufferSink {
@@ -50,12 +57,27 @@ impl BufferSink {
#[inline]
pub(crate) fn new(w: WriteState) -> Self {
BufferSink {
- state: State::Idle(Some(w)),
+ state: State::Idle(w),
buf: Buffer::new(),
position: 0,
}
}
+ /// Take the writer out of an idle sink so a request can own it.
+ ///
+ /// Returns `None` and leaves the state unchanged when the sink is not
idle.
+ /// The state has to move out for this hand-off; `State::Closed` only fills
+ /// the slot during that move, and no await point is crossed here.
+ fn take_idle_writer(&mut self) -> Option<WriteState> {
+ match std::mem::replace(&mut self.state, State::Closed) {
+ State::Idle(w) => Some(w),
+ state => {
+ self.state = state;
+ None
+ }
+ }
+ }
+
/// Return the number of bytes accepted by the underlying writer.
///
/// This includes bytes buffered by the writer and any prefix it accepted
@@ -66,7 +88,7 @@ impl BufferSink {
/// Return whether the sink has been closed.
pub(crate) fn is_closed(&self) -> bool {
- matches!(self.state, State::Idle(None))
+ matches!(self.state, State::Closed)
}
/// Return whether the sink is closing.
@@ -83,60 +105,52 @@ impl futures::Sink<Buffer> for BufferSink {
}
fn start_send(mut self: Pin<&mut Self>, item: Buffer) -> Result<()> {
- if self.is_closed() {
- return Err(Error::new(
+ match &self.state {
+ State::Closed => Err(Error::new(
ErrorKind::Unexpected,
"state invalid: sink has been closed",
- ));
- }
-
- if self.is_closing() {
- return Err(Error::new(
+ )),
+ State::Closing(_) => 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(
+ )),
+ // `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.
+ State::Writing(_) => Err(Error::new(
+ ErrorKind::Unexpected,
+ "state invalid: sink is not ready to send, please poll_ready
first",
+ )),
+ State::Idle(_) if !self.buf.is_empty() => Err(Error::new(
ErrorKind::Unexpected,
"state invalid: sink is not ready to send, please poll_ready
first",
- ));
+ )),
+ State::Idle(_) => {
+ self.buf = item;
+ Ok(())
+ }
}
-
- self.buf = item;
- Ok(())
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) ->
Poll<Result<()>> {
let this = self.get_mut();
loop {
match &mut this.state {
- State::Idle(w) => {
- let Some(mut w) = w.take() else {
- return Poll::Ready(Err(Error::new(
- ErrorKind::Unexpected,
- "state invalid: sink has been closed",
- )));
- };
- if this.buf.is_empty() {
- this.state = State::Idle(Some(w));
- return Poll::Ready(Ok(()));
+ State::Idle(_) if this.buf.is_empty() => return
Poll::Ready(Ok(())),
+ State::Idle(_) => {
+ if let Some(mut w) = this.take_idle_writer() {
+ let buf = this.buf.clone();
+ let fut = async move {
+ let res = w.write(buf).await;
+ (w, res)
+ };
+ this.state = State::Writing(Box::pin(fut));
}
- let buf = this.buf.clone();
- let fut = async move {
- let res = w.write(buf).await;
- (w, res)
- };
- this.state = State::Writing(Box::pin(fut));
}
State::Writing(fut) => {
let (w, res) = ready!(fut.as_mut().poll(cx));
- this.state = State::Idle(Some(w));
+ this.state = State::Idle(w);
match res {
Ok(n) => {
this.buf.advance(n);
@@ -151,59 +165,45 @@ impl futures::Sink<Buffer> for BufferSink {
"state invalid: sink is closing",
)));
}
+ State::Closed => {
+ return Poll::Ready(Err(Error::new(
+ ErrorKind::Unexpected,
+ "state invalid: sink has been closed",
+ )));
+ }
}
}
}
- fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) ->
Poll<Result<()>> {
+ fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) ->
Poll<Result<()>> {
+ if !self.is_closing() {
+ ready!(self.as_mut().poll_flush(cx))?;
+ }
+
let this = self.get_mut();
- loop {
- match &mut this.state {
- State::Idle(w) => {
- let Some(mut w) = w.take() else {
- return Poll::Ready(Err(Error::new(
- ErrorKind::Unexpected,
- "state invalid: sink has been closed",
- )));
- };
-
- if this.buf.is_empty() {
- let fut = async move {
- let res = w.close().await;
- (w, res)
- };
- this.state = State::Closing(Box::pin(fut));
- } else {
- let buf = this.buf.clone();
- let fut = async move {
- let res = w.write(buf).await;
- (w, res)
- };
- this.state = State::Writing(Box::pin(fut));
- }
- }
- State::Writing(fut) => {
- let (w, res) = ready!(fut.as_mut().poll(cx));
- this.state = State::Idle(Some(w));
- match res {
- Ok(n) => {
- this.buf.advance(n);
- this.position += n as u64;
- }
- Err(err) => return Poll::Ready(Err(err)),
- }
- }
- State::Closing(fut) => {
- let (w, res) = ready!(fut.as_mut().poll(cx));
- this.state = State::Idle(Some(w));
- match res {
- Ok(_) => {
- this.state = State::Idle(None);
- return Poll::Ready(Ok(()));
- }
- Err(err) => return Poll::Ready(Err(err)),
- }
- }
+ if let Some(mut w) = this.take_idle_writer() {
+ let fut = async move {
+ let res = w.close().await;
+ (w, res)
+ };
+ this.state = State::Closing(Box::pin(fut));
+ }
+
+ let State::Closing(fut) = &mut this.state else {
+ return Poll::Ready(Err(Error::new(
+ ErrorKind::Unexpected,
+ "state invalid: sink has been closed",
+ )));
+ };
+ let (w, res) = ready!(fut.as_mut().poll(cx));
+ match res {
+ Ok(_) => {
+ this.state = State::Closed;
+ Poll::Ready(Ok(()))
+ }
+ Err(err) => {
+ this.state = State::Idle(w);
+ Poll::Ready(Err(err))
}
}
}
@@ -215,6 +215,7 @@ mod tests {
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
+ use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::task::Context;
use std::task::Poll;
@@ -232,6 +233,8 @@ mod tests {
closed: Arc<AtomicBool>,
write_gate: Arc<AtomicBool>,
close_gate: Arc<AtomicBool>,
+ fail_next_close: Arc<AtomicBool>,
+ close_attempts: Arc<AtomicUsize>,
}
fn wait_for(gate: &AtomicBool) -> impl std::future::Future<Output = ()> +
'_ {
@@ -252,7 +255,11 @@ mod tests {
}
async fn close(&mut self) -> Result<Metadata> {
+ self.close_attempts.fetch_add(1, Ordering::SeqCst);
wait_for(&self.close_gate).await;
+ if self.fail_next_close.swap(false, Ordering::SeqCst) {
+ return Err(Error::new(ErrorKind::Unexpected, "close
failed").set_temporary());
+ }
self.closed.store(true, Ordering::SeqCst);
Ok(MetadataBuilder::unknown().build())
}
@@ -269,6 +276,8 @@ mod tests {
closed: Arc<AtomicBool>,
write_gate: Arc<AtomicBool>,
close_gate: Arc<AtomicBool>,
+ fail_next_close: Arc<AtomicBool>,
+ close_attempts: Arc<AtomicUsize>,
}
impl Gates {
@@ -278,6 +287,8 @@ mod tests {
closed: self.closed.clone(),
write_gate: self.write_gate.clone(),
close_gate: self.close_gate.clone(),
+ fail_next_close: self.fail_next_close.clone(),
+ close_attempts: self.close_attempts.clone(),
};
BufferSink::new(WriteState::new(Box::new(writer), None, false))
@@ -400,6 +411,79 @@ mod tests {
assert_eq!(sink.position(), 5);
}
+ #[test]
+ fn test_poll_close_retries_after_failure_then_closes() {
+ let gates = Gates::default();
+ gates.close_gate.store(true, Ordering::SeqCst);
+ gates.fail_next_close.store(true, Ordering::SeqCst);
+ let mut sink = gates.sink();
+ let waker = futures::task::noop_waker();
+ let mut cx = Context::from_waker(&waker);
+
+ let Poll::Ready(Err(err)) = Pin::new(&mut sink).poll_close(&mut cx)
else {
+ panic!("first close must return the writer error");
+ };
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ assert!(err.message().contains("close failed"), "{}", err.message());
+ assert!(!sink.is_closed());
+ assert!(!sink.is_closing());
+ assert!(!gates.closed.load(Ordering::SeqCst));
+ assert_eq!(gates.close_attempts.load(Ordering::SeqCst), 1);
+
+ let Poll::Ready(Ok(())) = Pin::new(&mut sink).poll_close(&mut cx) else
{
+ panic!("second close must succeed after restoring Idle");
+ };
+ assert!(sink.is_closed());
+ assert!(!sink.is_closing());
+ assert!(gates.closed.load(Ordering::SeqCst));
+ assert_eq!(gates.close_attempts.load(Ordering::SeqCst), 2);
+
+ let Poll::Ready(Err(err)) = Pin::new(&mut sink).poll_close(&mut cx)
else {
+ panic!("third close must reject a closed sink");
+ };
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ assert!(
+ err.message().contains("sink has been closed"),
+ "{}",
+ err.message()
+ );
+ assert!(sink.is_closed());
+ assert_eq!(gates.close_attempts.load(Ordering::SeqCst), 2);
+ }
+
+ #[test]
+ fn test_poll_flush_rejects_while_closing() {
+ let gates = Gates::default();
+ let mut sink = gates.sink();
+ let waker = futures::task::noop_waker();
+ let mut cx = Context::from_waker(&waker);
+
+ assert!(Pin::new(&mut sink).poll_close(&mut cx).is_pending());
+ assert!(sink.is_closing());
+ assert!(!sink.is_closed());
+
+ let Poll::Ready(Err(err)) = Pin::new(&mut sink).poll_flush(&mut cx)
else {
+ panic!("flush while closing must fail immediately");
+ };
+ assert_eq!(err.kind(), ErrorKind::Unexpected);
+ assert!(
+ err.message().contains("sink is closing"),
+ "{}",
+ err.message()
+ );
+ assert!(sink.is_closing());
+ assert!(!sink.is_closed());
+
+ gates.close_gate.store(true, Ordering::SeqCst);
+ let Poll::Ready(Ok(())) = Pin::new(&mut sink).poll_close(&mut cx) else
{
+ panic!("in-flight close must complete after rejected flush");
+ };
+ assert!(sink.is_closed());
+ assert!(!sink.is_closing());
+ assert!(gates.closed.load(Ordering::SeqCst));
+ assert_eq!(gates.close_attempts.load(Ordering::SeqCst), 1);
+ }
+
#[tokio::test]
async fn test_trait() {
let op = Operator::via_iter(services::MEMORY_SCHEME, []).unwrap();