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 1c223d7c5d13 CAMEL-27458: camel-aws2-kinesis - the consumer is not
ready, and its polls fail, while ListShards fails and no shard was listed
(#30840)
1c223d7c5d13 is described below
commit 1c223d7c5d1308d72a6f55d95396b54a5860adf5
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:01:15 2026 +0530
CAMEL-27458: camel-aws2-kinesis - the consumer is not ready, and its polls
fail, while ListShards fails and no shard was listed (#30840)
The polling consumer reads the shards of the list its shard monitor gets
with ListShards (since CAMEL-24197 also with
a configured shardId, which called DescribeStream in each poll before).
When ListShards fails from the start and keeps
failing (no kinesis:ListShards permission, a stream that does not exist,
sustained throttling), the list stays empty:
every poll read nothing, still ended as a successful poll
(forceConsumerAsReady, error counter 0), and the consumer
health check reported the consumer ready and UP while no record was ever
read.
The shard monitor now keeps the error of its last ListShards (cleared when
a ListShards returns). While no shard has
been listed, a poll fails with an IllegalStateException whose cause is that
error, so the error counter, the health
check (readiness DOWN, with the error) and the back-off options work as for
any failed poll. isConsumerReady() is
false until the shards have been listed, which also covers a first
ListShards that is slower than the initial delay of
the poll. Once the shards are listed nothing changes: a later ListShards
failure keeps the consumer reading the shards
it knows.
ShardMonitor is package-private so that the test runs it. Upgrade guide
4.24: new entry.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../component/aws2/kinesis/Kinesis2Consumer.java | 34 +++-
.../KinesisConsumerShardListHealthTest.java | 211 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 11 ++
3 files changed, 253 insertions(+), 3 deletions(-)
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 857f080bafd7..5892e6ffaaae 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
@@ -93,6 +93,10 @@ public class Kinesis2Consumer extends
ScheduledBatchPollingConsumer implements R
// appeared after the first list as the child of a listed shard
(resharding).
private final Set<String> knownShardIds = ConcurrentHashMap.newKeySet();
private final Set<String> childShardIds = ConcurrentHashMap.newKeySet();
+ // The failure of the last ListShards of the shard monitor, null once a
ListShards succeeded. While the shards have
+ // not been listed, poll() reports it, so that a consumer that cannot list
the shards (no permission, no such
+ // stream) is not seen healthy while it reads nothing.
+ private volatile Exception shardListError;
private volatile List<Shard> currentShardList = List.of();
private static final String SHARD_MONITOR_EXECUTOR_NAME =
"Kinesis_shard_monitor";
@@ -119,6 +123,19 @@ public class Kinesis2Consumer extends
ScheduledBatchPollingConsumer implements R
protected int poll() throws Exception {
var processedExchangeCount = new AtomicInteger(0);
+ List<Shard> shardList = getCurrentShardList();
+ if (shardList.isEmpty()) {
+ // the shard monitor has not listed the shards yet, so there is
nothing to read
+ Exception error = shardListError;
+ if (error != null) {
+ throw new IllegalStateException(
+ "Cannot list the shards of stream " +
getEndpoint().getConfiguration().getStreamName() + ": "
+ + error,
+ error);
+ }
+ return 0;
+ }
+
String shardId = getEndpoint().getConfiguration().getShardId();
if (!shardId.isEmpty()) {
// skip if the shard is closed
@@ -131,7 +148,7 @@ public class Kinesis2Consumer extends
ScheduledBatchPollingConsumer implements R
// Use the cached shard list from ShardMonitor instead of calling
DescribeStream
// on every poll. ShardMonitor uses ListShards (paginated, 100 TPS
limit) vs
// DescribeStream (unpaginated, 10 TPS limit).
- Shard shard = getCurrentShardList().stream()
+ Shard shard = shardList.stream()
.filter(s -> s.shardId().equalsIgnoreCase(shardId))
.findFirst()
.orElse(null);
@@ -149,7 +166,7 @@ public class Kinesis2Consumer extends
ScheduledBatchPollingConsumer implements R
// other shards still read and route, and the next poll could
start before they are done. The poll fails
// only once all the shards of the list have been read.
Queue<RuntimeException> failures = new ConcurrentLinkedQueue<>();
- getCurrentShardList()
+ shardList
.parallelStream()
.forEach(shard -> {
try {
@@ -282,6 +299,14 @@ public class Kinesis2Consumer extends
ScheduledBatchPollingConsumer implements R
return processedExchanges;
}
+ /**
+ * Not ready before the shard monitor has listed the shards of the stream:
until then a poll reads nothing.
+ */
+ @Override
+ public boolean isConsumerReady() {
+ return !getCurrentShardList().isEmpty() && super.isConsumerReady();
+ }
+
@Override
public Kinesis2Endpoint getEndpoint() {
return (Kinesis2Endpoint) super.getEndpoint();
@@ -543,11 +568,13 @@ public class Kinesis2Consumer extends
ScheduledBatchPollingConsumer implements R
this.currentShardList = List.copyOf(latestShardList);
}
- private class ShardMonitor implements Runnable {
+ // package-private for tests, which run the monitor themselves
+ class ShardMonitor implements Runnable {
@Override
public void run() {
try {
List<Shard> latestShardList = getShardList(connection);
+ shardListError = null;
if (ObjectHelper.isNotEmpty(latestShardList)) {
// before the list is published, so that poll() knows the
child shards of the list it reads
trackChildShards(latestShardList);
@@ -555,6 +582,7 @@ public class Kinesis2Consumer extends
ScheduledBatchPollingConsumer implements R
}
} catch (Exception e) {
LOG.warn("Exception getting latest shard list", e);
+ shardListError = e;
}
}
diff --git
a/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerShardListHealthTest.java
b/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerShardListHealthTest.java
new file mode 100644
index 000000000000..0a33b6aaaaa3
--- /dev/null
+++
b/components/camel-aws/camel-aws2-kinesis/src/test/java/org/apache/camel/component/aws2/kinesis/KinesisConsumerShardListHealthTest.java
@@ -0,0 +1,211 @@
+/*
+ * 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.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.camel.AsyncProcessor;
+import org.apache.camel.CamelContext;
+import org.apache.camel.health.HealthCheck;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.ScheduledPollConsumerHealthCheck;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
+import software.amazon.awssdk.core.SdkBytes;
+import software.amazon.awssdk.services.kinesis.KinesisClient;
+import software.amazon.awssdk.services.kinesis.model.AccessDeniedException;
+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.ResourceNotFoundException;
+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.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * The consumer reads the shards of the list of its shard monitor. While the
monitor has not listed the shards
+ * (ListShards fails, for example without the kinesis:ListShards permission or
for a stream that does not exist), a poll
+ * reads nothing: the consumer must not be seen ready and healthy then. The
polls and the monitor runs are driven by the
+ * test.
+ */
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
+class KinesisConsumerShardListHealthTest {
+
+ @Mock
+ private KinesisClient kinesisClient;
+ @Mock
+ private AsyncProcessor processor;
+
+ private final CamelContext context = new DefaultCamelContext();
+ private final Kinesis2Component component = new Kinesis2Component(context);
+ private final AtomicInteger listShardsCalls = new AtomicInteger();
+ // what the next ListShards does: answers this response, or throws this
exception
+ private final AtomicReference<Object> listShards = new AtomicReference<>();
+ // when set, ListShards waits for it before it answers
+ private volatile CountDownLatch listShardsGate;
+ private Kinesis2Consumer consumer;
+ private ScheduledPollConsumerHealthCheck healthCheck;
+
+ @AfterEach
+ void tearDown() {
+ if (consumer != null) {
+ consumer.stop();
+ }
+ context.stop();
+ }
+
+ @Test
+ void readinessIsDownWithTheFailureUntilTheShardsAreListed() {
+ AccessDeniedException denied = AccessDeniedException.builder()
+ .message("User is not authorized to perform:
kinesis:ListShards").statusCode(400).build();
+ listShards.set(denied);
+ startConsumer("");
+ // the run of the monitor at start, then one run of the test
+ await().atMost(10, TimeUnit.SECONDS).until(() -> listShardsCalls.get()
>= 1);
+ consumer.new ShardMonitor().run();
+
+ consumer.run();
+ consumer.run();
+
+ HealthCheck.Result result = readiness();
+ assertEquals(HealthCheck.State.DOWN, result.getState());
+ assertEquals(2L, consumer.getErrorCounter());
+ Throwable error = result.getError().orElseThrow();
+ assertInstanceOf(IllegalStateException.class, error);
+ assertSame(denied, error.getCause());
+ assertTrue(error.getMessage().contains("Cannot list the shards of
stream orders"), error.getMessage());
+ // a readiness check only (as for every polling consumer): liveness is
not affected
+ assertFalse(healthCheck.isLiveness());
+ verify(kinesisClient,
never()).getRecords(any(GetRecordsRequest.class));
+
+ // ListShards succeeds again: the next poll reads the shard, and the
consumer is ready
+
listShards.set(ListShardsResponse.builder().shards(Shard.builder().shardId("s0").build()).build());
+ consumer.new ShardMonitor().run();
+ consumer.run();
+
+ assertEquals(HealthCheck.State.UP, readiness().getState());
+ assertEquals(0L, consumer.getErrorCounter());
+ verify(kinesisClient).getRecords(any(GetRecordsRequest.class));
+ }
+
+ @Test
+ void readinessIsDownWithTheFailureForAConfiguredShardId() {
+ ResourceNotFoundException notFound =
ResourceNotFoundException.builder()
+ .message("Stream orders under account 123456789012 not
found.").statusCode(400).build();
+ listShards.set(notFound);
+ startConsumer("s0");
+ await().atMost(10, TimeUnit.SECONDS).until(() -> listShardsCalls.get()
>= 1);
+ consumer.new ShardMonitor().run();
+
+ consumer.run();
+
+ HealthCheck.Result result = readiness();
+ assertEquals(HealthCheck.State.DOWN, result.getState());
+ assertSame(notFound, result.getError().orElseThrow().getCause());
+ verify(kinesisClient,
never()).getRecords(any(GetRecordsRequest.class));
+ }
+
+ @Test
+ void notReadyWhileTheFirstListShardsIsInProgress() {
+ // a slow first ListShards: the first poll comes before the monitor
has listed the shards
+ CountDownLatch listed = new CountDownLatch(1);
+ listShardsGate = listed;
+
listShards.set(ListShardsResponse.builder().shards(Shard.builder().shardId("s0").build()).build());
+ startConsumer("");
+ await().atMost(10, TimeUnit.SECONDS).until(() -> listShardsCalls.get()
>= 1);
+
+ consumer.run();
+
+ assertEquals(HealthCheck.State.DOWN, readiness().getState());
+ assertEquals(0L, consumer.getErrorCounter());
+
+ listed.countDown();
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
!consumer.getCurrentShardList().isEmpty());
+ consumer.run();
+
+ assertEquals(HealthCheck.State.UP, readiness().getState());
+ verify(kinesisClient).getRecords(any(GetRecordsRequest.class));
+ }
+
+ private void startConsumer(String shardId) {
+
when(kinesisClient.listShards(any(ListShardsRequest.class))).thenAnswer(invocation
-> {
+ listShardsCalls.incrementAndGet();
+ CountDownLatch gate = listShardsGate;
+ if (gate != null) {
+ gate.await(10, TimeUnit.SECONDS);
+ }
+ Object next = listShards.get();
+ if (next instanceof RuntimeException e) {
+ throw e;
+ }
+ return next;
+ });
+
when(kinesisClient.getShardIterator(any(GetShardIteratorRequest.class)))
+
.thenReturn(GetShardIteratorResponse.builder().shardIterator("it").build());
+
when(kinesisClient.getRecords(any(GetRecordsRequest.class))).thenReturn(GetRecordsResponse.builder()
+ .nextShardIterator("next")
+ .records(Record.builder().sequenceNumber("1").partitionKey("p")
+ .data(SdkBytes.fromString("x",
StandardCharsets.UTF_8)).build())
+ .build());
+
+ component.start();
+ Kinesis2Configuration configuration = new Kinesis2Configuration();
+ configuration.setAmazonKinesisClient(kinesisClient);
+ configuration.setStreamName("orders");
+ configuration.setShardId(shardId);
+ configuration.setIteratorType(ShardIteratorType.TRIM_HORIZON);
+ // the monitor runs once at start; the test runs it after that
+ configuration.setShardMonitorInterval(TimeUnit.DAYS.toMillis(1));
+ Kinesis2Endpoint endpoint = new
Kinesis2Endpoint("aws2-kinesis:orders", configuration, component);
+ endpoint.start();
+ consumer = new Kinesis2Consumer(endpoint, processor);
+ consumer.setConnection(component.getConnection());
+ // the test polls with run(), which updates the state the health check
reads as a scheduled poll does
+ consumer.setStartScheduler(false);
+ consumer.start();
+ healthCheck = new ScheduledPollConsumerHealthCheck(consumer,
"consumer:orders");
+ }
+
+ private HealthCheck.Result readiness() {
+ return healthCheck.call(Map.of(HealthCheck.CHECK_KIND,
HealthCheck.Kind.READINESS));
+ }
+}
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 1773b1169a6f..3b5a91c094ba 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
@@ -7256,6 +7256,17 @@ other shards of the poll have been read and routed, with
the exception of that s
are added as suppressed exceptions). Before, the poll failed as soon as one
shard failed, with the exception wrapped
by the parallel stream, while the other shards were still being read.
+=== camel-aws2-kinesis - the consumer is not ready before it has listed the
shards
+
+The consumer (without `useKclConsumers`) reads the shards that its shard
monitor lists with `ListShards`. Until that
+listing has succeeded once, the consumer is no longer reported ready, and a
poll fails with an
+`IllegalStateException` whose cause is the error of the last `ListShards` (for
example an `AccessDeniedException`
+without the `kinesis:ListShards` permission, or a `ResourceNotFoundException`
for a stream that does not exist). The
+consumer health check (a readiness check) is then DOWN with that error, and
each poll is reported to the exception
+handler of the consumer (with `bridgeErrorHandler`, to the error handler of
the route), as for other poll failures;
+`backoffErrorThreshold` and `backoffMultiplier` make the consumer poll less
often meanwhile. Before, such a consumer
+read nothing and was reported UP, and only the shard monitor logged a WARN.
+
=== camel-graphql - the credentials are only sent to the authority of httpUri
The `accessToken` (with its `jwtAuthorizationType`) is now added to a request
only when the request goes to the