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 72829b863e feat: add explicit abort for blocking Writer and Java 
OperatorOutputStream (#9064)
72829b863e is described below

commit 72829b863e141e96b9470cc4af23ba06778bd7e2
Author: Xuanwo <[email protected]>
AuthorDate: Wed Nov 25 19:36:26 2026 +0800

    feat: add explicit abort for blocking Writer and Java OperatorOutputStream 
(#9064)
    
    * feat(bindings/java): support aborting unfinished output streams
    
    * fix(bindings/java): recheck stream state after a flush override
---
 .../org/apache/opendal/OperatorOutputStream.java   | 47 +++++++++++++---
 bindings/java/src/operator_output_stream.rs        | 17 ++++++
 .../test/OperatorInputOutputStreamTest.java        | 64 ++++++++++++++++++++++
 core/core/src/blocking/write/writer.rs             | 53 ++++++++++++++++++
 core/core/src/types/context/write.rs               | 19 +++----
 core/core/src/types/write/writer.rs                | 11 ++--
 website/docs/20-bindings/java/04-tasks.md          | 37 +++++++++++++
 7 files changed, 225 insertions(+), 23 deletions(-)

diff --git 
a/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java 
b/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
index 8c20c601c7..7d4b75fc45 100644
--- a/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
+++ b/bindings/java/src/main/java/org/apache/opendal/OperatorOutputStream.java
@@ -25,11 +25,14 @@ import java.util.Objects;
 
 public class OperatorOutputStream extends OutputStream {
     private static class Writer extends NativeObject {
-        /**
-         * Whether disposing this object commits it. Guarded by the owning
-         * {@link OperatorOutputStream}, which owns the only reference.
-         */
-        private boolean commitOnDispose = true;
+        private enum Disposition {
+            COMMIT,
+            DISCARD,
+            ABORT
+        }
+
+        /** Guarded by the owning {@link OperatorOutputStream}. */
+        private Disposition disposition = Disposition.COMMIT;
 
         private Writer(long nativeHandle) {
             super(nativeHandle);
@@ -39,13 +42,22 @@ public class OperatorOutputStream extends OutputStream {
          * Releases the native writer without committing the object it was 
writing.
          */
         private void discard() {
-            commitOnDispose = false;
+            disposition = Disposition.DISCARD;
+            close();
+        }
+
+        private void abort() {
+            disposition = Disposition.ABORT;
             close();
         }
 
         @Override
         protected void disposeInternal(long handle) {
-            disposeWriter(handle, commitOnDispose);
+            if (disposition == Disposition.ABORT) {
+                abortWriter(handle);
+            } else {
+                disposeWriter(handle, disposition == Disposition.COMMIT);
+            }
         }
     }
 
@@ -129,6 +141,8 @@ public class OperatorOutputStream extends OutputStream {
                         recordFailure(t);
                         OperatorOutputStream.<RuntimeException>sneakyThrow(t);
                     }
+                    // A flush override may close or abort this stream before 
returning.
+                    ensureOpen();
                 }
             }
             off += count;
@@ -144,6 +158,23 @@ public class OperatorOutputStream extends OutputStream {
         }
     }
 
+    /**
+     * Discards buffered bytes and asks the backend to clean up the unfinished 
write.
+     *
+     * <p>Call this before {@link #close()} to abandon an upload, for example 
when reading
+     * the source fails. Cleanup depends on the backend. Data already visible 
may remain,
+     * and a previous object may not be restored.
+     *
+     * <p>This releases the native writer even if cleanup fails. Subsequent 
writes and
+     * flushes throw {@link IllegalStateException}. Subsequent calls to {@code 
abort()} or
+     * {@code close()} do nothing.
+     *
+     * @throws OpenDALException if backend cleanup fails or is unsupported
+     */
+    public synchronized void abort() {
+        writer.abort();
+    }
+
     @Override
     public synchronized void close() {
         if (writer.isDisposed()) {
@@ -276,5 +307,7 @@ public class OperatorOutputStream extends OutputStream {
 
     private static native void disposeWriter(long writer, boolean commit);
 
+    private static native void abortWriter(long writer);
+
     private static native void writeByteRange(long writer, byte[] bytes, int 
off, int len);
 }
diff --git a/bindings/java/src/operator_output_stream.rs 
b/bindings/java/src/operator_output_stream.rs
index 4b99829455..1be576422a 100644
--- a/bindings/java/src/operator_output_stream.rs
+++ b/bindings/java/src/operator_output_stream.rs
@@ -93,6 +93,23 @@ fn intern_dispose_write(writer: &mut blocking::Writer, 
commit: bool) -> crate::R
     Ok(())
 }
 
+/// # Safety
+///
+/// `writer` must be a live pointer from `Box::into_raw` and must not be used 
after this call.
+#[unsafe(no_mangle)]
+pub unsafe extern "system" fn 
Java_org_apache_opendal_OperatorOutputStream_abortWriter<'local>(
+    mut env: EnvUnowned<'local>,
+    _: JClass<'local>,
+    writer: *mut blocking::Writer,
+) {
+    env.with_env(|_env| -> crate::Result<()> {
+        let mut writer = unsafe { Box::from_raw(writer) };
+        writer.abort()?;
+        Ok(())
+    })
+    .resolve::<ThrowException>()
+}
+
 /// # Safety
 ///
 /// `writer` must point to a live writer with exclusive access, and `offset` 
and
diff --git 
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
 
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
index de927cfe00..f9673e6903 100644
--- 
a/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
+++ 
b/bindings/java/src/test/java/org/apache/opendal/test/OperatorInputOutputStreamTest.java
@@ -24,6 +24,7 @@ import static 
org.assertj.core.api.Assertions.assertThatThrownBy;
 import java.io.BufferedReader;
 import java.io.ByteArrayOutputStream;
 import java.io.InputStreamReader;
+import java.nio.file.Files;
 import java.nio.file.Path;
 import java.util.Arrays;
 import java.util.Random;
@@ -511,6 +512,69 @@ public class OperatorInputOutputStreamTest {
         }
     }
 
+    @Test
+    void testOutputStreamAbortDiscardsStagedWriteWithoutFlushing() throws 
Exception {
+        final Path staging = Files.createTempDirectory(tempDir, 
"abort-staging");
+        final ServiceConfig.Fs fs = ServiceConfig.Fs.builder()
+                .root(tempDir.toString())
+                .atomicWriteDir(staging.toString())
+                .build();
+        final String path = "abort-staged";
+        final byte[] original = {1, 2, 3};
+        try (final Operator op = Operator.of(fs)) {
+            op.write(path, original);
+            try (final OperatorOutputStream out =
+                    new OperatorOutputStream(op, path, 8, 
WriteOptions.builder().build()) {
+                        @Override
+                        public synchronized void flush() {
+                            throw new AssertionError("abort or automatic close 
called flush");
+                        }
+                    }) {
+                out.write(new byte[16]);
+                out.write(1);
+                assertThat(staging).isNotEmptyDirectory();
+
+                out.abort();
+                assertThat(staging).isEmptyDirectory();
+                assertThatThrownBy(() -> 
out.write(1)).isInstanceOf(IllegalStateException.class);
+                out.abort();
+            }
+            assertThat(op.read(path)).isEqualTo(original);
+        }
+    }
+
+    @Test
+    void testBulkWriteStopsWhenFlushAbortsStream() throws Exception {
+        final String path = "abort-during-flush";
+        try (final Operator op = 
Operator.of(ServiceConfig.Memory.builder().build())) {
+            try (final OperatorOutputStream out =
+                    new OperatorOutputStream(op, path, 8, 
WriteOptions.builder().build()) {
+                        @Override
+                        public synchronized void flush() {
+                            super.flush();
+                            abort();
+                        }
+                    }) {
+                out.write(1);
+                assertThatThrownBy(() -> out.write(new 
byte[8])).isInstanceOf(IllegalStateException.class);
+            }
+            assertNotExist(op, path);
+        }
+    }
+
+    @Test
+    void testOutputStreamAbortFailureStillClosesStream() throws Exception {
+        final ServiceConfig.Fs fs =
+                ServiceConfig.Fs.builder().root(tempDir.toString()).build();
+        try (final Operator op = Operator.of(fs);
+                final OperatorOutputStream out = 
op.createOutputStream("abort-unstaged", 8)) {
+            out.write(new byte[16]);
+            
assertThatThrownBy(out::abort).is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.Unsupported));
+            assertThatThrownBy(() -> 
out.write(1)).isInstanceOf(IllegalStateException.class);
+            
assertThatThrownBy(out::flush).isInstanceOf(IllegalStateException.class);
+        }
+    }
+
     private static void assertNotExist(Operator op, String path) {
         assertThatThrownBy(() -> 
op.stat(path)).is(OpenDALExceptionCondition.ofSync(OpenDALException.Code.NotFound));
     }
