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 253177d86bc1 CAMEL-28126: camel-alibaba-oss - get each object of a 
poll right before routing its exchange (#31408)
253177d86bc1 is described below

commit 253177d86bc18f010385a08d7ce4f1fae3e18b02
Author: Saravanakumar Selvaraj <[email protected]>
AuthorDate: Sun Dec 6 13:28:58 2026 +0530

    CAMEL-28126: camel-alibaba-oss - get each object of a poll right before 
routing its exchange (#31408)
    
    The consumer got every listed object of a poll before it routed the first 
exchange. With the default
    includeBody=true, the heap held the content of every object of the poll at 
the same time. With includeBody=false,
    each object over 32 KiB held an HTTP connection while the earlier exchanges 
ran. A consumer that stopped during a poll
    still got every object of the poll.
    
    poll now only takes the listed objects and marks them as in progress. 
processBatch gets each object right before it
    routes its exchange, as AWS2S3Consumer does since CAMEL-26662. A consumer 
that stops during a poll gets no further
    object of that poll, unless shutdownRunningTask is CompleteAllTasks. The 
batch properties count the objects that the
    poll took. So an object that the consumer skips leaves a gap in 
CamelBatchIndex. A failed get now reaches the
    exception handler after the consumer routed the other exchanges of the 
poll. The doc page says so, and the upgrade
    guide has a section on it.
    
    The rules of CAMEL-25760 stay. The consumer skips an object that no longer 
exists, with a DEBUG line. Any other
    failure to get an object goes to the exception handler, unless the poll got 
no object. Then the poll fails with the
    first failure. The in-progress set stays in the consumer. The new 
OSSConsumerGetEachObjectTest covers the order, the
    open streams, the batch properties and a failed get. One test of 
OSSConsumerIncludeBodyTest expected the old order.
    It now expects that a stopping consumer gets only the object it routes.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/catalog/docs/alibaba-oss-component.adoc  |  11 +-
 .../src/main/docs/alibaba-oss-component.adoc       |  11 +-
 .../camel/component/alibaba/oss/OSSConsumer.java   | 136 ++++++-----
 .../alibaba/oss/OSSConsumerGetEachObjectTest.java  | 268 +++++++++++++++++++++
 .../alibaba/oss/OSSConsumerIncludeBodyTest.java    |  11 +-
 .../ROOT/pages/camel-4x-upgrade-guide-4_25.adoc    |  25 ++
 6 files changed, 392 insertions(+), 70 deletions(-)

diff --git 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/alibaba-oss-component.adoc
 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/alibaba-oss-component.adoc
index aaef7111591f..b516cf458a65 100644
--- 
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/alibaba-oss-component.adoc
+++ 
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/alibaba-oss-component.adoc
@@ -65,10 +65,19 @@ The consumer deletes the object it consumed, whatever the 
route does with the `C
 A failed delete goes to the exception handler of the consumer.
 A route can set the bucket name header to write a copy of the object to 
another bucket.
 
+The consumer gets each listed object right before it routes the exchange of 
the object.
+A consumer that stops during a poll gets no further object of that poll, 
unless `shutdownRunningTask` is `CompleteAllTasks`.
+
+The batch properties count the listed objects, other than folders and objects 
that an earlier exchange still processes.
+The consumer skips an object that no longer exists, or that it fails to get, 
but counts it in `CamelBatchSize`.
+A skipped object leaves a gap in `CamelBatchIndex`, and if it is last, no 
exchange of the poll has `CamelBatchComplete=true`.
+
 By default (`includeBody=true`) the consumer reads the content of each object 
into a `byte[]`, which is the body, so an object needs as much memory as its 
size.
 With `includeBody=false` the body is the `InputStream` of the content of the 
object instead, which the consumer closes when the exchange is done.
 Stream caching, which is enabled by default, would still read the stream into 
memory at the start of the route: to keep large objects out of memory, disable 
stream caching for the route, as in the example below, or enable the spooling 
of stream caching to disk.
-Closing a stream that was not read to its end still reads the rest of the 
object, without keeping it, as the HTTP client of the SDK does so to reuse the 
connection: a route that does not read the body of an object, and a consumer 
that stops before it processes all the objects of a poll, still download them.
+Closing a stream that was not read to its end still reads the rest of the 
object, without keeping it.
+The HTTP client of the SDK does so to reuse the connection.
+So a route that does not read the body of an object still downloads it.
 
 == Examples
 
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/main/docs/alibaba-oss-component.adoc
 
b/components/camel-alibaba/camel-alibaba-oss/src/main/docs/alibaba-oss-component.adoc
index aaef7111591f..b516cf458a65 100644
--- 
a/components/camel-alibaba/camel-alibaba-oss/src/main/docs/alibaba-oss-component.adoc
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/main/docs/alibaba-oss-component.adoc
@@ -65,10 +65,19 @@ The consumer deletes the object it consumed, whatever the 
route does with the `C
 A failed delete goes to the exception handler of the consumer.
 A route can set the bucket name header to write a copy of the object to 
another bucket.
 
+The consumer gets each listed object right before it routes the exchange of 
the object.
+A consumer that stops during a poll gets no further object of that poll, 
unless `shutdownRunningTask` is `CompleteAllTasks`.
+
+The batch properties count the listed objects, other than folders and objects 
that an earlier exchange still processes.
+The consumer skips an object that no longer exists, or that it fails to get, 
but counts it in `CamelBatchSize`.
+A skipped object leaves a gap in `CamelBatchIndex`, and if it is last, no 
exchange of the poll has `CamelBatchComplete=true`.
+
 By default (`includeBody=true`) the consumer reads the content of each object 
into a `byte[]`, which is the body, so an object needs as much memory as its 
size.
 With `includeBody=false` the body is the `InputStream` of the content of the 
object instead, which the consumer closes when the exchange is done.
 Stream caching, which is enabled by default, would still read the stream into 
memory at the start of the route: to keep large objects out of memory, disable 
stream caching for the route, as in the example below, or enable the spooling 
of stream caching to disk.
-Closing a stream that was not read to its end still reads the rest of the 
object, without keeping it, as the HTTP client of the SDK does so to reuse the 
connection: a route that does not read the body of an object, and a consumer 
that stops before it processes all the objects of a poll, still download them.
+Closing a stream that was not read to its end still reads the rest of the 
object, without keeping it.
+The HTTP client of the SDK does so to reuse the connection.
+So a route that does not read the body of an object still downloads it.
 
 == Examples
 
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSConsumer.java
 
b/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSConsumer.java
index 5db3cfede85b..f9415c37da8b 100644
--- 
a/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSConsumer.java
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/main/java/org/apache/camel/component/alibaba/oss/OSSConsumer.java
@@ -16,7 +16,6 @@
  */
 package org.apache.camel.component.alibaba.oss;
 
-import java.io.Closeable;
 import java.io.InputStream;
 import java.util.LinkedHashMap;
 import java.util.LinkedList;
@@ -53,7 +52,7 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
     private static final Logger LOG = 
LoggerFactory.getLogger(OSSConsumer.class);
 
     private final OSSEndpoint endpoint;
-    // objects whose exchanges are being processed, which a later poll must 
not consume again
+    // objects that a poll took and has not released yet, which a later poll 
must not consume again
     private final Set<String> inProgress = ConcurrentHashMap.newKeySet();
     private OSSClient ossClient;
     private String continuationToken;
@@ -108,23 +107,52 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
             continuationToken = null;
         }
 
-        Queue<Exchange> exchanges = createExchanges(bucketName, 
listing.contents());
-        return processBatch(CastUtils.cast(exchanges));
+        Queue<ObjectSummary> listed = takeListedObjects(listing.contents());
+        return processBatch(CastUtils.cast(listed));
     }
 
