This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/main by this push:
     new a0f5e729312d CAMEL-27455: camel-aws2-s3 - streaming upload keeps the 
data of a failed timeout upload and takes a failed exchange out of the open 
upload (#30811)
a0f5e729312d is described below

commit a0f5e729312d44692747f7959ace86424a438028
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:40:07 2026 +0530

    CAMEL-27455: camel-aws2-s3 - streaming upload keeps the data of a failed 
timeout upload and takes a failed exchange out of the open upload (#30811)
    
    When uploading the data buffered for the streamingUploadTimeout failed, the 
timeout task logged a WARN and forgot it
    (the open upload, or the timestamp window), although the exchanges of that 
data had returned success, and the
    multipart upload stayed open. The task now keeps the data for the next run 
of the timeout or the next exchange. After
    3 runs that failed to upload it, it aborts the upload; a part uploaded in 
between by an exchange starts the count
    again. When the data is lost (given up, or completing the upload failed, 
which aborts it), the failure goes to the
    endpoint's exceptionHandler, or is logged at ERROR, naming the object, the 
upload id and the number of exchanges. An
    exception thrown by the exceptionHandler is logged at ERROR, so it does not 
stop the timeout task.
    
    Without timestamp grouping, an exchange whose uploadPart failed left its 
bytes in the open upload, so its redelivery
    stored them twice. The producer now puts the open upload back as it was 
before the exchange (buffer, uploaded parts,
    counters) when the exchange fails.
    
    * CAMEL-27455: camel-aws2-s3 - review follow-up: exceptionHandler note in 
the docs, one copy of the data before an exchange
    
    - Streaming upload docs: the exceptionHandler option is listed with the 
consumer options, but the streaming upload
      producer uses it too, and it is set on the endpoint URI 
(exceptionHandler=#myHandler).
    - AggregateMark: the data buffered before an exchange is kept with one copy 
instead of two (toByteArray() copied the
      whole buffer, and Arrays.copyOf copied it again), and restoring it 
without an uploaded part truncates the buffer
      instead of copying it twice and writing it back. The buffer is a small 
ByteArrayOutputStream subclass for this.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/aws2-s3-streaming.adoc      |  13 +
 .../src/main/docs/aws2-s3-streaming.adoc           |  13 +
 .../aws2/s3/stream/AWS2S3StreamUploadProducer.java | 179 ++++++++-
 .../stream/AWS2S3StreamUploadFailedFlushTest.java  | 435 +++++++++++++++++++++
 4 files changed, 625 insertions(+), 15 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws2-s3-streaming.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws2-s3-streaming.adoc
index 1fa950c8cc9d..4f809b8e56bb 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws2-s3-streaming.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws2-s3-streaming.adoc
@@ -82,6 +82,19 @@ from(kafka("topic1").brokers("localhost:9092"))
 
 In this case, the upload will be completed after 10 seconds.
 
+The exchanges whose data is buffered have already returned success when the 
timeout runs, so a failure of the timeout
+upload does not drop the data. When uploading the buffered data fails, it 
stays buffered and the next run of the
+timeout (or the next exchange) uploads it again. After three runs that failed 
to upload it, or when completing the
+upload fails, the multipart upload is aborted and the data is lost: the 
failure, naming the object and the number of
+exchanges, goes to the `exceptionHandler` of the endpoint when one is set, and 
is logged at ERROR level otherwise. The
+`exceptionHandler` option is listed with the consumer options, but this 
producer uses it too: set it on the endpoint
+URI, for example `exceptionHandler=#myHandler`.
+
+Without `timestampGroupingEnabled`, when an exchange fails (for example 
because uploading a part failed), its data is
+taken out of the upload again: the data buffered before it stays, and a 
redelivery of the exchange does not store its
+data twice. This does not apply to the data of an exchange that already 
completed an object before the exchange failed
+(an exchange larger than the batch): that object stays.
+
 === Timestamp Grouping
 
 The streaming upload mode also supports timestamp-based file grouping, which 
allows messages to be automatically grouped into time windows and written to 
the same S3 file based on their timestamps. This feature enables append-like 
behavior where messages with timestamps falling within the same time window are 
combined into a single file.
diff --git 
a/components/camel-aws/camel-aws2-s3/src/main/docs/aws2-s3-streaming.adoc 
b/components/camel-aws/camel-aws2-s3/src/main/docs/aws2-s3-streaming.adoc
index 1fa950c8cc9d..4f809b8e56bb 100644
--- a/components/camel-aws/camel-aws2-s3/src/main/docs/aws2-s3-streaming.adoc
+++ b/components/camel-aws/camel-aws2-s3/src/main/docs/aws2-s3-streaming.adoc
@@ -82,6 +82,19 @@ from(kafka("topic1").brokers("localhost:9092"))
 
 In this case, the upload will be completed after 10 seconds.
 
+The exchanges whose data is buffered have already returned success when the 
timeout runs, so a failure of the timeout
+upload does not drop the data. When uploading the buffered data fails, it 
stays buffered and the next run of the
+timeout (or the next exchange) uploads it again. After three runs that failed 
to upload it, or when completing the
+upload fails, the multipart upload is aborted and the data is lost: the 
failure, naming the object and the number of
+exchanges, goes to the `exceptionHandler` of the endpoint when one is set, and 
is logged at ERROR level otherwise. The
+`exceptionHandler` option is listed with the consumer options, but this 
producer uses it too: set it on the endpoint
+URI, for example `exceptionHandler=#myHandler`.
+
+Without `timestampGroupingEnabled`, when an exchange fails (for example 
because uploading a part failed), its data is
+taken out of the upload again: the data buffered before it stays, and a 
redelivery of the exchange does not store its
+data twice. This does not apply to the data of an exchange that already 
completed an object before the exchange failed
+(an exchange larger than the batch): that object stays.
+
 === Timestamp Grouping
 
 The streaming upload mode also supports timestamp-based file grouping, which 
allows messages to be automatically grouped into time windows and written to 
the same S3 file based on their timestamps. This feature enables append-like 
behavior where messages with timestamps falling within the same time window are 
combined into a single file.
diff --git 
a/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadProducer.java
 
b/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadProducer.java
index cf466437f177..c398b92915f5 100644
--- 
a/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadProducer.java
+++ 
b/components/camel-aws/camel-aws2-s3/src/main/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadProducer.java
@@ -20,6 +20,7 @@ import java.io.ByteArrayOutputStream;
 import java.io.InputStream;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Comparator;
 import java.util.Date;
 import java.util.LinkedHashMap;
@@ -36,12 +37,15 @@ import java.util.concurrent.locks.ReentrantLock;
 
 import org.apache.camel.Endpoint;
 import org.apache.camel.Exchange;
+import org.apache.camel.LoggingLevel;
 import org.apache.camel.Message;
 import org.apache.camel.component.aws2.s3.AWS2S3Configuration;
 import org.apache.camel.component.aws2.s3.AWS2S3Constants;
 import org.apache.camel.component.aws2.s3.AWS2S3Endpoint;
 import org.apache.camel.component.aws2.s3.utils.AWS2S3Utils;
+import org.apache.camel.spi.ExceptionHandler;
 import org.apache.camel.support.DefaultProducer;
+import org.apache.camel.support.LoggingExceptionHandler;
 import org.apache.camel.util.ObjectHelper;
 import org.apache.camel.util.URISupport;
 import org.slf4j.Logger;
@@ -75,6 +79,8 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
     private static final String TIMEOUT_CHECKER_EXECUTOR_NAME = 
"S3_Streaming_Upload_Timeout_Checker";
     // the number of timestamp windows whose completed uploads are counted
     private static final int MAX_COUNTED_WINDOWS = 10000;
+    // the runs of the timeout task that try to upload the buffered data of an 
upload before it is given up
+    private static final int TIMEOUT_FLUSH_ATTEMPTS = 3;
     private AtomicInteger part = new AtomicInteger();
     private UploadState uploadAggregate = null;
     private final Map<Long, UploadState> timestampBasedUploads = new 
ConcurrentHashMap<>();
@@ -153,13 +159,7 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
         public void run() {
             lock.lock();
             try {
-                if (ObjectHelper.isNotEmpty(uploadAggregate)) {
-                    try {
-                        uploadPart(uploadAggregate);
-                        completeUpload(uploadAggregate);
-                    } catch (Exception e) {
-                        LOG.warn("Error during timeout-triggered upload flush 
for {}", uploadAggregate.dynamicKeyName, e);
-                    }
+                if (ObjectHelper.isNotEmpty(uploadAggregate) && 
flushOnTimeout(uploadAggregate) != TimeoutFlush.KEPT) {
                     uploadAggregate = null;
                 }
 
@@ -169,14 +169,13 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
                     for (Map.Entry<Long, UploadState> entry : 
timestampBasedUploads.entrySet()) {
                         UploadState state = entry.getValue();
                         if (ObjectHelper.isNotEmpty(state) && 
state.buffer.size() > 0) {
-                            try {
-                                uploadPart(state);
-                                completeUpload(state);
+                            TimeoutFlush flush = flushOnTimeout(state);
+                            if (flush == TimeoutFlush.COMPLETED) {
                                 completedUploadsByWindow.merge(entry.getKey(), 
1, Integer::sum);
-                            } catch (Exception e) {
-                                LOG.warn("Error during timeout-triggered 
upload flush for {}", state.dynamicKeyName, e);
                             }
-                            keysToRemove.add(entry.getKey());
+                            if (flush != TimeoutFlush.KEPT) {
+                                keysToRemove.add(entry.getKey());
+                            }
                         }
                     }
                     keysToRemove.forEach(timestampBasedUploads::remove);
@@ -187,6 +186,72 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
         }
     }
 
+    private enum TimeoutFlush {
+        COMPLETED,
+        KEPT,
+        LOST
+    }
+
+    /**
+     * Uploads and completes an upload when the streamingUploadTimeout runs. 
The exchanges of the buffered data have
+     * already returned success, so a failure does not drop the data: when 
uploading it fails, it stays buffered in the
+     * open upload, and the next run of the timeout task (or the next 
exchange) uploads it again. When the upload of the
+     * data failed in {@link #TIMEOUT_FLUSH_ATTEMPTS} runs, the multipart 
upload is aborted. When the data is lost this
+     * way, or because completing the upload failed (which aborts it), the 
failure goes to the exception handler.
+     */
+    private TimeoutFlush flushOnTimeout(UploadState state) {
+        try {
+            uploadPart(state);
+        } catch (Exception e) {
+            state.failedTimeoutFlushes++;
+            if (state.failedTimeoutFlushes < TIMEOUT_FLUSH_ATTEMPTS) {
+                LOG.warn("Uploading the data buffered for {} when the 
streamingUploadTimeout ran out failed (attempt {} of {})."
+                         + " The data stays buffered and the next run of the 
timeout uploads it again: {}",
+                        state.dynamicKeyName, state.failedTimeoutFlushes, 
TIMEOUT_FLUSH_ATTEMPTS, e.toString());
+                LOG.debug("Uploading the data buffered for {} failed", 
state.dynamicKeyName, e);
+                return TimeoutFlush.KEPT;
+            }
+            abortUpload(state);
+            lostOnTimeout(state, "uploading it failed " + 
TIMEOUT_FLUSH_ATTEMPTS + " times and the upload was aborted", e);
+            return TimeoutFlush.LOST;
+        }
+        try {
+            completeUpload(state);
+            return TimeoutFlush.COMPLETED;
+        } catch (Exception e) {
+            lostOnTimeout(state, "completing the upload failed and the upload 
was aborted", e);
+            return TimeoutFlush.LOST;
+        }
+    }
+
+    private void lostOnTimeout(UploadState state, String reason, Exception 
cause) {
+        String message = "The data of " + state.index + " exchange(s) buffered 
for " + state.dynamicKeyName
+                         + " (multipart upload " + 
state.initResponse.uploadId() + ") was not stored when the"
+                         + " streamingUploadTimeout ran out: " + reason;
+        ExceptionHandler handler = getEndpoint().getExceptionHandler();
+        if (handler == null) {
+            handler = new 
LoggingExceptionHandler(getEndpoint().getCamelContext(), getClass(), 
LoggingLevel.ERROR);
+        }
+        try {
+            handler.handleException(message, cause);
+        } catch (Exception e) {
+            // the timeout task must keep running (CAMEL-24195), so a failing 
handler only gets the loss logged
+            LOG.error("{} (the exceptionHandler of the endpoint failed: {})", 
message, e.toString(), cause);
+        }
+    }
+
+    private void abortUpload(UploadState state) {
+        try {
+            getEndpoint().getS3Client()
+                    
.abortMultipartUpload(AbortMultipartUploadRequest.builder().bucket(getConfiguration().getBucketName())
+                            
.key(state.dynamicKeyName).uploadId(state.initResponse.uploadId()).build());
+        } catch (Exception e) {
+            LOG.warn("Aborting the multipart upload {} of {} failed: {}", 
state.initResponse.uploadId(), state.dynamicKeyName,
+                    e.toString());
+            LOG.debug("Aborting the multipart upload {} failed", 
state.initResponse.uploadId(), e);
+        }
+    }
+
     @Override
     public void process(final Exchange exchange) throws Exception {
         if (getConfiguration().isTimestampGroupingEnabled()) {
@@ -209,6 +274,20 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
     }
 
     private void writeWithoutTimestampGrouping(final Exchange exchange, final 
InputStream is) throws Exception {
+        // the open upload before this exchange, to take the exchange out of 
it again when the exchange fails
+        AggregateMark mark = uploadAggregate != null ? new 
AggregateMark(uploadAggregate) : null;
+        try {
+            appendWithoutTimestampGrouping(exchange, is, mark);
+        } catch (Exception e) {
+            if (mark != null && uploadAggregate == mark.state) {
+                mark.restore();
+            }
+            throw e;
+        }
+    }
+
+    private void appendWithoutTimestampGrouping(final Exchange exchange, final 
InputStream is, final AggregateMark mark)
+            throws Exception {
         UploadState state = null;
         int totalSize = 0;
         byte[] b;
@@ -229,6 +308,9 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
                 uploadAggregate.buffer.write(b);
                 if (getConfiguration().isMultiPartUpload() &&
                         uploadAggregate.buffer.size() >= 
getConfiguration().getPartSize()) {
+                    if (mark != null) {
+                        mark.beforeUploadPart();
+                    }
                     uploadPart(uploadAggregate);
                     maxRead = 
Math.toIntExact(getConfiguration().getPartSize());
                     continue;
@@ -510,6 +592,8 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
         state.completedParts.add(partUpload);
         state.buffer.reset();
         state.multipartIndex++;
+        // the data that failed timeout runs kept is uploaded: count the 
failed runs again from here
+        state.failedTimeoutFlushes = 0;
     }
 
     private String fileNameToUpload(
@@ -739,12 +823,60 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
         }
     }
 
+    /**
+     * The open upload as it was before an exchange was added to it. When the 
exchange fails, {@link #restore()} takes
+     * the data of the exchange out of the upload again: the exchange is 
redelivered (or reported as failed), so it must
+     * not be stored by a later upload of the data buffered before it.
+     */
+    private static final class AggregateMark {
+        private final UploadState state;
+        private final int index;
+        private final int bufferSize;
+        private final int completedParts;
+        private final int multipartIndex;
+        private final int failedTimeoutFlushes;
+        // the data buffered before the exchange, once a part with it was 
uploaded during the exchange
+        private byte[] buffered;
+
+        AggregateMark(UploadState state) {
+            this.state = state;
+            this.index = state.index;
+            this.bufferSize = state.buffer.size();
+            this.completedParts = state.completedParts.size();
+            this.multipartIndex = state.multipartIndex;
+            this.failedTimeoutFlushes = state.failedTimeoutFlushes;
+        }
+
+        void beforeUploadPart() {
+            if (buffered == null) {
+                buffered = state.buffer.copyOf(bufferSize);
+            }
+        }
+
+        void restore() {
+            // a part uploaded again replaces the part with the same number, 
and the parts after the restored ones are
+            // not completed, so S3 discards them
+            if (buffered != null) {
+                state.buffer.reset();
+                state.buffer.write(buffered, 0, buffered.length);
+            } else {
+                state.buffer.truncate(bufferSize);
+            }
+            state.completedParts.subList(completedParts, 
state.completedParts.size()).clear();
+            state.multipartIndex = multipartIndex;
+            state.index = index;
+            state.failedTimeoutFlushes = failedTimeoutFlushes;
+        }
+    }
+
     private class UploadState {
         int index;
         int multipartIndex;
         int part;
+        // the runs of the timeout task that failed to upload the buffered data
+        int failedTimeoutFlushes;
         List<CompletedPart> completedParts = new ArrayList<>();
-        ByteArrayOutputStream buffer;
+        UploadBuffer buffer;
         String dynamicKeyName;
         UUID id;
         long timestamp;
@@ -754,7 +886,24 @@ public class AWS2S3StreamUploadProducer extends 
DefaultProducer {
             index = 1;
             multipartIndex = 1;
             part = AWS2S3StreamUploadProducer.this.part.get();
-            buffer = new ByteArrayOutputStream();
+            buffer = new UploadBuffer();
+        }
+    }
+
+    /**
+     * The buffered data of an upload. {@link AggregateMark} keeps or restores 
the data buffered before an exchange with
+     * at most one copy of it.
+     */
+    private static final class UploadBuffer extends ByteArrayOutputStream {
+
+        // the first bytes of the buffer, in one copy (toByteArray() would 
copy the whole buffer first)
+        synchronized byte[] copyOf(int length) {
+            return Arrays.copyOf(buf, Math.min(length, count));
+        }
+
+        // drops the bytes after the given length, without a copy
+        synchronized void truncate(int length) {
+            count = Math.min(length, count);
         }
     }
 }
diff --git 
a/components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadFailedFlushTest.java
 
b/components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadFailedFlushTest.java
new file mode 100644
index 000000000000..5ebb04da1336
--- /dev/null
+++ 
b/components/camel-aws/camel-aws2-s3/src/test/java/org/apache/camel/component/aws2/s3/stream/AWS2S3StreamUploadFailedFlushTest.java
@@ -0,0 +1,435 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.aws2.s3.stream;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.component.aws2.s3.AWS2S3Configuration;
+import org.apache.camel.component.aws2.s3.AWS2S3Endpoint;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.ExceptionHandler;
+import org.apache.camel.spi.ExecutorServiceManager;
+import org.apache.camel.support.DefaultExchange;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import software.amazon.awssdk.core.sync.RequestBody;
+import software.amazon.awssdk.http.SdkHttpResponse;
+import software.amazon.awssdk.services.s3.S3Client;
+import software.amazon.awssdk.services.s3.model.AbortMultipartUploadRequest;
+import software.amazon.awssdk.services.s3.model.AbortMultipartUploadResponse;
+import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest;
+import 
software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse;
+import software.amazon.awssdk.services.s3.model.CompletedPart;
+import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest;
+import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse;
+import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
+import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
+import software.amazon.awssdk.services.s3.model.S3Exception;
+import software.amazon.awssdk.services.s3.model.UploadPartRequest;
+import software.amazon.awssdk.services.s3.model.UploadPartResponse;
+
+import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
+/**
+ * A failed upload must neither drop the data of exchanges that already 
returned success (the upload of the
+ * streamingUploadTimeout task) nor keep the data of the exchange that failed 
(the upload of an exchange, which is
+ * redelivered). The timeout task is not scheduled: the test runs it. The 
mocked S3Client keeps the parts of each
+ * multipart upload by part number, as S3 does (a part uploaded again replaces 
the one with the same number), stores the
+ * parts listed by completeMultipartUpload, and answers NoSuchUpload (404) for 
a completed or aborted upload.
+ */
+class AWS2S3StreamUploadFailedFlushTest {
+
+    private static final String TIMEOUT_CHECKER = 
"S3_Streaming_Upload_Timeout_Checker";
+    private static final long WINDOW_TIMESTAMP = 1_700_000_000_000L;
+
+    @Mock
+    private AWS2S3Endpoint endpoint;
+
+    @Mock
+    private AWS2S3Configuration configuration;
+
+    @Mock
+    private S3Client s3Client;
+
+    // the bucket: completed objects by key
+    private final Map<String, String> bucket = new ConcurrentHashMap<>();
+    private final Map<String, String> keysByUploadId = new 
ConcurrentHashMap<>();
+    private final Map<String, Map<Integer, byte[]>> partsByUploadId = new 
ConcurrentHashMap<>();
+    // open, completed or aborted
+    private final Map<String, String> uploadStatus = new ConcurrentHashMap<>();
+    private final AtomicInteger uploadIds = new AtomicInteger();
+    // the next uploadPart calls that answer 503, after the given number of 
calls that succeed
+    private final AtomicInteger uploadPartsBeforeFailure = new AtomicInteger();
+    private final AtomicInteger failingUploadParts = new AtomicInteger();
+    private final AtomicInteger failingCompletes = new AtomicInteger();
+    // the failures given to the exception handler of the endpoint
+    private final List<String> handledFailures = new CopyOnWriteArrayList<>();
+    // whether the exception handler of the endpoint throws
+    private final AtomicBoolean failingExceptionHandler = new AtomicBoolean();
+
+    private DefaultCamelContext camelContext;
+    private Runnable timeoutTask;
+    private AWS2S3StreamUploadProducer producer;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        MockitoAnnotations.openMocks(this);
+        camelContext = new DefaultCamelContext();
+        // the producer gets this scheduler for its timeout task, which the 
test runs itself
+        ScheduledExecutorService scheduler = 
mock(ScheduledExecutorService.class);
+        when(scheduler.scheduleAtFixedRate(any(Runnable.class), anyLong(), 
anyLong(), any(TimeUnit.class)))
+                .thenAnswer(invocation -> {
+                    timeoutTask = invocation.getArgument(0);
+                    return mock(ScheduledFuture.class);
+                });
+        // a scheduler without threads: shut down and terminated, whichever 
way the producer shuts it down
+        when(scheduler.isShutdown()).thenReturn(true);
+        when(scheduler.isTerminated()).thenReturn(true);
+        when(scheduler.awaitTermination(anyLong(), 
any(TimeUnit.class))).thenReturn(true);
+        ExecutorServiceManager manager = 
spy(camelContext.getExecutorServiceManager());
+        
doReturn(scheduler).when(manager).newSingleThreadScheduledExecutor(any(), 
eq(TIMEOUT_CHECKER));
+        camelContext.setExecutorServiceManager(manager);
+        camelContext.start();
+
+        ExceptionHandler exceptionHandler = mock(ExceptionHandler.class);
+        doAnswer(invocation -> {
+            handledFailures.add(invocation.getArgument(0));
+            if (failingExceptionHandler.get()) {
+                throw new IllegalStateException("the exception handler 
failed");
+            }
+            return null;
+        }).when(exceptionHandler).handleException(any(String.class), 
any(Throwable.class));
+
+        when(endpoint.getConfiguration()).thenReturn(configuration);
+        when(endpoint.getCamelContext()).thenReturn(camelContext);
+        when(endpoint.getS3Client()).thenReturn(s3Client);
+        when(endpoint.getExceptionHandler()).thenReturn(exceptionHandler);
+
+        when(configuration.getBucketName()).thenReturn("test-bucket");
+        when(configuration.getKeyName()).thenReturn("camel.txt");
+        when(configuration.isMultiPartUpload()).thenReturn(false);
+        when(configuration.getPartSize()).thenReturn(25L * 1024 * 1024);
+        
when(configuration.getNamingStrategy()).thenReturn(AWSS3NamingStrategyEnum.progressive);
+        
when(configuration.getRestartingPolicy()).thenReturn(AWSS3RestartingPolicyEnum.override);
+        // the defaults of the endpoint
+        when(configuration.getBatchMessageNumber()).thenReturn(10);
+        when(configuration.getBatchSize()).thenReturn(1000000);
+        when(configuration.getBufferSize()).thenReturn(1000000);
+        
when(configuration.getTimestampHeaderName()).thenReturn(Exchange.MESSAGE_TIMESTAMP);
+        when(configuration.getTimestampWindowSizeMillis()).thenReturn(300000L);
+
+        SdkHttpResponse ok = SdkHttpResponse.builder().statusCode(200).build();
+
+        when(s3Client.listObjectsV2(any(ListObjectsV2Request.class)))
+                
.thenReturn(ListObjectsV2Response.builder().contents(Collections.emptyList()).isTruncated(false).build());
+
+        
when(s3Client.createMultipartUpload(any(CreateMultipartUploadRequest.class))).thenAnswer(invocation
 -> {
+            CreateMultipartUploadRequest request = invocation.getArgument(0);
+            String uploadId = "upload-" + uploadIds.incrementAndGet();
+            keysByUploadId.put(uploadId, request.key());
+            partsByUploadId.put(uploadId, new ConcurrentHashMap<>());
+            uploadStatus.put(uploadId, "open");
+            return 
CreateMultipartUploadResponse.builder().uploadId(uploadId).sdkHttpResponse(ok).build();
+        });
+
+        when(s3Client.uploadPart(any(UploadPartRequest.class), 
any(RequestBody.class))).thenAnswer(invocation -> {
+            UploadPartRequest request = invocation.getArgument(0);
+            RequestBody body = invocation.getArgument(1);
+            if (!"open".equals(uploadStatus.get(request.uploadId()))) {
+                throw noSuchUpload(request.uploadId());
+            }
+            if (uploadPartsBeforeFailure.getAndUpdate(n -> Math.max(0, n - 1)) 
== 0
+                    && failingUploadParts.getAndUpdate(n -> Math.max(0, n - 
1)) > 0) {
+                throw 
S3Exception.builder().statusCode(503).message("SlowDown").build();
+            }
+            partsByUploadId.get(request.uploadId()).put(request.partNumber(),
+                    body.contentStreamProvider().newStream().readAllBytes());
+            return UploadPartResponse.builder().eTag("etag-" + 
request.partNumber()).sdkHttpResponse(ok).build();
+        });
+
+        
when(s3Client.completeMultipartUpload(any(CompleteMultipartUploadRequest.class))).thenAnswer(invocation
 -> {
+            CompleteMultipartUploadRequest request = invocation.getArgument(0);
+            String uploadId = request.uploadId();
+            if (!"open".equals(uploadStatus.get(uploadId))) {
+                throw noSuchUpload(uploadId);
+            }
+            if (failingCompletes.getAndUpdate(n -> Math.max(0, n - 1)) > 0) {
+                throw 
S3Exception.builder().statusCode(500).message("InternalError").build();
+            }
+            // the object is made of the listed parts; S3 discards the other 
parts of the upload
+            Map<Integer, byte[]> uploaded = partsByUploadId.get(uploadId);
+            Map<Integer, byte[]> listed = new TreeMap<>();
+            for (CompletedPart part : request.multipartUpload().parts()) {
+                listed.put(part.partNumber(), uploaded.get(part.partNumber()));
+            }
+            ByteArrayOutputStream object = new ByteArrayOutputStream();
+            listed.values().forEach(object::writeBytes);
+            uploadStatus.put(uploadId, "completed");
+            bucket.put(keysByUploadId.get(uploadId), 
object.toString(StandardCharsets.UTF_8));
+            return 
CompleteMultipartUploadResponse.builder().eTag("final-etag").sdkHttpResponse(ok).build();
+        });
+
+        
when(s3Client.abortMultipartUpload(any(AbortMultipartUploadRequest.class))).thenAnswer(invocation
 -> {
+            AbortMultipartUploadRequest request = invocation.getArgument(0);
+            if (!"open".equals(uploadStatus.get(request.uploadId()))) {
+                throw noSuchUpload(request.uploadId());
+            }
+            uploadStatus.put(request.uploadId(), "aborted");
+            return AbortMultipartUploadResponse.builder().build();
+        });
+
+        producer = new AWS2S3StreamUploadProducer(endpoint);
+    }
+
+    @AfterEach
+    void tearDown() {
+        camelContext.stop();
+    }
+
+    private static S3Exception noSuchUpload(String uploadId) {
+        return (S3Exception) S3Exception.builder().statusCode(404)
+                .message("NoSuchUpload: the upload " + uploadId + " was 
completed or aborted").build();
+    }
+
+    private void send(Object body, Long timestamp) throws Exception {
+        Exchange exchange = new DefaultExchange(camelContext);
+        exchange.getIn().setBody(body);
+        if (timestamp != null) {
+            exchange.getIn().setHeader(Exchange.MESSAGE_TIMESTAMP, timestamp);
+        }
+        producer.process(exchange);
+    }
+
+    // a body read 10 bytes at a time, as a stream from the network gives it
+    private static InputStream readInSmallChunks(String body) {
+        return new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)) 
{
+            @Override
+            public synchronized int read(byte[] b, int off, int len) {
+                return super.read(b, off, Math.min(len, 10));
+            }
+        };
+    }
+
+    private void startWithTimeout() {
+        when(configuration.getStreamingUploadTimeout()).thenReturn(1000L);
+        producer.start();
+        assertNotNull(timeoutTask, "the producer scheduled its timeout task");
+    }
+
+    @Test
+    void timeoutUploadKeepsTheDataWhenUploadingItFails() throws Exception {
+        startWithTimeout();
+        send("message-0\n", null);
+
+        failingUploadParts.set(1);
+        timeoutTask.run();
+        assertEquals("open", uploadStatus.get("upload-1"));
+        assertTrue(bucket.isEmpty());
+
+        timeoutTask.run();
+        assertEquals("completed", uploadStatus.get("upload-1"));
+        assertEquals(Map.of("camel.txt", "message-0\n"), bucket);
+        assertEquals(List.of(), handledFailures);
+        producer.stop();
+    }
+
+    @Test
+    void nextExchangeUploadsTheDataKeptByAFailedTimeoutUpload() throws 
Exception {
+        when(configuration.getBatchMessageNumber()).thenReturn(2);
+        startWithTimeout();
+        send("message-0\n", null);
+
+        failingUploadParts.set(1);
+        timeoutTask.run();
+
+        // the second exchange of the upload completes it
+        send("message-1\n", null);
+        assertEquals(Map.of("camel.txt", "message-0\nmessage-1\n"), bucket);
+        assertEquals(1, uploadIds.get());
+        assertEquals(List.of(), handledFailures);
+        producer.stop();
+    }
+
+    @Test
+    void timeoutUploadIsAbortedAndReportedAfterThreeFailedRuns() throws 
Exception {
+        startWithTimeout();
+        send("message-0\n", null);
+
+        failingUploadParts.set(3);
+        timeoutTask.run();
+        timeoutTask.run();
+        assertEquals("open", uploadStatus.get("upload-1"));
+        assertEquals(List.of(), handledFailures);
+
+        timeoutTask.run();
+        assertEquals("aborted", uploadStatus.get("upload-1"));
+        assertEquals(1, handledFailures.size());
+        String failure = handledFailures.get(0);
+        assertTrue(failure.contains("1 exchange(s)") && 
failure.contains("camel.txt") && failure.contains("upload-1"),
+                failure);
+
+        // the next exchange starts a new upload
+        send("message-1\n", null);
+        timeoutTask.run();
+        assertEquals("completed", uploadStatus.get("upload-2"));
+        assertEquals(Map.of("camel.txt", "message-1\n"), bucket);
+        producer.stop();
+    }
+
+    @Test
+    void timeoutUploadWhoseCompletionFailsIsReported() throws Exception {
+        startWithTimeout();
+        send("message-0\n", null);
+
+        failingCompletes.set(1);
+        timeoutTask.run();
+        // completeUpload aborts the upload when completing it fails
+        assertEquals("aborted", uploadStatus.get("upload-1"));
+        assertEquals(1, handledFailures.size());
+        assertTrue(handledFailures.get(0).contains("camel.txt"), 
handledFailures.get(0));
+        producer.stop();
+    }
+
+    @Test
+    void timeoutTaskKeepsRunningWhenTheExceptionHandlerFails() throws 
Exception {
+        failingExceptionHandler.set(true);
+        startWithTimeout();
+        send("message-0\n", null);
+
+        failingCompletes.set(1);
+        // an exception out of the task would stop scheduleAtFixedRate from 
running it again
+        assertDoesNotThrow(timeoutTask::run);
+        assertEquals("aborted", uploadStatus.get("upload-1"));
+        assertEquals(1, handledFailures.size());
+
+        // the aborted upload is dropped: the next exchange starts a new 
upload, which the next run stores
+        send("message-1\n", null);
+        assertDoesNotThrow(timeoutTask::run);
+        assertEquals("completed", uploadStatus.get("upload-2"));
+        assertEquals(Map.of("camel.txt", "message-1\n"), bucket);
+        producer.stop();
+    }
+
+    @Test
+    void uploadedPartStartsTheCountOfFailedTimeoutRunsAgain() throws Exception 
{
+        when(configuration.isMultiPartUpload()).thenReturn(true);
+        when(configuration.getPartSize()).thenReturn(20L);
+        startWithTimeout();
+        send("message-0\n", null);
+
+        failingUploadParts.set(2);
+        timeoutTask.run();
+        timeoutTask.run();
+
+        // S3 answers again: the next exchange fills part 1 with the kept data 
and uploads it
+        String body = "C".repeat(15);
+        send(readInSmallChunks(body), null);
+
+        // one more failed run is the first one for the data buffered now
+        failingUploadParts.set(1);
+        timeoutTask.run();
+        assertEquals("open", uploadStatus.get("upload-1"));
+        assertEquals(List.of(), handledFailures);
+
+        timeoutTask.run();
+        assertEquals(Map.of("camel.txt", "message-0\n" + body), bucket);
+        producer.stop();
+    }
+
+    @Test
+    void timeoutUploadOfATimestampWindowKeepsTheDataWhenUploadingItFails() 
throws Exception {
+        when(configuration.isTimestampGroupingEnabled()).thenReturn(true);
+        startWithTimeout();
+        send("message-0\n", WINDOW_TIMESTAMP);
+
+        failingUploadParts.set(1);
+        timeoutTask.run();
+        assertEquals("open", uploadStatus.get("upload-1"));
+        assertTrue(bucket.isEmpty());
+
+        timeoutTask.run();
+        assertEquals("completed", uploadStatus.get("upload-1"));
+        assertEquals(List.of("message-0\n"), List.copyOf(bucket.values()));
+        assertEquals(List.of(), handledFailures);
+        producer.stop();
+    }
+
+    @Test
+    void failedExchangeIsNotStoredAgainWhenItIsRedelivered() throws Exception {
+        when(configuration.getBatchMessageNumber()).thenReturn(2);
+        producer.start();
+        send("message-0\n", null);
+
+        // the second exchange completes the upload, and uploading the part 
fails
+        failingUploadParts.set(1);
+        assertThrows(S3Exception.class, () -> send("message-1\n", null));
+
+        // the redelivery of the exchange
+        send("message-1\n", null);
+        producer.stop();
+        assertEquals(Map.of("camel.txt", "message-0\nmessage-1\n"), bucket);
+    }
+
+    @Test
+    void failedExchangeOfAMultipartUploadIsNotStoredAgainWhenItIsRedelivered() 
throws Exception {
+        when(configuration.isMultiPartUpload()).thenReturn(true);
+        when(configuration.getPartSize()).thenReturn(20L);
+        producer.start();
+        send("message-0\n", null);
+
+        // the exchange fills part 1 (with the 10 bytes of message-0) and part 
2; uploading part 2 fails
+        String body = "B".repeat(30);
+        uploadPartsBeforeFailure.set(1);
+        failingUploadParts.set(1);
+        assertThrows(S3Exception.class, () -> send(readInSmallChunks(body), 
null));
+
+        // the redelivery of the exchange
+        send(readInSmallChunks(body), null);
+        producer.stop();
+        assertEquals(Map.of("camel.txt", "message-0\n" + body), bucket);
+    }
+}

Reply via email to