diff --git a/core/core/src/blocking/write/writer.rs 
b/core/core/src/blocking/write/writer.rs
index d5892c3256..09bed65b9f 100644
--- a/core/core/src/blocking/write/writer.rs
+++ b/core/core/src/blocking/write/writer.rs
@@ -73,6 +73,23 @@ impl Writer {
         self.handle.block_on(inner.write(bs))
     }
 
+    /// Abort the writer, discarding buffered data and asking the backend to
+    /// clean up the unfinished write.
+    ///
+    /// Cleanup depends on the backend. In particular, abort cannot guarantee
+    /// that already visible data is removed or that a previous object is 
restored.
+    /// Backend cleanup errors are returned and abort can be retried. Once 
abort
+    /// starts, writes and close return [`ErrorKind::Unexpected`].
+    ///
+    /// This has the same semantics as [`crate::Writer::abort`].
+    pub fn abort(&mut self) -> Result<()> {
+        let Some(inner) = self.inner.as_mut() else {
+            return Err(Error::new(ErrorKind::Unexpected, "writer has been 
dropped"));
+        };
+
+        self.handle.block_on(inner.abort())
+    }
+
     /// Close the writer and make sure all data have been committed.
     ///
     /// ## Notes
@@ -107,3 +124,39 @@ impl Drop for Writer {
         }
     }
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_writer_abort_discards_uncommitted_data() -> Result<()> {
+        let runtime = tokio::runtime::Builder::new_multi_thread()
+            .enable_all()
+            .build()
+            .unwrap();
+        let op = {
+            let _guard = runtime.enter();
+            let op = Operator::new(services::Memory::default())?;
+            blocking::Operator::new(op)?
+        };
+        let path = "target";
+        op.write(path, "original")?;
+        let mut writer = op.writer_options(
+            path,
+            options::WriteOptions {
+                chunk: Some(8),
+                ..Default::default()
+            },
+        )?;
+        writer.write("unfinished write")?;
+
+        writer.abort()?;
+
+        assert_eq!(writer.write("x").unwrap_err().kind(), 
ErrorKind::Unexpected);
+        assert_eq!(writer.close().unwrap_err().kind(), ErrorKind::Unexpected);
+        assert_eq!(writer.abort().unwrap_err().kind(), ErrorKind::Unexpected);
+        assert_eq!(op.read(path)?.to_vec(), b"original");
+        Ok(())
+    }
+}
diff --git a/core/core/src/types/context/write.rs 
b/core/core/src/types/context/write.rs
index 7b9d1e232f..ef7cd560eb 100644
--- a/core/core/src/types/context/write.rs
+++ b/core/core/src/types/context/write.rs
@@ -159,8 +159,8 @@ pub struct WriteState {
     can_copy_from: bool,
     /// Whether a logical write stopped after the inner writer accepted part 
of its input.
     requires_abort: bool,
-    /// Whether abort discarded local data but the underlying cleanup is still 
pending.
-    abort_pending: bool,
+    /// Abort discards buffered data immediately and permanently disables 
writes and close.
+    abort_started: bool,
     /// A source copy that stopped after accepting part of its range.
     pending_copy: Option<Box<PendingCopy>>,
     buffer: oio::QueueBuf,
@@ -180,7 +180,7 @@ impl WriteState {
             exact,
             can_copy_from,
             requires_abort: false,
-            abort_pending: false,
+            abort_started: false,
             pending_copy: None,
             buffer: oio::QueueBuf::new(),
         })