+    /**
+     * Gets each object that the poll took, right before it routes the 
exchange of the object. The batch properties
+     * count the objects that the poll took. So an object that the consumer 
skips leaves a gap in
+     * {@code CamelBatchIndex}. When the consumer skips the last object, no 
exchange of the poll has
+     * {@code CamelBatchComplete} set to true.
+     */
     @Override
     public int processBatch(Queue<Object> exchanges) throws Exception {
         int total = exchanges.size();
+        // the listed objects that this poll skipped
+        int skipped = 0;
+        // the listed objects that could not be got, other than those that no 
longer exist, by key
+        Map<String, Exception> failures = new LinkedHashMap<>();
+        // whether at least one listed object could be got
+        boolean anyGot = false;
 
         for (int index = 0; index < total && isBatchAllowed(); index++) {
-            final Exchange exchange = ObjectHelper.cast(Exchange.class, 
exchanges.poll());
+            final String key = ObjectHelper.cast(ObjectSummary.class, 
exchanges.poll()).key();
+
+            pendingExchanges = total - index - 1;
+
+            // a failure to get one listed object does not fail the poll as 
long as another listed object could be
+            // got: the object is skipped, the other listed objects are 
consumed, and a later poll tries it again
+            Exchange exchange;
+            try {
+                exchange = getListedObject(endpoint.getBucketName(), key);
+            } catch (Exception e) {
+                failures.put(key, e);
+                exchange = null;
+            }
+            if (exchange == null) {
+                // this poll does not consume the object: a later poll can 
take it
+                inProgress.remove(key);
+                skipped++;
+                continue;
+            }
+            anyGot = true;
 
             exchange.setProperty(ExchangePropertyKey.BATCH_SIZE, total);
             exchange.setProperty(ExchangePropertyKey.BATCH_INDEX, index);
             exchange.setProperty(ExchangePropertyKey.BATCH_COMPLETE, index == 
total - 1);
 
-            pendingExchanges = total - index - 1;
-
             // the object to delete once the exchange is done. It is taken 
now, as the route may change or remove the
             // bucket and key headers before it ends (the producer takes the 
bucket to write to from the bucket header)
             final String bucketName = 
exchange.getIn().getHeader(OSSHeaders.BUCKET_NAME, String.class);
@@ -152,41 +180,14 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
             AsyncCallback callback = defaultConsumerCallback(exchange, true);
             getAsyncProcessor().process(exchange, callback);
         }
