This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-26669-26670-kinesis-polling-consumer in repository https://gitbox.apache.org/repos/asf/camel.git
commit 83098df23fc6894ac927de57f42e7eb651d9c083 Author: Claus Ibsen <[email protected]> AuthorDate: Thu Nov 26 16:45:26 2026 +0100 CAMEL-26669: camel-aws2-kinesis - a stop or suspend ends the poll of the polling consumer after the record being routed processBatch routed every record of a GetRecords response before it returned, and never asked isBatchAllowed(). Since CAMEL-26650 a poll holds up to 1000 records per shard, so a graceful stop of a route with a slow processor reached the shutdown timeout and was forced, and the records not routed by then failed one by one with RouteStoppingException. processBatch now stops when isBatchAllowed() is false, as aws2-ddbstream, aws2-sqs and file do. A shard whose batch was cut short does not keep the next iterator of the response: the next poll (after a resume) requests a new iterator after the last routed record, or at the first record of the response when nothing of the shard was routed yet (as CAMEL-25570 did for aws2-ddbstream). The exchanges that were not routed are released to the exchange factory. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../camel/catalog/docs/aws2-kinesis-component.adoc | 11 +- .../src/main/docs/aws2-kinesis-component.adoc | 11 +- .../component/aws2/kinesis/Kinesis2Consumer.java | 56 ++- ...isConsumerSuspendedBatchPooledExchangeTest.java | 76 ++++ .../kinesis/KinesisConsumerSuspendedBatchTest.java | 385 +++++++++++++++++++++ .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 27 +- 6 files changed, 548 insertions(+), 18 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws2-kinesis-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws2-kinesis-component.adoc index 758ab65198ad..6d0a1079e6ba 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws2-kinesis-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/aws2-kinesis-component.adoc @@ -95,10 +95,13 @@ second stay within 2 MiB per second. For example, 1000 records of 1 KiB every 50 larger records, lower `maxResultsPerRequest` or raise `delay`. While the records of a response are routed, the consumer holds that response in memory, one for each shard of the poll. -A xref:manual::graceful-shutdown.adoc[graceful shutdown] waits until the consumer has routed all the records of the -poll that is running. Choose `maxResultsPerRequest` so that the route handles the records of a poll within the shutdown -timeout (45 seconds by default). Otherwise the shutdown is forced, and the records of the poll that are not routed yet -fail with a `RouteStoppingException`. +When the route is stopped or suspended while a poll runs, the consumer stops after the record it is routing from each +shard, and a xref:manual::graceful-shutdown.adoc[graceful shutdown] waits only for these records. The consumer does not +move past the records of the response that it did not route: after a resume it reads the shard again from the first of +them. A route stopped and started again gets a new consumer, which starts from `iteratorType` (or from the resume +strategy), as at the first start. With `shutdownRunningTask` set to `CompleteAllTasks`, the consumer routes all the +records of the poll before it stops; choose `maxResultsPerRequest` then so that the route handles the records of a poll +within the shutdown timeout (45 seconds by default), or the shutdown is forced. These options apply to the polling consumer only. The KCL consumer (`useKclConsumers=true`) fetches the records with the settings of the Kinesis Client Library and does not use `maxResultsPerRequest`, `delay` or `greedy`. diff --git a/components/camel-aws/camel-aws2-kinesis/src/main/docs/aws2-kinesis-component.adoc b/components/camel-aws/camel-aws2-kinesis/src/main/docs/aws2-kinesis-component.adoc index 758ab65198ad..6d0a1079e6ba 100644 --- a/components/camel-aws/camel-aws2-kinesis/src/main/docs/aws2-kinesis-component.adoc +++ b/components/camel-aws/camel-aws2-kinesis/src/main/docs/aws2-kinesis-component.adoc @@ -95,10 +95,13 @@ second stay within 2 MiB per second. For example, 1000 records of 1 KiB every 50 larger records, lower `maxResultsPerRequest` or raise `delay`. While the records of a response are routed, the consumer holds that response in memory, one for each shard of the poll. -A xref:manual::graceful-shutdown.adoc[graceful shutdown] waits until the consumer has routed all the records of the -poll that is running. Choose `maxResultsPerRequest` so that the route handles the records of a poll within the shutdown -timeout (45 seconds by default). Otherwise the shutdown is forced, and the records of the poll that are not routed yet -fail with a `RouteStoppingException`. +When the route is stopped or suspended while a poll runs, the consumer stops after the record it is routing from each +shard, and a xref:manual::graceful-shutdown.adoc[graceful shutdown] waits only for these records. The consumer does not +move past the records of the response that it did not route: after a resume it reads the shard again from the first of +them. A route stopped and started again gets a new consumer, which starts from `iteratorType` (or from the resume +strategy), as at the first start. With `shutdownRunningTask` set to `CompleteAllTasks`, the consumer routes all the +records of the poll before it stops; choose `maxResultsPerRequest` then so that the route handles the records of a poll +within the shutdown timeout (45 seconds by default), or the shutdown is forced. These options apply to the polling consumer only. The KCL consumer (`useKclConsumers=true`) fetches the records with the settings of the Kinesis Client Library and does not use `maxResultsPerRequest`, `delay` or `greedy`. diff --git a/components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/Kinesis2Consumer.java b/components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/Kinesis2Consumer.java index 5892e6ffaaae..baaf550c672b 100644 --- a/components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/Kinesis2Consumer.java +++ b/components/camel-aws/camel-aws2-kinesis/src/main/java/org/apache/camel/component/aws2/kinesis/Kinesis2Consumer.java @@ -85,6 +85,10 @@ public class Kinesis2Consumer extends ScheduledBatchPollingConsumer implements R // cached one has expired. Like the cached iterators it is not cleared in doStop, and a route that is stopped and // started gets a new consumer. private final Map<String, String> lastSequenceNumbers = new ConcurrentHashMap<>(); + // The shards of which no record was routed yet, and whose first response with records was not routed at all as + // the route was being stopped or suspended: the sequence number of the first record of that response, where the + // next shard iterator starts + private final Map<String, String> firstNotRoutedSequenceNumbers = new ConcurrentHashMap<>(); // The time the consumer asked for the first LATEST iterator of each shard: where it continues a shard from which it // has not routed a record yet when that iterator has expired (a LATEST iterator again would skip the records stored // in between) @@ -232,22 +236,57 @@ public class Kinesis2Consumer extends ScheduledBatchPollingConsumer implements R result = getRecords(shardIterator, kinesisConnection); } + List<Record> records = result.records(); + Queue<Exchange> exchanges = createExchanges(shard, records); + int routed; try { - Queue<Exchange> exchanges = createExchanges(shard, result.records()); - processedExchangeCount.addAndGet(processBatch(CastUtils.cast(exchanges))); + routed = processBatch(CastUtils.cast(exchanges)); } catch (Exception e) { throw new RuntimeException(e); } + processedExchangeCount.addAndGet(routed); + + if (routed < records.size()) { + // the route is being stopped or suspended, and processBatch did not route the rest of the records + batchCutShort(shard.shardId(), records, routed, exchanges); + return; + } // remember the last record of the batch, to continue after it when the next shard iterator has expired // before it is used (an iterator is valid for 5 minutes) - List<Record> records = result.records(); if (!records.isEmpty()) { lastSequenceNumbers.put(shard.shardId(), records.get(records.size() - 1).sequenceNumber()); + firstNotRoutedSequenceNumbers.remove(shard.shardId()); } updateShardIterator(shard, result.nextShardIterator()); } + /** + * Does not move past the records of the response that were not routed, so that the next poll of this consumer + * (after a resume) routes them: the next shard iterator of the response is not kept (a null one, of a closed shard, + * would mark the shard closed before its last records are routed), and the next poll requests a new iterator at the + * first record that was not routed. + */ + private void batchCutShort(String shardId, List<Record> records, int routed, Queue<Exchange> notRouted) { + if (routed > 0) { + // AFTER_SEQUENCE_NUMBER of the last routed record + lastSequenceNumbers.put(shardId, records.get(routed - 1).sequenceNumber()); + firstNotRoutedSequenceNumbers.remove(shardId); + } else if (!lastSequenceNumbers.containsKey(shardId)) { + // nothing routed from the shard yet: AT_SEQUENCE_NUMBER of the first record of the response, and not the + // configured iterator type again (it would skip these records with LATEST) + firstNotRoutedSequenceNumbers.put(shardId, records.get(0).sequenceNumber()); + } + currentShardIterators.remove(shardId); + LOG.debug("Routed {} of the {} records of shard {} on stream {} before the consumer stopped or was suspended", + routed, records.size(), shardId, getEndpoint().getConfiguration().getStreamName()); + // processBatch removes the exchanges it routes: those left are never routed, and nothing else gives them back + // to the exchange factory + for (Exchange exchange : notRouted) { + releaseExchange(exchange, true); + } + } + private GetRecordsResponse getRecords(String shardIterator, KinesisConnection kinesisConnection) { GetRecordsRequest req = GetRecordsRequest .builder() @@ -285,10 +324,14 @@ public class Kinesis2Consumer extends ScheduledBatchPollingConsumer implements R currentShardIterators.put(shard.shardId(), nextShardIterator == null ? CLOSED_SHARD_ITERATOR : nextShardIterator); } + /** + * Routes the exchanges one after the other, and stops when the route is being stopped or suspended (unless its + * shutdownRunningTask is CompleteAllTasks): the exchanges that are not routed stay in the queue. + */ @Override public int processBatch(Queue<Object> exchanges) throws Exception { int processedExchanges = 0; - while (!exchanges.isEmpty()) { + while (!exchanges.isEmpty() && isBatchAllowed()) { final Exchange exchange = ObjectHelper.cast(Exchange.class, exchanges.poll()); // use default consumer callback @@ -338,6 +381,11 @@ public class Kinesis2Consumer extends ScheduledBatchPollingConsumer implements R // shard again (TRIM_HORIZON, AT_TIMESTAMP, a sequence number) or skip the new ones (LATEST) request.shardIteratorType(ShardIteratorType.AFTER_SEQUENCE_NUMBER) .startingSequenceNumber(lastSequenceNumber); + } else if (firstNotRoutedSequenceNumbers.containsKey(shardId)) { + // no record of this shard was routed, and the consumer stopped routing the first response with + // records when the route was suspended: start at the first record of that response + request.shardIteratorType(ShardIteratorType.AT_SEQUENCE_NUMBER) + .startingSequenceNumber(firstNotRoutedSequenceNumbers.get(shardId)); } else if (latestStartTimes.containsKey(shardId)) { // the shard started at LATEST and the expired iterator returned no record: continue from the time of // that start, so the records stored since then are routed (Kinesis compares this time of the consumer's diff --git a/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerSuspendedBatchPooledExchangeTest.java b/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerSuspendedBatchPooledExchangeTest.java new file mode 100644 index 000000000000..706af2096093 --- /dev/null +++ b/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerSuspendedBatchPooledExchangeTest.java @@ -0,0 +1,76 @@ +/* + * 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.kinesis; + +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.apache.camel.CamelContext; +import org.apache.camel.ServiceStatus; +import org.apache.camel.impl.engine.PooledExchangeFactory; +import org.apache.camel.spi.ExchangeFactory; +import org.junit.jupiter.api.Test; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The same with the pooled exchange factory: the exchanges created for the records that a suspending consumer does not + * route are given back to the pool, once, so the records routed after the resume do not share an exchange. + */ +class KinesisConsumerSuspendedBatchPooledExchangeTest extends KinesisConsumerSuspendedBatchTest { + + @Override + protected CamelContext createCamelContext() throws Exception { + CamelContext context = super.createCamelContext(); + PooledExchangeFactory factory = new PooledExchangeFactory(); + factory.setStatisticsEnabled(true); + context.getCamelContextExtension().setExchangeFactory(factory); + return context; + } + + @Test + void exchangesOfTheRecordsThatWereNotRoutedAreGivenBackToThePool() throws Exception { + stream.addShard("shard-0"); + stream.put("shard-0", 4); + interruptAtRecord = "shard-0/2"; + + context.getCamelContextExtension().getExchangeFactoryManager().setStatisticsEnabled(true); + context.getRouteController().startRoute(ROUTE_ID); + awaitRouteStatus(ServiceStatus.Suspended); + assertEquals(List.of("shard-0/1", "shard-0/2"), routed); + // one exchange per record of the response: two were routed, and the two that were not are given back as well + awaitExchangesTakenAndReleased(4); + + context.getRouteController().resumeRoute(ROUTE_ID); + await().atMost(20, TimeUnit.SECONDS).untilAsserted( + () -> assertEquals(List.of("shard-0/1", "shard-0/2", "shard-0/3", "shard-0/4"), routed, + "records routed after the resume")); + // and only once: the pool does not hold an exchange twice + awaitExchangesTakenAndReleased(6); + } + + private void awaitExchangesTakenAndReleased(int expected) { + await().atMost(20, TimeUnit.SECONDS).untilAsserted(() -> { + ExchangeFactory.Statistics stats + = context.getCamelContextExtension().getExchangeFactoryManager().getStatistics(); + assertEquals(expected, stats.getCreatedCounter() + stats.getAcquiredCounter(), "exchanges taken"); + assertEquals(expected, stats.getReleasedCounter(), "exchanges given back to the pool"); + assertEquals(0, stats.getDiscardedCounter(), "exchanges discarded"); + }); + } +} diff --git a/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerSuspendedBatchTest.java b/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerSuspendedBatchTest.java new file mode 100644 index 000000000000..fe43285db455 --- /dev/null +++ b/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerSuspendedBatchTest.java @@ -0,0 +1,385 @@ +/* + * 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.kinesis; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import org.apache.camel.BindToRegistry; +import org.apache.camel.ServiceStatus; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.test.junit6.CamelTestSupport; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import software.amazon.awssdk.core.SdkBytes; +import software.amazon.awssdk.services.kinesis.KinesisClient; +import software.amazon.awssdk.services.kinesis.model.GetRecordsRequest; +import software.amazon.awssdk.services.kinesis.model.GetRecordsResponse; +import software.amazon.awssdk.services.kinesis.model.GetShardIteratorRequest; +import software.amazon.awssdk.services.kinesis.model.GetShardIteratorResponse; +import software.amazon.awssdk.services.kinesis.model.ListShardsRequest; +import software.amazon.awssdk.services.kinesis.model.ListShardsResponse; +import software.amazon.awssdk.services.kinesis.model.Record; +import software.amazon.awssdk.services.kinesis.model.Shard; +import software.amazon.awssdk.services.kinesis.model.ShardIteratorType; + +import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +/** + * A route that is stopped or suspended while the polling consumer routes the records of a GetRecords response: the + * consumer stops after the record it is routing (with the default shutdownRunningTask CompleteCurrentTaskOnly), and + * after a resume it routes the records of that response that it did not route, once. + */ +class KinesisConsumerSuspendedBatchTest extends CamelTestSupport { + + static final String ROUTE_ID = "kinesis"; + + final FakeStream stream = new FakeStream(); + + // the records routed, as shard/sequence number + final List<String> routed = new CopyOnWriteArrayList<>(); + // the record whose processor stops or suspends the route (once), as shard/sequence number + volatile String interruptAtRecord; + // the record whose processor waits until the consumer stops its batch, as shard/sequence number + volatile String waitAtRecord; + volatile boolean stopInsteadOfSuspend; + + private final AtomicBoolean requested = new AtomicBoolean(); + private final AtomicReference<Exception> controlFailure = new AtomicReference<>(); + private volatile Thread controller; + + @BindToRegistry("kinesis") + final KinesisClient kinesisClient = stream.client(); + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + from("aws2-kinesis://stream?amazonKinesisClient=#kinesis&iteratorType=TRIM_HORIZON" + + "&initialDelay=0&delay=10&shardMonitorInterval=100") + .routeId(ROUTE_ID).autoStartup(false) + .process(exchange -> { + String shardId = exchange.getMessage().getHeader(Kinesis2Constants.SHARD_ID, String.class); + String sequenceNumber + = exchange.getMessage().getHeader(Kinesis2Constants.SEQUENCE_NUMBER, String.class); + String record = shardId + "/" + sequenceNumber; + if (record.equals(interruptAtRecord)) { + stopOrSuspendRouteDuringThePoll(); + } else if (record.equals(waitAtRecord)) { + awaitBatchEnded(); + } + routed.add(record); + }); + } + }; + } + + @Test + void recordsNotRoutedByASuspendingConsumerAreRoutedAfterTheResume() throws Exception { + stream.addShard("shard-0"); + stream.put("shard-0", 4); + interruptAtRecord = "shard-0/2"; + + context.getRouteController().startRoute(ROUTE_ID); + awaitRouteStatus(ServiceStatus.Suspended); + assertEquals(List.of("shard-0/1", "shard-0/2"), routed, + "the suspend ends the batch after the record that is being routed"); + + context.getRouteController().resumeRoute(ROUTE_ID); + await().atMost(20, TimeUnit.SECONDS).untilAsserted( + () -> assertEquals(List.of("shard-0/1", "shard-0/2", "shard-0/3", "shard-0/4"), routed, + "records routed after the resume")); + + // the consumer continues after the last record it routed + GetShardIteratorRequest last = stream.lastIteratorRequest(); + assertEquals(ShardIteratorType.AFTER_SEQUENCE_NUMBER, last.shardIteratorType()); + assertEquals("2", last.startingSequenceNumber()); + assertNoMoreRecordsRouted(4); + } + + @Test + void recordsOfAResponseThatArrivesWhileSuspendingAreRoutedAfterTheResume() throws Exception { + stream.addShard("shard-0"); + stream.put("shard-0", 2); + // the route is suspended while the GetRecords request is in flight: none of its records is routed + stream.onRecordsReturned = shardId -> stopOrSuspendRouteDuringThePoll(); + + context.getRouteController().startRoute(ROUTE_ID); + awaitRouteStatus(ServiceStatus.Suspended); + assertEquals(List.of(), routed, "nothing is routed by the suspending consumer"); + + context.getRouteController().resumeRoute(ROUTE_ID); + await().atMost(20, TimeUnit.SECONDS).untilAsserted( + () -> assertEquals(List.of("shard-0/1", "shard-0/2"), routed, "records routed after the resume")); + + // nothing was routed from the shard: the consumer starts at the first record that was not routed, and not + // at the configured iterator type again + GetShardIteratorRequest last = stream.lastIteratorRequest(); + assertEquals(ShardIteratorType.AT_SEQUENCE_NUMBER, last.shardIteratorType()); + assertEquals("1", last.startingSequenceNumber()); + assertNoMoreRecordsRouted(2); + } + + @Test + void closedShardWhoseLastResponseWasCutShortIsReadToItsEnd() throws Exception { + stream.addShard("shard-0"); + stream.put("shard-0", 3); + // the last response of the shard has no next shard iterator + stream.close("shard-0"); + interruptAtRecord = "shard-0/1"; + + context.getRouteController().startRoute(ROUTE_ID); + awaitRouteStatus(ServiceStatus.Suspended); + Kinesis2Consumer consumer = (Kinesis2Consumer) context.getRoute(ROUTE_ID).getConsumer(); + assertFalse(consumer.isShardClosed("shard-0"), "records of the shard are not routed yet"); + + context.getRouteController().resumeRoute(ROUTE_ID); + await().atMost(20, TimeUnit.SECONDS).untilAsserted( + () -> assertEquals(List.of("shard-0/1", "shard-0/2", "shard-0/3"), routed, + "records routed after the resume")); + await().atMost(20, TimeUnit.SECONDS).until(() -> consumer.isShardClosed("shard-0")); + } + + @Test + void eachShardEndsItsBatchAtItsOwnRecordAndContinuesThereAfterTheResume() throws Exception { + stream.addShard("shard-0"); + stream.addShard("shard-1"); + stream.put("shard-0", 5); + stream.put("shard-1", 5); + interruptAtRecord = "shard-0/2"; + // routed while the consumer is being suspended, if the shard is read at the same time as shard-0 + waitAtRecord = "shard-1/3"; + + context.getRouteController().startRoute(ROUTE_ID); + awaitRouteStatus(ServiceStatus.Suspended); + assertEquals(List.of("shard-0/1", "shard-0/2"), routedOf("shard-0")); + assertTrue(routedOf("shard-1").size() <= 3, "shard-1 ends its batch too: " + routedOf("shard-1")); + + context.getRouteController().resumeRoute(ROUTE_ID); + await().atMost(20, TimeUnit.SECONDS).untilAsserted(() -> { + assertEquals(List.of("shard-0/1", "shard-0/2", "shard-0/3", "shard-0/4", "shard-0/5"), routedOf("shard-0")); + assertEquals(List.of("shard-1/1", "shard-1/2", "shard-1/3", "shard-1/4", "shard-1/5"), routedOf("shard-1")); + }); + assertNoMoreRecordsRouted(10); + } + + @Test + void stopEndsThePollAfterTheRecordBeingRouted() throws Exception { + stream.addShard("shard-0"); + // one response of 1000 records (maxResultsPerRequest) + stream.put("shard-0", 1000); + interruptAtRecord = "shard-0/2"; + stopInsteadOfSuspend = true; + context.getShutdownStrategy().setTimeout(60); + + context.getRouteController().startRoute(ROUTE_ID); + awaitRouteStatus(ServiceStatus.Stopped); + assertEquals(List.of("shard-0/1", "shard-0/2"), routed, + "the stop ends the batch after the record that is being routed"); + assertFalse(context.getShutdownStrategy().hasTimeoutOccurred(), "the graceful stop did not time out"); + } + + List<String> routedOf(String shardId) { + return routed.stream().filter(r -> r.startsWith(shardId + "/")).toList(); + } + + private void assertNoMoreRecordsRouted(int expected) { + // a few more polls: nothing is routed twice + int requests = stream.recordRequests(); + await().atMost(20, TimeUnit.SECONDS).until(() -> stream.recordRequests() >= requests + 3); + assertEquals(expected, routed.size(), "records routed: " + routed); + } + + /** + * Called by the thread that routes a record: stops or suspends the route from another thread, as a route must not + * stop itself, and returns when the stop has reached the consumer (it no longer routes the following records of the + * batch). + */ + private void stopOrSuspendRouteDuringThePoll() { + if (!requested.compareAndSet(false, true)) { + return; + } + controller = new Thread(() -> { + try { + if (stopInsteadOfSuspend) { + context.getRouteController().stopRoute(ROUTE_ID); + } else { + context.getRouteController().suspendRoute(ROUTE_ID); + } + } catch (Exception e) { + controlFailure.set(e); + } + }, "control-route"); + controller.start(); + awaitBatchEnded(); + } + + /** + * Waits until the consumer no longer allows its batch to go on. An interrupt of the thread must not end this wait. + */ + private void awaitBatchEnded() { + Kinesis2Consumer consumer = (Kinesis2Consumer) context.getRoute(ROUTE_ID).getConsumer(); + CountDownLatch batchEnded = new CountDownLatch(1); + Thread watcher = new Thread(() -> { + await().atMost(20, TimeUnit.SECONDS).until(() -> !consumer.isBatchAllowed()); + batchEnded.countDown(); + }, "watch-consumer"); + watcher.start(); + + boolean interrupted = false; + boolean ended = false; + long remaining = TimeUnit.SECONDS.toNanos(30); + long deadline = System.nanoTime() + remaining; + while (!ended && remaining > 0) { + try { + ended = batchEnded.await(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + interrupted = true; + } + remaining = deadline - System.nanoTime(); + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + + void awaitRouteStatus(ServiceStatus status) throws InterruptedException { + await().atMost(20, TimeUnit.SECONDS).until(() -> controller != null); + controller.join(TimeUnit.SECONDS.toMillis(60)); + assertFalse(controller.isAlive(), "the route stop or suspend has returned"); + assertNull(controlFailure.get()); + assertEquals(status, context.getRouteController().getRouteStatus(ROUTE_ID)); + } + + /** + * Shards with records numbered from 1, and shard iterators that point between two records of a shard. + */ + static final class FakeStream { + volatile Consumer<String> onRecordsReturned; + private final List<GetShardIteratorRequest> iteratorRequests = new CopyOnWriteArrayList<>(); + private final Map<String, List<Record>> records = new LinkedHashMap<>(); + private final Set<String> closed = new HashSet<>(); + private final Map<String, String> iteratorShard = new HashMap<>(); + private final Map<String, Integer> iteratorPosition = new HashMap<>(); + private int iterators; + private int recordRequests; + + synchronized void addShard(String shardId) { + records.put(shardId, new ArrayList<>()); + } + + synchronized void put(String shardId, int count) { + List<Record> list = records.get(shardId); + for (int i = 0; i < count; i++) { + String sequenceNumber = String.valueOf(list.size() + 1); + list.add(Record.builder().sequenceNumber(sequenceNumber).partitionKey("key") + .data(SdkBytes.fromString("record-" + sequenceNumber, StandardCharsets.UTF_8)).build()); + } + } + + synchronized void close(String shardId) { + closed.add(shardId); + } + + synchronized int recordRequests() { + return recordRequests; + } + + GetShardIteratorRequest lastIteratorRequest() { + return iteratorRequests.get(iteratorRequests.size() - 1); + } + + KinesisClient client() { + KinesisClient client = Mockito.mock(KinesisClient.class); + when(client.listShards(any(ListShardsRequest.class))) + .thenAnswer(inv -> listShards()); + when(client.getShardIterator(any(GetShardIteratorRequest.class))) + .thenAnswer(inv -> getShardIterator(inv.getArgument(0))); + when(client.getRecords(any(GetRecordsRequest.class))) + .thenAnswer(inv -> getRecords(inv.getArgument(0))); + return client; + } + + private synchronized ListShardsResponse listShards() { + List<Shard> shards = new ArrayList<>(); + for (String shardId : records.keySet()) { + shards.add(Shard.builder().shardId(shardId).build()); + } + return ListShardsResponse.builder().shards(shards).build(); + } + + private synchronized GetShardIteratorResponse getShardIterator(GetShardIteratorRequest request) { + iteratorRequests.add(request); + List<Record> list = records.get(request.shardId()); + int position = switch (request.shardIteratorType()) { + case TRIM_HORIZON -> 0; + case LATEST -> list.size(); + case AT_SEQUENCE_NUMBER -> Integer.parseInt(request.startingSequenceNumber()) - 1; + case AFTER_SEQUENCE_NUMBER -> Integer.parseInt(request.startingSequenceNumber()); + default -> throw new IllegalArgumentException("Not expected in this test: " + request.shardIteratorType()); + }; + return GetShardIteratorResponse.builder().shardIterator(newIterator(request.shardId(), position)).build(); + } + + private GetRecordsResponse getRecords(GetRecordsRequest request) { + GetRecordsResponse response; + String shardId; + synchronized (this) { + recordRequests++; + String iterator = request.shardIterator(); + shardId = iteratorShard.get(iterator); + List<Record> list = records.get(shardId); + int from = iteratorPosition.get(iterator); + int to = Math.min(list.size(), from + request.limit()); + String next = closed.contains(shardId) && to == list.size() ? null : newIterator(shardId, to); + response = GetRecordsResponse.builder().records(new ArrayList<>(list.subList(from, to))) + .nextShardIterator(next).build(); + } + Consumer<String> hook = onRecordsReturned; + if (hook != null && !response.records().isEmpty()) { + hook.accept(shardId); + } + return response; + } + + private String newIterator(String shardId, int position) { + String iterator = "iterator-" + (++iterators); + iteratorShard.put(iterator, shardId); + iteratorPosition.put(iterator, position); + return iterator; + } + } +} diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc index 38b8b68c3feb..2230bb4b7da9 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc @@ -2394,7 +2394,7 @@ a success reply, and the exchange could stay inflight. Compared with 4.23: is restarted. Before, the error ended some loops silently (a polling task, a `seda` thread, every route on a shared `timer`) and left others running. A consumer that is pushed requests (such as HTTP or `direct`) only fails that request. A route that catches the `Error` explicitly keeps its consumer going. Not yet covered: a batch consumer that - does not check between the messages of a batch whether it may go on (such as `aws2-kinesis` or `couchdb`) routes the + does not check between the messages of a batch whether it may go on (such as `couchdb`) routes the rest of the batch it has already fetched before it stops, and a `VirtualMachineError` thrown by a `RoutePolicy` fails the exchange without stopping the consumer. * A polling consumer whose poll throws another `Error` (such as a `NoClassDefFoundError` of a client library) treats it @@ -7337,16 +7337,31 @@ that many records, so with the default `delay` of 500 ms it can read up to about 1000 records per shard in memory while they are routed. The KCL consumer (`useKclConsumers=true`) does not use this option. -A graceful shutdown waits until the consumer has routed all the records of the poll that is running. With 1000 records -per shard and a route that takes 50 ms per record, a poll takes about 50 seconds, which is more than the default -xref:graceful-shutdown.adoc[shutdown timeout] of 45 seconds. The shutdown is then forced, and the records of the poll -that are not routed yet fail with a `RouteStoppingException`. Before, a poll held one record per shard. Lower -`maxResultsPerRequest`, or raise the shutdown timeout, so that the records of a poll are routed within the timeout. +A stop or suspend of the route ends the poll after the record being routed (see the next section). With +`shutdownRunningTask` set to `CompleteAllTasks`, a graceful shutdown waits until the consumer has routed all the +records of the poll that is running: with 1000 records per shard and a route that takes 50 ms per record, a poll takes +about 50 seconds, which is more than the default xref:graceful-shutdown.adoc[shutdown timeout] of 45 seconds. The +shutdown is then forced, and the records of the poll that are not routed yet fail with a `RouteStoppingException`. +Lower `maxResultsPerRequest`, or raise the shutdown timeout, so that the records of a poll are routed within the +timeout. To keep the previous behaviour, set `maxResultsPerRequest=1`. See the xref:components::aws2-kinesis-component.adoc[AWS Kinesis component] for how `maxResultsPerRequest`, `delay` and `greedy` relate to the Kinesis read quotas of a shard. +=== camel-aws2-kinesis - a stop or suspend ends the poll after the record being routed + +The polling consumer (without `useKclConsumers`) now stops routing the records of a `GetRecords` response when its +route is stopped or suspended, after the record it is routing from each shard, as the other batch consumers do (such +as `aws2-sqs`, `aws2-ddbstream` and `file`). Before, it routed all the records of the poll first (up to +`maxResultsPerRequest` per shard), so with a slow route a stop could reach the shutdown timeout and be forced, and the +records not routed by then failed with a `RouteStoppingException`. + +The consumer does not move past the records it did not route: after a resume it reads them again (with a new shard +iterator at the first record it did not route). A route that is stopped and started again gets a new consumer, which starts +from `iteratorType`, or from its resume strategy, as before. Routes that need the previous behaviour set +`shutdownRunningTask` to `CompleteAllTasks`. + === camel-aws2-kinesis - shardClosed=fail reports a closed shard once With `shardClosed=fail`, the consumer now reports a closed shard once: it hands a `ReachedClosedStatusException` to