@@ -196,7 +196,7 @@ impl WriteState {
             exact,
             can_copy_from: false,
             requires_abort: false,
-            abort_pending: false,
+            abort_started: false,
             pending_copy: None,
             buffer: oio::QueueBuf::new(),
         }
@@ -237,10 +237,10 @@ impl WriteState {
     }
 
     fn check_not_aborted(&self) -> Result<()> {
-        if self.abort_pending {
+        if self.abort_started {
             return Err(Error::new(
                 ErrorKind::Unexpected,
-                "writer cannot accept data or close while abort is pending",
+                "writer cannot accept data or close after abort has started",
             ));
         }
         if self.requires_abort {
@@ -593,13 +593,10 @@ impl WriteState {
 
     /// Abort the write process.
     pub async fn abort(&mut self) -> Result<()> {
-        // A failed or canceled abort cannot restore the buffered bytes or 
copy offset.
-        self.abort_pending = true;
+        self.abort_started = true;
         self.buffer.clear();
         self.pending_copy = None;
-        self.w.abort().await?;
-        self.abort_pending = false;
-        Ok(())
+        self.w.abort().await
     }
 }
 
diff --git a/core/core/src/types/write/writer.rs 
b/core/core/src/types/write/writer.rs
index 6f67ed3442..86124308e4 100644
--- a/core/core/src/types/write/writer.rs
+++ b/core/core/src/types/write/writer.rs
@@ -281,12 +281,13 @@ impl Writer {
             .await
     }
 
-    /// Abort the writer and clean up all written data.
+    /// Abort the writer, discarding buffered data and asking the backend to
+    /// clean up the unfinished write.
     ///
-    /// ## Notes
-    ///
-    /// Abort should only be called when the writer is not closed or
-    /// aborted, otherwise an unexpected error could be returned.
+    /// Cleanup depends on the backend. In particular, abort cannot guarantee
+    /// that already visible data is removed or that a previous object is 
restored.
+    /// Backend cleanup errors are returned and abort can be retried. Once 
abort
+    /// starts, writes and close return [`ErrorKind::Unexpected`].
     pub async fn abort(&mut self) -> Result<()> {
         self.inner.abort().await
     }
diff --git a/website/docs/20-bindings/java/04-tasks.md 
b/website/docs/20-bindings/java/04-tasks.md
index 57387938cc..97133f6bdf 100644
--- a/website/docs/20-bindings/java/04-tasks.md
+++ b/website/docs/20-bindings/java/04-tasks.md
@@ -136,6 +136,43 @@ try (OutputStream out = op.createOutputStream("big.bin")) {
 }
 ```
 
+When copying from an input stream, a source failure still leaves the output
+stream open. Try-with-resources then closes it and can commit the prefix
+already written. To abandon the upload, catch the failure inside the resource
+block and call `OperatorOutputStream.abort()` before automatic close. Keep the
+original failure, including unchecked cancellation exceptions, and attach any
+abort failure as a suppressed exception. This example uses `transferTo` from
+JDK 9.
+
+```java
+import java.io.InputStream;
+import java.nio.file.Files;
+import org.apache.opendal.OperatorOutputStream;
+
+try (InputStream in = Files.newInputStream(source);
+        OperatorOutputStream out = op.createOutputStream("big.bin")) {
+    try {
+        in.transferTo(out);
+    } catch (Throwable failure) {
+        try {
+            out.abort();
+        } catch (Throwable cleanupFailure) {
+            if (cleanupFailure != failure) {
+                failure.addSuppressed(cleanupFailure);
+            }
+        }
+        throw failure;
+    }
+}
+```
+
+`abort()` discards Java-side buffered bytes and asks the storage backend to
+clean up the unfinished write. The stream closes even if cleanup fails, so
+automatic `close()` never commits after abort. Inspect suppressed exceptions
+for cleanup failures. Cleanup depends on the backend and can leave already
+visible data in place. Restoring a previous object requires backend-specific
+support.
+
 ## Check metadata
 
 ```java

Reply via email to