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 275cb3759bc0 CAMEL-27349: camel-core - Idempotent Consumer: process an
exchange that a calling route redelivers (#30631)
275cb3759bc0 is described below
commit 275cb3759bc0ff5d7946489877ebd75b5d141aa3
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 23 14:02:07 2026 +0530
CAMEL-27349: camel-core - Idempotent Consumer: process an exchange that a
calling route redelivers (#30631)
When the error handler of a calling route redelivered an exchange that
failed inside the idempotent consumer (a sub route with noErrorHandler
called by to("direct:sub"), or an exception that escapes a doTry block of
the called route), the exchange entered the idempotent consumer again
while the message id it had added was still in the repository, as
completionEager=false removes it only when the exchange is done. The
exchange was taken for a duplicate of itself: the message was skipped,
the redelivery counted as successful (the message never reached a dead
letter channel), and the message id was kept. A doCatch of the calling
route that sent the failed exchange to the sub route again hit the same
duplicate.
An exchange that added the message id and fails in the idempotent
consumer is now marked as the owner of it while its on completion is
still pending. When the same exchange comes back, it is processed again
under that on completion. Other exchanges with the same id stay
duplicates, an exchange that failed after the idempotent consumer is not
processed again by it, and removeOnFailure=false keeps the current
behaviour.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../camel/catalog/docs/idempotentConsumer-eip.adoc | 9 +
.../modules/eips/pages/idempotentConsumer-eip.adoc | 9 +
.../processor/idempotent/IdempotentConsumer.java | 85 ++++++-
.../IdempotentConsumerRedeliveryTest.java | 265 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 13 +
5 files changed, 378 insertions(+), 3 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/idempotentConsumer-eip.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/idempotentConsumer-eip.adoc
index da7c8cb5f4ed..43b1cf04ef33 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/idempotentConsumer-eip.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/idempotentConsumer-eip.adoc
@@ -21,6 +21,15 @@ An Exchange marked with `markRollbackOnly()` or
`markRollbackOnlyLast()` counts
failed too, even without an exception. Set `removeOnFailure=false` to keep the
message id
of a failed Exchange.
+The message id of a failed Exchange is removed when the Exchange is done
(unless `completionEager` is
+`true`). If the error handler of a calling route redelivers an Exchange that
failed inside the idempotent
+consumer, the redelivered Exchange is processed again: it is not a duplicate
of itself. This happens when
+a route calls a sub route with `to("direct:sub")` and the sub route uses
`noErrorHandler` (to retry the
+entire sub route), or when the exception escapes a `doTry` block of the sub
route. The same holds when a
+`doCatch` of the calling route sends the failed Exchange to the sub route
again. An Exchange that failed
+after the idempotent consumer does not run the idempotent consumer again on
the redelivery, and with
+`removeOnFailure=false` the redelivery is a duplicate.
+
== Options
// eip options: START
diff --git
a/core/camel-core-engine/src/main/docs/modules/eips/pages/idempotentConsumer-eip.adoc
b/core/camel-core-engine/src/main/docs/modules/eips/pages/idempotentConsumer-eip.adoc
index da7c8cb5f4ed..43b1cf04ef33 100644
---
a/core/camel-core-engine/src/main/docs/modules/eips/pages/idempotentConsumer-eip.adoc
+++
b/core/camel-core-engine/src/main/docs/modules/eips/pages/idempotentConsumer-eip.adoc
@@ -21,6 +21,15 @@ An Exchange marked with `markRollbackOnly()` or
`markRollbackOnlyLast()` counts
failed too, even without an exception. Set `removeOnFailure=false` to keep the
message id
of a failed Exchange.
+The message id of a failed Exchange is removed when the Exchange is done
(unless `completionEager` is
+`true`). If the error handler of a calling route redelivers an Exchange that
failed inside the idempotent
+consumer, the redelivered Exchange is processed again: it is not a duplicate
of itself. This happens when
+a route calls a sub route with `to("direct:sub")` and the sub route uses
`noErrorHandler` (to retry the
+entire sub route), or when the exception escapes a `doTry` block of the sub
route. The same holds when a
+`doCatch` of the calling route sends the failed Exchange to the sub route
again. An Exchange that failed
+after the idempotent consumer does not run the idempotent consumer again on
the redelivery, and with
+`removeOnFailure=false` the redelivery is a duplicate.
+
== Options
// eip options: START
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java
index 52f1cf5d87eb..aefe4b24a38f 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/idempotent/IdempotentConsumer.java
@@ -52,6 +52,7 @@ public class IdempotentConsumer extends BaseProcessorSupport
implements CamelContextAware, Navigate<Processor>, IdAware,
RouteIdAware, StepIdAware {
private static final Logger LOG =
LoggerFactory.getLogger(IdempotentConsumer.class);
+ private static final AtomicLong KEY_OWNER_IDS = new AtomicLong();
private CamelContext camelContext;
private String id;
@@ -65,6 +66,9 @@ public class IdempotentConsumer extends BaseProcessorSupport
private final boolean skipDuplicate;
private final boolean removeOnFailure;
private final AtomicLong duplicateMessageCount = new AtomicLong();
+ // the exchange property that marks an exchange whose processing failed in
this idempotent consumer, while the
+ // message id it added is still in the repository (one property per
idempotent consumer)
+ private final String keyOwnerProperty = "CamelIdempotentConsumerKeyOwner-"
+ KEY_OWNER_IDS.incrementAndGet();
public IdempotentConsumer(Expression messageIdExpression,
IdempotentRepository idempotentRepository,
boolean eager, boolean completionEager, boolean
skipDuplicate, boolean removeOnFailure,
@@ -149,7 +153,14 @@ public class IdempotentConsumer extends
BaseProcessorSupport
newKey = !idempotentRepository.contains(exchange, messageId);
}
- if (!newKey) {
+ final KeyOwner owner = !newKey && eager ? ownedKey(exchange,
messageId) : null;
+ if (owner != null) {
+ // this exchange added the key and failed in this idempotent
consumer, and is routed through it again
+ // (the error handler of a calling route redelivers it) before
its completion removes the key: it is
+ // not a duplicate of itself, so process it again under the
completion it registered the first time
+ LOG.debug("Processing again redelivered message with id: {}
for exchange: {}", messageId, exchange);
+ target = new KeyOwnerCallback(exchange, owner,
keyOwnerProperty, callback);
+ } else if (!newKey) {
// mark the exchange as duplicate
exchange.setProperty(ExchangePropertyKey.DUPLICATE_MESSAGE,
Boolean.TRUE);
@@ -174,11 +185,18 @@ public class IdempotentConsumer extends
BaseProcessorSupport
// the callback will eager complete
target = new IdempotentConsumerCallback(exchange,
onCompletion, callback);
} else {
- // we can use existing callback as target
- target = callback;
// the scope is to do the idempotent completion work as an
unit of work on the exchange
// when its done being routed
exchange.getExchangeExtension().addOnCompletion(onCompletion);
+ if (eager && removeOnFailure) {
+ // remember when the exchange fails in this idempotent
consumer, so a redelivery of the
+ // exchange is not taken for a duplicate (the key is
removed only when the exchange is done)
+ target = new KeyOwnerCallback(
+ exchange, new KeyOwner(exchange, messageId,
onCompletion), keyOwnerProperty, callback);
+ } else {
+ // we can use existing callback as target
+ target = callback;
+ }
}
}
} catch (Exception e) {
@@ -279,6 +297,22 @@ public class IdempotentConsumer extends
BaseProcessorSupport
onDuplicateMessage(exchange, messageId);
}
+ /**
+ * The key owner of this idempotent consumer on the exchange, if the
exchange added this message id, failed in this
+ * idempotent consumer, and the completion that removes the key is still
pending on the exchange.
+ */
+ private KeyOwner ownedKey(Exchange exchange, String messageId) {
+ if (!removeOnFailure || completionEager) {
+ return null;
+ }
+ KeyOwner owner = exchange.getProperty(keyOwnerProperty,
KeyOwner.class);
+ if (owner != null && owner.exchange() == exchange &&
owner.messageId().equals(messageId)
+ &&
exchange.getExchangeExtension().containsOnCompletion(owner.onCompletion())) {
+ return owner;
+ }
+ return null;
+ }
+
/**
* Clear the idempotent repository
*/
@@ -296,6 +330,51 @@ public class IdempotentConsumer extends
BaseProcessorSupport
// noop
}
+ /**
+ * The message id that an exchange added to the repository, with the
completion that confirms or removes it when the
+ * exchange is done.
+ */
+ private record KeyOwner(Exchange exchange, String messageId,
Synchronization onCompletion) {
+ @Override
+ public String toString() {
+ return "IdempotentConsumerKeyOwner[" + messageId + "]";
+ }
+ }
+
+ /**
+ * {@link org.apache.camel.AsyncCallback} that marks the exchange as the
owner of its key when the exchange fails in
+ * the idempotent consumer block (the exception leaves the block, so an
error handler of a calling route may
+ * redeliver it), and removes the mark when the block succeeds.
+ */
+ private static final class KeyOwnerCallback implements AsyncCallback {
+ private final Exchange exchange;
+ private final KeyOwner owner;
+ private final String property;
+ private final AsyncCallback callback;
+
+ KeyOwnerCallback(Exchange exchange, KeyOwner owner, String property,
AsyncCallback callback) {
+ this.exchange = exchange;
+ this.owner = owner;
+ this.property = property;
+ this.callback = callback;
+ }
+
+ @Override
+ public void done(boolean doneSync) {
+ if (exchange.isFailed()) {
+ exchange.setProperty(property, owner);
+ } else {
+ exchange.removeProperty(property);
+ }
+ callback.done(doneSync);
+ }
+
+ @Override
+ public String toString() {
+ return "IdempotentConsumerKeyOwnerCallback";
+ }
+ }
+
/**
* {@link org.apache.camel.AsyncCallback} that is invoked when the
idempotent consumer block ends
*/
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerRedeliveryTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerRedeliveryTest.java
new file mode 100644
index 000000000000..63c735b3a544
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/IdempotentConsumerRedeliveryTest.java
@@ -0,0 +1,265 @@
+/*
+ * 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.processor;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.spi.IdempotentRepository;
+import org.apache.camel.support.KeyValueIdempotentRepository;
+import org.junit.jupiter.api.Test;
+
+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;
+
+/**
+ * The error handler of a calling route redelivers an exchange that failed
inside the idempotent consumer of a sub route
+ * without an error handler. The redelivered exchange enters the idempotent
consumer again, while the message id it
+ * added on the first attempt is still in the repository
(completionEager=false removes it when the exchange is done).
+ * It must not be dropped as a duplicate of itself: the message would never be
processed, the exchange would complete
+ * successfully, and the message id would stay in the repository.
+ */
+class IdempotentConsumerRedeliveryTest extends ContextTestSupport {
+
+ private final IdempotentRepository repository = new
KeyValueIdempotentRepository();
+ private final AtomicInteger attempts = new AtomicInteger();
+ private final AtomicInteger failures = new AtomicInteger();
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+
errorHandler(deadLetterChannel("mock:dead").maximumRedeliveries(2).redeliveryDelay(0));
+
+ from("direct:start").to("direct:sub");
+ from("direct:sub").errorHandler(noErrorHandler())
+ .idempotentConsumer(header("messageId"), repository)
+ .process(e -> failFirstAttempts())
+ .to("mock:result")
+ .end()
+ .to("mock:after");
+
+ // the called route keeps its error handler, but an exception
that escapes its doTry block is dealt with
+ // by the error handler of the calling route, whose redelivery
calls the whole route again
+ from("direct:doTry").to("direct:subDoTry");
+ from("direct:subDoTry")
+ .doTry()
+ .idempotentConsumer(header("messageId"),
repository)
+ .process(e -> failFirstAttempts())
+ .to("mock:result")
+ .end()
+ .endDoTry()
+ .doCatch(IllegalArgumentException.class)
+ .to("mock:caught")
+ .end();
+
+ // a doCatch of the calling route sends the failed exchange to
the sub route again
+ from("direct:catchAndRetry").errorHandler(noErrorHandler())
+ .doTry()
+ .to("direct:sub")
+ .doCatch(IllegalStateException.class)
+ .to("direct:sub")
+ .end();
+
+ from("direct:failAfter").to("direct:subFailAfter");
+ from("direct:subFailAfter").errorHandler(noErrorHandler())
+ .idempotentConsumer(header("messageId"), repository)
+ .to("mock:result")
+ .end()
+ .process(e -> failFirstAttempts())
+ .to("mock:after");
+
+ from("direct:routedDuplicate").to("direct:subRoutedDuplicate");
+
from("direct:subRoutedDuplicate").errorHandler(noErrorHandler())
+ .idempotentConsumer(header("messageId"),
repository).skipDuplicate(false)
+ .choice()
+
.when(exchangeProperty(Exchange.DUPLICATE_MESSAGE).isEqualTo(true))
+ .to("mock:duplicate")
+ .otherwise()
+ .process(e -> failFirstAttempts())
+ .to("mock:result")
+ .end()
+ .end();
+
+ from("direct:keepOnFailure").to("direct:subKeepOnFailure");
+ from("direct:subKeepOnFailure").errorHandler(noErrorHandler())
+ .idempotentConsumer(header("messageId"),
repository).removeOnFailure(false)
+ .process(e -> failFirstAttempts())
+ .to("mock:result")
+ .end();
+
+ from("direct:completionEager").to("direct:subCompletionEager");
+
from("direct:subCompletionEager").errorHandler(noErrorHandler())
+ .idempotentConsumer(header("messageId"),
repository).completionEager(true)
+ .process(e -> failFirstAttempts())
+ .to("mock:result")
+ .end();
+
+ // another exchange with the same message id arrives while the
first one waits for its redelivery
+
from("direct:other").errorHandler(deadLetterChannel("mock:dead").maximumRedeliveries(1).redeliveryDelay(0)
+ .onRedelivery(e -> template.send("direct:sub", o -> {
+ o.getIn().setBody("other");
+ o.getIn().setHeader("messageId", "1");
+ })))
+ .to("direct:sub");
+ }
+ };
+ }
+
+ private void failFirstAttempts() {
+ attempts.incrementAndGet();
+ if (failures.getAndDecrement() > 0) {
+ throw new IllegalStateException("Forced failure");
+ }
+ }
+
+ @Test
+ void testRedeliveredExchangeIsProcessed() throws Exception {
+ failures.set(1);
+ getMockEndpoint("mock:result").expectedBodiesReceived("one");
+ getMockEndpoint("mock:after").expectedBodiesReceived("one");
+ getMockEndpoint("mock:dead").expectedMessageCount(0);
+
+ Exchange out = send("direct:start");
+
+ assertMockEndpointsSatisfied();
+ assertNull(out.getException());
+ assertEquals(2, attempts.get(), "The redelivered exchange should run
the idempotent consumer block again");
+ assertTrue(repository.contains("1"));
+ }
+
+ @Test
+ void testExhaustedRedeliveriesRemoveMessageId() throws Exception {
+ failures.set(3);
+ getMockEndpoint("mock:result").expectedMessageCount(0);
+ getMockEndpoint("mock:dead").expectedBodiesReceived("one");
+
+ send("direct:start");
+
+ assertMockEndpointsSatisfied();
+ assertEquals(3, attempts.get(), "Every redelivery should run the
idempotent consumer block again");
+ assertFalse(repository.contains("1"), "The message id of a failed
exchange should be removed");
+ }
+
+ @Test
+ void testExceptionEscapingDoTryOfCalledRoute() throws Exception {
+ failures.set(1);
+ getMockEndpoint("mock:result").expectedBodiesReceived("one");
+ getMockEndpoint("mock:caught").expectedMessageCount(0);
+ getMockEndpoint("mock:dead").expectedMessageCount(0);
+
+ Exchange out = send("direct:doTry");
+
+ assertMockEndpointsSatisfied();
+ assertNull(out.getException());
+ assertEquals(2, attempts.get(), "The redelivered exchange should run
the idempotent consumer block again");
+ assertTrue(repository.contains("1"));
+ }
+
+ @Test
+ void testDoCatchOfCallingRouteSendsExchangeAgain() throws Exception {
+ failures.set(1);
+ getMockEndpoint("mock:result").expectedBodiesReceived("one");
+ getMockEndpoint("mock:dead").expectedMessageCount(0);
+
+ Exchange out = send("direct:catchAndRetry");
+
+ assertMockEndpointsSatisfied();
+ assertNull(out.getException());
+ assertEquals(2, attempts.get(), "The exchange sent again should run
the idempotent consumer block again");
+ assertTrue(repository.contains("1"));
+ }
+
+ @Test
+ void testRedeliveryAfterTheBlockDoesNotProcessAgain() throws Exception {
+ // the block succeeded, a step after it failed: the redelivery skips
the block, as the message was processed
+ failures.set(1);
+ getMockEndpoint("mock:result").expectedBodiesReceived("one");
+ getMockEndpoint("mock:after").expectedBodiesReceived("one");
+ getMockEndpoint("mock:dead").expectedMessageCount(0);
+
+ Exchange out = send("direct:failAfter");
+
+ assertMockEndpointsSatisfied();
+ assertNull(out.getException());
+ assertTrue(repository.contains("1"));
+ }
+
+ @Test
+ void testRedeliveredExchangeIsNotRoutedAsDuplicate() throws Exception {
+ failures.set(1);
+ getMockEndpoint("mock:result").expectedBodiesReceived("one");
+ getMockEndpoint("mock:duplicate").expectedMessageCount(0);
+
+ Exchange out = send("direct:routedDuplicate");
+
+ assertMockEndpointsSatisfied();
+ assertNull(out.getException());
+ assertTrue(repository.contains("1"));
+ }
+
+ @Test
+ void testOtherExchangeIsStillDuplicateWhileFirstIsRedelivered() throws
Exception {
+ failures.set(1);
+ getMockEndpoint("mock:result").expectedBodiesReceived("one");
+
+ Exchange out = send("direct:other");
+
+ assertMockEndpointsSatisfied();
+ assertNull(out.getException());
+ assertEquals(2, attempts.get(), "Only the first exchange should run
the block, twice");
+ assertTrue(repository.contains("1"));
+ }
+
+ @Test
+ void testRedeliveryKeepsMessageIdWhenNotRemovedOnFailure() throws
Exception {
+ // removeOnFailure=false keeps the message id of a failed attempt, so
the redelivery is a duplicate, as before
+ failures.set(1);
+ getMockEndpoint("mock:result").expectedMessageCount(0);
+
+ send("direct:keepOnFailure");
+
+ assertMockEndpointsSatisfied();
+ assertEquals(1, attempts.get());
+ assertTrue(repository.contains("1"));
+ }
+
+ @Test
+ void testRedeliveryCompletionEager() throws Exception {
+ // completionEager=true removes the message id when the block fails,
so the redelivery is processed
+ failures.set(1);
+ getMockEndpoint("mock:result").expectedBodiesReceived("one");
+
+ send("direct:completionEager");
+
+ assertMockEndpointsSatisfied();
+ assertEquals(2, attempts.get());
+ assertTrue(repository.contains("1"));
+ }
+
+ private Exchange send(String uri) {
+ return template.send(uri, exchange -> {
+ exchange.getIn().setBody("one");
+ exchange.getIn().setHeader("messageId", "1");
+ });
+ }
+}
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 e9ee33664122..22f86b24e6f1 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
@@ -199,6 +199,19 @@ Starting in 4.24:
* The Cache EIP stores keys directly without a namespace prefix, preserving
documented cache invalidation recipes (`cache.delete(key)` and
`cache.clear()`). Note that because cache keys are un-prefixed, calling
`clear()` on a `KeyValueRepository` shared with the Cache EIP will clear all
entries in that repository, including state-store entries. It is recommended to
use a dedicated repository for the Cache EIP when co-located with state-store.
* `KeyValueAggregationRepository` safely verifies entry types before
unmarshalling, ignoring unexpected types gracefully instead of failing with a
class cast exception.
+=== camel-core - Idempotent Consumer processes an exchange that a calling
route redelivers
+
+When the error handler of a calling route redelivers an exchange that failed
inside an Idempotent Consumer (for
+example `to("direct:sub")` where the sub route uses `noErrorHandler`, or an
exception that escapes a `doTry` block of
+the sub route), the Idempotent Consumer took the redelivered exchange for a
duplicate of itself, as the message id it
+had added was still in the repository: the message was skipped (or routed on
with `CamelDuplicateMessage=true` when
+`skipDuplicate=false`), the exchange completed without an error, never reached
a dead letter channel, and the message
+id stayed in the repository. The redelivered exchange is now processed again.
The same applies when a `doCatch` of the
+calling route sends the failed exchange to the sub route again. This applies
with `eager=true`, `removeOnFailure=true`
+and `completionEager=false` (the defaults); with `completionEager=true` the
message id was already removed when the
+exchange failed. An exchange that failed after the Idempotent Consumer still
does not run the Idempotent Consumer
+again, and with `removeOnFailure=false` the redelivery is still a duplicate.
+
=== camel-core - throwException with an exception instance gets no suppressed
exceptions
A `throwException` step given an exception instance (`throwException(new
MyException("..."))` in Java, or a bean with