-        // the remaining exchanges are not processed as the consumer is 
stopping
+        // the consumer is stopping, so it gets none of the remaining listed 
objects
         releaseNotProcessed(exchanges);
 
-        return total;
-    }
-
-    private Queue<Exchange> createExchanges(String bucketName, 
List<ObjectSummary> summaries) throws Exception {
-        Queue<Exchange> answer = new LinkedList<>();
-        if (summaries == null) {
-            return answer;
-        }
-
-        // the listed objects that could not be got, other than those that no 
longer exist, by key
-        Map<String, Exception> failures = new LinkedHashMap<>();
-        // whether at least one listed object could be got
-        boolean anyGot = false;
-        for (ObjectSummary summary : summaries) {
-            String key = summary.key();
-            if (key == null || key.endsWith("/")) {
-                continue;
-            }
-            // a failure to get one listed object does not fail the poll as 
long as another listed object could be
-            // got: the object is skipped, the other listed objects are 
consumed, and a later poll tries it again
-            try {
-                anyGot |= addExchange(bucketName, key, answer);
-            } catch (Exception e) {
-                failures.put(key, e);
-            }
-        }
-
         if (!failures.isEmpty()) {
+            String bucketName = endpoint.getBucketName();
             if (!anyGot) {
                 // none of the listed objects could be got, so this is not 
about one object (expired credentials, no
                 // permission to get, no connection): the poll fails, and the 
backoff of the scheduled consumer applies
-                releaseNotProcessed(answer);
                 Map.Entry<String, Exception> first = 
failures.entrySet().iterator().next();
                 LOG.warn("None of the listed objects of bucket {} could be got 
({} failed, the first is {}): the poll fails",
                         bucketName, failures.size(), first.getKey());
@@ -198,21 +199,42 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
                         failure.getValue());
             }
         }
+        // the poll counts only the objects that it did not skip
+        return total - skipped;
+    }
+
+    /**
+     * Takes the listed objects that are not folders and not in progress, and 
marks them as in progress.
+     * {@link #processBatch(Queue)} gets each of them right before it routes 
its exchange. So only the objects of the
+     * exchanges in flight are in memory, or open as streams with 
includeBody=false.
+     */
+    private Queue<ObjectSummary> takeListedObjects(List<ObjectSummary> 
summaries) {
+        Queue<ObjectSummary> answer = new LinkedList<>();
+        if (summaries == null) {
+            return answer;
+        }
+
+        for (ObjectSummary summary : summaries) {
+            String key = summary.key();
+            if (key == null || key.endsWith("/")) {
+                continue;
+            }
+            // skip the object if an exchange of a previous poll is still 
processing it
+            if (!inProgress.add(key)) {
+                LOG.trace("Skipping object {} as it is already in progress", 
key);
+                continue;
+            }
+            answer.add(summary);
+        }
         return answer;
     }
 
     /**
-     * Gets a listed object and adds its exchange.
+     * Gets a listed object and creates its exchange.
      *
-     * @return true if the object was got and its exchange added, false if it 
is skipped (an exchange of a previous poll
-     *         is still processing it, or it no longer exists)
+     * @return the exchange of the object, or null if the object no longer 
exists
      */
-    private boolean addExchange(String bucketName, String key, Queue<Exchange> 
answer) throws Exception {
-        // skip the object if an exchange of a previous poll is still 
processing it
-        if (!inProgress.add(key)) {
-            LOG.trace("Skipping object {} as it is already in progress", key);
-            return false;
-        }
+    private Exchange getListedObject(String bucketName, String key) throws 
Exception {
         try {
             GetObjectResult result = 
ossClient.getObject(GetObjectRequest.newBuilder()
                     .bucket(bucketName)
@@ -228,17 +250,15 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
                 Exchange exchange = createExchange(true);
                 exchange.setPattern(endpoint.getExchangePattern());
                 OSSUtils.mapOssObject(exchange, bucketName, key, result, body);
-                answer.add(exchange);
+                return exchange;
             } else {
-                answer.add(createStreamExchange(bucketName, key, result));
+                return createStreamExchange(bucketName, key, result);
             }
-            return true;
         } catch (Exception e) {
-            inProgress.remove(key);
             if (isNotFound(e)) {
                 // deleted (for example by another consumer) after it was 
listed
                 LOG.debug("Skipping object {} as it no longer exists", key);
-                return false;
+                return null;
             }
             throw e;
         }
@@ -246,8 +266,7 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
 
     /**
      * Creates the exchange of an object whose body is the stream of its 
content, which is not read into memory. The
-     * stream is closed when the exchange is done, or by {@link 
#releaseNotProcessed(Queue)} when the exchange is not
-     * processed.
+     * stream is closed when the exchange is done.
      */
     private Exchange createStreamExchange(String bucketName, String key, 
GetObjectResult result) {
         InputStream stream = result.body();
@@ -275,17 +294,8 @@ public class OSSConsumer extends 
ScheduledBatchPollingConsumer {
 
     private void releaseNotProcessed(Queue<?> exchanges) {
         for (Object o : exchanges) {
-            Exchange exchange = (Exchange) o;
-            String key = exchange.getIn().getHeader(OSSHeaders.OBJECT_KEY, 
String.class);
-            if (key != null) {
-                inProgress.remove(key);
-            }
-            // with includeBody=false the body is the stream of the object, 
which nothing else closes as the exchange
-            // is not processed
-            if (exchange.getIn().getBody() instanceof Closeable body) {
-                IOHelper.close(body);
-            }
-            releaseExchange(exchange, true);
+            ObjectSummary summary = (ObjectSummary) o;
+            inProgress.remove(summary.key());
         }
         exchanges.clear();
     }
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerGetEachObjectTest.java
 
b/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerGetEachObjectTest.java
new file mode 100644
index 000000000000..4d00f6036840
--- /dev/null
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerGetEachObjectTest.java
@@ -0,0 +1,268 @@
+/*
+ * 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.alibaba.oss;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentSkipListMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.aliyun.sdk.service.oss2.OSSClient;
+import com.aliyun.sdk.service.oss2.exceptions.OperationException;
+import com.aliyun.sdk.service.oss2.exceptions.ServiceException;
+import com.aliyun.sdk.service.oss2.models.GetObjectRequest;
+import com.aliyun.sdk.service.oss2.models.GetObjectResult;
+import com.aliyun.sdk.service.oss2.models.ListObjectsV2Request;
+import com.aliyun.sdk.service.oss2.models.ListObjectsV2Result;
+import com.aliyun.sdk.service.oss2.models.ObjectSummary;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.alibaba.oss.constants.OSSHeaders;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.spi.ExceptionHandler;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * The consumer gets each listed object right before it routes the exchange of 
the object. So the objects of a poll are
+ * not all in memory, or all open as streams, at the same time. The consumer 
starts no scheduler. Each test calls
+ * {@code poll()} itself, and the routes run on the thread of the test.
+ */
+class OSSConsumerGetEachObjectTest extends CamelTestSupport {
+
+    // the objects of the fake bucket, by key, which the listing returns in 
the order of their keys
+    private final Map<String, byte[]> objects = new ConcurrentSkipListMap<>();
+    // the objects that the fake bucket deletes right after the listing, as 
another consumer would
+    private final Set<String> deletedAfterListing = 
ConcurrentHashMap.newKeySet();
+    // the objects whose get the fake bucket refuses with 403
+    private final Set<String> forbidden = ConcurrentHashMap.newKeySet();
+    // the number of objects that the fake client gave
+    private final AtomicInteger gets = new AtomicInteger();
+    // the streams that the fake client gave, in the order of the gets
+    private final List<TrackingInputStream> streams = new 
CopyOnWriteArrayList<>();
+    // for each get, the keys of the objects whose streams were still open
+    private final List<List<String>> openStreamsAtEachGet = new 
CopyOnWriteArrayList<>();
+    // what happened in a poll, in order: the exchanges that the route got, 
and the calls of the exception handler
+    private final List<String> events = new CopyOnWriteArrayList<>();
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        CamelContext context = super.createCamelContext();
+        context.getRegistry().bind("ossClient", ossClient());
+        context.getRegistry().bind("recordEvents", new ExceptionHandler() {
+            @Override
+            public void handleException(Throwable exception) {
+                events.add("handled " + exception.getMessage());
+            }
+
+            @Override
+            public void handleException(String message, Throwable exception) {
+                events.add("handled " + message);
+            }
+
+            @Override
+            public void handleException(String message, Exchange exchange, 
Throwable exception) {
+                events.add("handled " + message);
+            }
+        });
+        return context;
+    }
+
+    @Test
+    void eachObjectIsGotRightBeforeItsExchangeIsRouted() throws Exception {
+        objects.put("a.txt", bytes("a"));
+        objects.put("b.txt", bytes("b"));
+        objects.put("c.txt", bytes("c"));
+        List<Integer> getsWhenRouted = new CopyOnWriteArrayList<>();
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceived("a", "b", "c");
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("alibaba-oss:bucket?ossClient=#ossClient&startScheduler=false").routeId("oss")
+                        .process(e -> getsWhenRouted.add(gets.get()))
+                        .convertBodyTo(String.class)
+                        .to("mock:result");
+            }
+        });
+
+        assertThat(ossConsumer().poll()).isEqualTo(3);
+
+        mock.assertIsSatisfied();
+        assertThat(getsWhenRouted).as("the number of objects that the consumer 
got when it routed each exchange")
+                .containsExactly(1, 2, 3);
+    }
+
+    @Test
+    void streamIsClosedBeforeTheNextObjectIsGot() throws Exception {
+        objects.put("a.bin", bytes("a"));
+        objects.put("b.bin", bytes("b"));
+        objects.put("c.bin", bytes("c"));
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedMessageCount(3);
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                // the route does not read the streams, and it ends on the 
thread of the consumer
+                
from("alibaba-oss:bucket?ossClient=#ossClient&startScheduler=false&includeBody=false").routeId("oss")
+                        .streamCache(false)
+                        .to("mock:result");
+            }
+        });
+
+        assertThat(ossConsumer().poll()).isEqualTo(3);
+
+        mock.assertIsSatisfied();
+        assertThat(openStreamsAtEachGet).as("the objects whose streams were 
open when the consumer got each object")
+                .containsExactly(List.of(), List.of(), List.of());
+    }
+
+    @Test
+    void batchPropertiesCountTheListedObjects() throws Exception {
+        objects.put("a.txt", bytes("a"));
+        objects.put("b.txt", bytes("b"));
+        objects.put("c.txt", bytes("c"));
+        // the consumer finds out that b.txt no longer exists only when it 
gets it
+        deletedAfterListing.add("b.txt");
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceived("a", "c");
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("alibaba-oss:bucket?ossClient=#ossClient&startScheduler=false").routeId("oss")
+                        .convertBodyTo(String.class)
+                        .to("mock:result");
+            }
+        });
+
+        // the poll counts the objects that it did not skip
+        assertThat(ossConsumer().poll()).isEqualTo(2);
+
+        mock.assertIsSatisfied();
+        
assertThat(mock.getReceivedExchanges()).extracting(OSSConsumerGetEachObjectTest::batchProperties)
+                .as("the batch properties of the exchanges")
+                .containsExactly("a.txt: index 0, size 3, complete false", 
"c.txt: index 2, size 3, complete true");
+    }
+
+    @Test
+    void failedGetReachesTheExceptionHandlerAfterTheOtherExchangesOfThePoll() 
throws Exception {
+        objects.put("a.txt", bytes("a"));
+        objects.put("b.txt", bytes("b"));
+        objects.put("c.txt", bytes("c"));
+        forbidden.add("a.txt");
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("alibaba-oss:bucket?ossClient=#ossClient&startScheduler=false&exceptionHandler=#recordEvents")
+                        .routeId("oss")
+                        .process(e -> events.add("routed " + 
e.getIn().getHeader(OSSHeaders.OBJECT_KEY)));
+            }
+        });
+
+        assertThat(ossConsumer().poll()).isEqualTo(2);
+
+        assertThat(events).containsExactly("routed b.txt", "routed c.txt",
+                "handled Error getting object a.txt from bucket bucket. The 
object is skipped for this poll.");
+    }
+
+    private OSSConsumer ossConsumer() {
+        return (OSSConsumer) context.getRoute("oss").getConsumer();
+    }
+
+    private static byte[] bytes(String content) {
+        return content.getBytes(StandardCharsets.UTF_8);
+    }
+
+    private static String batchProperties(Exchange exchange) {
+        return exchange.getIn().getHeader(OSSHeaders.OBJECT_KEY) + ": index " 
+ exchange.getProperty(Exchange.BATCH_INDEX)
+               + ", size " + exchange.getProperty(Exchange.BATCH_SIZE)
+               + ", complete " + exchange.getProperty(Exchange.BATCH_COMPLETE);
+    }
+
+    private OSSClient ossClient() {
+        OSSClient client = Mockito.mock(OSSClient.class);
+        
Mockito.when(client.listObjectsV2(Mockito.any(ListObjectsV2Request.class))).thenAnswer(i
 -> {
+            List<ObjectSummary> contents = objects.keySet().stream().map(key 
-> {
+                ObjectSummary summary = Mockito.mock(ObjectSummary.class);
+                Mockito.when(summary.key()).thenReturn(key);
+                return summary;
+            }).toList();
+            objects.keySet().removeAll(deletedAfterListing);
+            ListObjectsV2Result result = 
Mockito.mock(ListObjectsV2Result.class);
+            Mockito.when(result.contents()).thenReturn(contents);
+            return result;
+        });
+        
Mockito.when(client.getObject(Mockito.any(GetObjectRequest.class))).thenAnswer(i
 -> {
+            String key = i.<GetObjectRequest> getArgument(0).key();
+            if (!objects.containsKey(key)) {
+                throw new OperationException("GetObject", 
ServiceException.newBuilder().statusCode(404).build());
+            }
+            if (forbidden.contains(key)) {
+                throw new OperationException("GetObject", 
ServiceException.newBuilder().statusCode(403).build());
+            }
+            gets.incrementAndGet();
+            openStreamsAtEachGet.add(streams.stream().filter(s -> 
!s.isClosed()).map(TrackingInputStream::key).toList());
+            TrackingInputStream stream = new TrackingInputStream(key, 
objects.get(key));
+            streams.add(stream);
+            GetObjectResult result = Mockito.mock(GetObjectResult.class);
+            Mockito.when(result.body()).thenReturn(stream);
+            Mockito.when(result.contentLength()).thenReturn((long) 
objects.get(key).length);
+            return result;
+        });
+        return client;
+    }
+
+    /**
+     * The stream of the content of an object. It records its key, and whether 
the consumer closed it.
+     */
+    private static final class TrackingInputStream extends 
ByteArrayInputStream {
+
+        private final String key;
+        private volatile boolean closed;
+
+        TrackingInputStream(String key, byte[] content) {
+            super(content);
+            this.key = key;
+        }
+
+        String key() {
+            return key;
+        }
+
+        boolean isClosed() {
+            return closed;
+        }
+
+        @Override
+        public void close() {
+            closed = true;
+        }
+    }
+}
diff --git 
a/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerIncludeBodyTest.java
 
b/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerIncludeBodyTest.java
index ce038ea3db49..a92c592e38dc 100644
--- 
a/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerIncludeBodyTest.java
+++ 
b/components/camel-alibaba/camel-alibaba-oss/src/test/java/org/apache/camel/component/alibaba/oss/OSSConsumerIncludeBodyTest.java
@@ -49,8 +49,8 @@ import static org.awaitility.Awaitility.await;
 
 /**
  * By default the consumer reads the content of an object into a byte array. 
With includeBody=false the body is the
- * stream of the content, which the consumer does not read, and which is 
closed when the exchange is done, also when it
- * fails, or when the exchange is not processed as the consumer stops.
+ * stream of the content, which the consumer does not read. The consumer 
closes the stream when the exchange is done,
+ * also when it fails. A consumer that stops during a poll gets only the 
object that it routes.
  */
 class OSSConsumerIncludeBodyTest extends CamelTestSupport {
 
@@ -151,7 +151,7 @@ class OSSConsumerIncludeBodyTest extends CamelTestSupport {
     }
 
     @Test
-    void streamsOfTheExchangesThatAreNotProcessedAreClosed() throws Exception {
+    void consumerThatStopsDuringAPollGetsOnlyTheObjectThatItRoutes() throws 
Exception {
         objects.put("a.bin", new byte[] { 0x41 });
         objects.put("b.bin", new byte[] { 0x42 });
         objects.put("c.bin", new byte[] { 0x43 });
@@ -162,8 +162,9 @@ class OSSConsumerIncludeBodyTest extends CamelTestSupport {
         context.addRoutes(new RouteBuilder() {
             @Override
             public void configure() {
+                // one poll only: a second poll that starts before the stop 
suspends the consumer gets b.bin and c.bin
                 
from("alibaba-oss:bucket?ossClient=#ossClient&initialDelay=0&delay=10&deleteAfterRead=true"
-                     + "&includeBody=false").routeId("oss")
+                     + "&includeBody=false&repeatCount=1").routeId("oss")
                         .streamCache(false)
                         .process(e -> {
                             if (first.compareAndSet(true, false)) {
@@ -188,7 +189,7 @@ class OSSConsumerIncludeBodyTest extends CamelTestSupport {
         await().atMost(20, TimeUnit.SECONDS)
                 .until(() -> 
context.getRouteController().getRouteStatus("oss") == ServiceStatus.Stopped);
 
-        assertThat(streams.keySet()).containsExactlyInAnyOrder("a.bin", 
"b.bin", "c.bin");
+        assertThat(streams.keySet()).as("the objects that the consumer 
got").containsExactly("a.bin");
         await().atMost(20, TimeUnit.SECONDS).untilAsserted(
                 () -> assertThat(streams.values()).allSatisfy(list -> 
assertThat(list)
                         .as("a stream of the batch is left 
open").allMatch(TrackingInputStream::isClosed)));
diff --git 
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc 
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
index 59bcf6a5762c..616db97c5546 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_25.adoc
@@ -341,6 +341,31 @@ A route that tests the `code` key of the body for an error 
needs `onException`,
 handler that redelivers now sends such a request again. A test that mocks the 
client must return a body with the `Code`
 `OK` for a send that succeeds.
 
+=== camel-alibaba-oss - the consumer gets each object right before it routes 
its exchange
+
+The `alibaba-oss` consumer now gets each listed object right before it routes 
the exchange of the object. Before, it
+got every object of the poll first. With the default `includeBody=true`, the 
content of every object of a poll was
+then in memory at the same time. With `includeBody=false`, the streams of all 
the objects of a poll were open at the
+same time. Each object over 32 KiB held a connection of the HTTP client of the 
SDK. Now only the objects of the
+exchanges in flight are in memory, or open as streams.
+
+The batch properties now count the listed objects, other than folders and 
objects that an earlier exchange still
+processes. The consumer skips an object that no longer exists, or that it 
fails to get, but still counts it. So
+`CamelBatchSize` can be higher than the number of exchanges of the poll, and 
`CamelBatchIndex` can have a gap. When
+the consumer skips the last object, no exchange of the poll has 
`CamelBatchComplete` set to `true`. Before, the batch
+properties counted only the exchanges.
+
+An aggregator with `completionFromBatchConsumer` counts the exchanges up to 
`CamelBatchSize`. So it does not complete
+the group of a poll in which the consumer skips an object. The group waits for 
the exchanges of the next poll. Such a
+route can use `completionTimeout` instead of `completionFromBatchConsumer`, 
not both. Choose a timeout longer than the
+time between two exchanges of a poll. Keep it shorter than the `delay` of the 
consumer minus the
+`completionTimeoutCheckerInterval`. With their defaults, 500 milliseconds and 
1 second, no timeout fits, so raise the
+`delay` or lower that interval.
+
+A failed get now reaches the exception handler after the consumer routed the 
other exchanges of the poll. Before, it
+reached the handler before the first exchange. A consumer that stops during a 
poll now gets no further object of that
+poll, unless `shutdownRunningTask` is `CompleteAllTasks`. Before, it had 
already got every object of the poll.
+
 === camel-alibaba-oss - a failed delete of a consumed object goes to the 
exception handler
 
 With `deleteAfterRead=true`, a failed delete of a consumed object now goes to 
the exception handler of the `alibaba-oss`

Reply via email to