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 b861a65feca6 CAMEL-27422: camel-core - Aggregate EIP: a discarded
group whose confirm fails is confirmed again by the recover task, and not sent
(#30838)
b861a65feca6 is described below
commit b861a65feca68ad7a3c112ca004732a6d27f553a
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 26 14:41:07 2026 +0530
CAMEL-27422: camel-core - Aggregate EIP: a discarded group whose confirm
fails is confirmed again by the recover task, and not sent (#30838)
With a recoverable aggregation repository, discard()
(discardOnCompletionTimeout,
discardOnAggregationFailure, force discarding) called confirm unguarded.
When it
threw, the completed exchange stayed in the completed store, held by nobody
as
in progress or not confirmed, and the next recover pass recovered the
discarded
group and sent it to the route.
discard() now calls confirmWithResult for a recoverable repository and,
when it
throws or returns false, keeps the exchange as not confirmed, as onComplete
does
since CAMEL-26995 and the dead letter path since CAMEL-27008, so the
recover task
confirms it again. While a recover pass runs, the id is also added to the
snapshot of that pass, as onSubmitCompletion does, since the pass may have
scanned the exchange before the discard. Both happen while the exchange is
still
marked as being completed. A repository that is not recoverable is called as
before.
* CAMEL-27422: camel-core - review follow-up: a longer completion timeout
in the discard test
- AggregateRecoverableDiscardConfirmFailureTest: the completion timeout of
the timeout route is 1000 ms instead of
100 ms, so that A and B are always in one group, also when the two sends
are far apart on a loaded machine (A alone
would time out as its own group, and the counts of the test would be
off). It adds about a second to the two
timeout tests.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../spi/RecoverableAggregationRepository.java | 9 +-
.../processor/aggregate/AggregateProcessor.java | 36 ++-
.../aggregator/AggregateRecoverInProgressTest.java | 19 +-
...regateRecoverableDiscardConfirmFailureTest.java | 328 +++++++++++++++++++++
4 files changed, 378 insertions(+), 14 deletions(-)
diff --git
a/core/camel-api/src/main/java/org/apache/camel/spi/RecoverableAggregationRepository.java
b/core/camel-api/src/main/java/org/apache/camel/spi/RecoverableAggregationRepository.java
index 504307add5ab..77f5f20f9df0 100644
---
a/core/camel-api/src/main/java/org/apache/camel/spi/RecoverableAggregationRepository.java
+++
b/core/camel-api/src/main/java/org/apache/camel/spi/RecoverableAggregationRepository.java
@@ -141,11 +141,12 @@ public interface RecoverableAggregationRepository extends
AggregationRepository
* <p>
* It is not invoked for a group that was completed by its first exchange
(for example with a completion size of 1),
* as such a group was never added to the repository, so there is nothing
to confirm. It is also invoked for a
- * recovered exchange that was moved to the dead letter channel.
+ * recovered exchange that was moved to the dead letter channel, and for
an exchange that was discarded (by
+ * discardOnCompletionTimeout, discardOnAggregationFailure or force
discarding with an AggregateController).
* <p>
- * When it returns false or throws an exception, the exchange (which was
processed, or moved to the dead letter
- * channel) is kept as not confirmed: the recover task does not recover
it, and invokes this method again for it, as
- * long as {@link #scan(CamelContext)} returns its exchange id.
+ * When it returns false or throws an exception, the exchange (which was
processed, moved to the dead letter
+ * channel, or discarded) is kept as not confirmed: the recover task does
not recover it, and invokes this method
+ * again for it, as long as {@link #scan(CamelContext)} returns its
exchange id.
*
* @param camelContext the current CamelContext
* @param exchangeId exchange id to confirm
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
index 478f2339854e..abf6973c8835 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/aggregate/AggregateProcessor.java
@@ -1066,7 +1066,11 @@ public class AggregateProcessor extends
BaseProcessorSupport
// discard due timeout
LOG.debug("Aggregation for correlation key {} discarding aggregated
exchange: {}", key, aggregated);
// must confirm the discarded exchange
- aggregationRepository.confirm(aggregated.getContext(),
aggregated.getExchangeId());
+ if (isRecoverableRepository()) {
+ confirmDiscarded(aggregated);
+ } else {
+ aggregationRepository.confirm(aggregated.getContext(),
aggregated.getExchangeId());
+ }
// and remove redelivery state as well
redeliveryState.remove(aggregated.getExchangeId());
// and release the references that the discarded exchange holds to
spooled stream caches (only those, as the
@@ -1075,6 +1079,36 @@ public class AggregateProcessor extends
BaseProcessorSupport
// the completion was from timeout and we should just discard it
}
+ /**
+ * Confirms a discarded exchange, which a recoverable repository has moved
to its completed store. When the confirm
+ * fails, the exchange is kept as not confirmed, as a processed exchange
(see AggregateOnCompletion), so the recover
+ * task tries to confirm it again instead of recovering it and sending it.
+ */
+ private void confirmDiscarded(Exchange aggregated) {
+ String exchangeId = aggregated.getExchangeId();
+ boolean confirmed;
+ try {
+ confirmed = ((RecoverableAggregationRepository)
aggregationRepository).confirmWithResult(aggregated.getContext(),
+ exchangeId);
+ } catch (VirtualMachineError e) {
+ // left as before: a JVM-level failure is not handled here
+ throw e;
+ } catch (RuntimeException | Error e) {
+ LOG.warn("Error confirming the aggregated exchange with id: {},
which was discarded. It is kept as not"
+ + " confirmed: the recover task will try to confirm it
again, and will not send it.",
+ exchangeId, e);
+ confirmed = false;
+ }
+ if (!confirmed) {
+ // the exchange is still marked as being completed, so a recover
check cannot recover it before this: a
+ // check that has already taken its snapshot must see it as well,
as onSubmitCompletion does
+ unconfirmedCompleteExchanges.add(exchangeId);
+ if (recoveryInProgress.get()) {
+ inProgressCompleteExchangesForRecoveryTask.add(exchangeId);
+ }
+ }
+ }
+
/**
* Takes the references that the group holds to spooled stream caches,
when the group is removed from the
* repository.
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateRecoverInProgressTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateRecoverInProgressTest.java
index 80d33ed3bee1..671e2ff5c3d7 100644
---
a/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateRecoverInProgressTest.java
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateRecoverInProgressTest.java
@@ -45,7 +45,6 @@ import org.junit.jupiter.api.Test;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
@@ -156,9 +155,10 @@ public class AggregateRecoverInProgressTest extends
ContextTestSupport {
}
@Test
- public void testForceDiscardingNotConfirmedIsRecovered() throws Exception {
+ public void testForceDiscardingNotConfirmedIsConfirmedAgain() throws
Exception {
// a force discarded group is not sent, so it must not be left marked
as being completed: if it could not be
- // confirmed, it is still in the completed store, and the recover task
must recover it
+ // confirmed, it is still in the completed store, and the recover task
must confirm it again, without sending
+ // it (as a processed exchange whose confirm failed, CAMEL-26995)
AggregateController controller = new DefaultAggregateController();
context.addRoutes(new RouteBuilder() {
@Override
@@ -171,17 +171,18 @@ public class AggregateRecoverInProgressTest extends
ContextTestSupport {
context.start();
MockEndpoint mock = getMockEndpoint("mock:result");
- mock.expectedBodiesReceived("A");
- mock.expectedHeaderReceived(Exchange.REDELIVERED, true);
+ mock.expectedMessageCount(0);
send("A", "1");
repository.failConfirm.set(true);
- assertThrows(IllegalStateException.class, () ->
controller.forceDiscardingOfGroup("1"));
- assertFalse(repository.completed.isEmpty(), "The discarded exchange
should still be in the completed store");
+ assertEquals(1, controller.forceDiscardingOfGroup("1"));
+ assertFalse(repository.failConfirm.get(), "The confirm of the
discarded exchange should have failed");
- assertMockEndpointsSatisfied();
await().atMost(20,
TimeUnit.SECONDS).until(repository.completed::isEmpty);
- assertEquals(1, repository.recovered.get());
+ int scans = repository.scans.get();
+ await().atMost(20, TimeUnit.SECONDS).until(() ->
repository.scans.get() >= scans + 2);
+ assertEquals(0, repository.recovered.get(), "The discarded exchange
should not be recovered");
+ assertMockEndpointsSatisfied();
}
private void assertNotRecoveredWhilePaused(Thread producer) throws
Exception {
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateRecoverableDiscardConfirmFailureTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateRecoverableDiscardConfirmFailureTest.java
new file mode 100644
index 000000000000..5993b356be89
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/aggregator/AggregateRecoverableDiscardConfirmFailureTest.java
@@ -0,0 +1,328 @@
+/*
+ * 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.aggregator;
+
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.AggregationStrategy;
+import org.apache.camel.CamelContext;
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.processor.BodyInAggregatingStrategy;
+import org.apache.camel.processor.aggregate.AggregateController;
+import org.apache.camel.processor.aggregate.DefaultAggregateController;
+import org.apache.camel.spi.RecoverableAggregationRepository;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.DefaultExchangeHolder;
+import org.apache.camel.support.service.ServiceSupport;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * With a {@link RecoverableAggregationRepository}, a discarded group must
never be sent, also when the repository fails
+ * to confirm it: the recover task confirms it again, and does not recover it.
This is the same as for a processed
+ * exchange (CAMEL-26995) and for an exchange moved to the dead letter channel
(CAMEL-27008).
+ */
+class AggregateRecoverableDiscardConfirmFailureTest extends ContextTestSupport
{
+
+ private final DiscardRepository timeoutRepository = new
DiscardRepository();
+ private final DiscardRepository failureRepository = new
DiscardRepository();
+ private final DiscardRepository forceRepository = new DiscardRepository();
+ private final AggregateController controller = new
DefaultAggregateController();
+
+ @Test
+ void testDiscardOnCompletionTimeoutConfirmThrows() throws Exception {
+ timeoutRepository.throwOnConfirm(false);
+
+ send("direct:timeout", "A", "B");
+
+ assertDiscardedOnce(timeoutRepository);
+ }
+
+ @Test
+ void testDiscardOnCompletionTimeoutConfirmThrowsDuringRecoverCheck()
throws Exception {
+ // the confirm fails after the recover task has scanned the completed
exchange: the check that is running must
+ // not recover it either
+ timeoutRepository.throwOnConfirm(true);
+
+ send("direct:timeout", "A", "B");
+
+ assertDiscardedOnce(timeoutRepository);
+ assertTrue(timeoutRepository.scannedBeforeThrow, "The recover task
should scan A+B before its confirm fails");
+ }
+
+ @Test
+ void testDiscardOnAggregationFailureConfirmThrows() throws Exception {
+ failureRepository.throwOnConfirm(false);
+
+ Exchange out = send("direct:failure", "A", "B", "Kaboom");
+
+ assertDiscardedOnce(failureRepository);
+ assertNull(out.getException(), "The exchange that discarded the group
should not fail");
+ }
+
+ @Test
+ void testDiscardOnAggregationFailureConfirmThrowsDuringRecoverCheck()
throws Exception {
+ failureRepository.throwOnConfirm(true);
+
+ Exchange out = send("direct:failure", "A", "B", "Kaboom");
+
+ assertDiscardedOnce(failureRepository);
+ assertTrue(failureRepository.scannedBeforeThrow, "The recover task
should scan A+B before its confirm fails");
+ assertNull(out.getException(), "The exchange that discarded the group
should not fail");
+ }
+
+ @Test
+ void testForceDiscardingConfirmThrows() throws Exception {
+ forceRepository.throwOnConfirm(false);
+
+ send("direct:force", "A", "B");
+ assertEquals(1, controller.forceDiscardingOfGroup("1"));
+
+ assertDiscardedOnce(forceRepository);
+ }
+
+ /**
+ * Sends the bodies to the endpoint, with the same correlation key, and
returns the last exchange.
+ */
+ private Exchange send(String uri, String... bodies) {
+ Exchange out = null;
+ for (String body : bodies) {
+ out = template.send(uri, exchange -> {
+ exchange.getMessage().setBody(body);
+ exchange.getMessage().setHeader("id", 1);
+ });
+ }
+ return out;
+ }
+
+ private void assertDiscardedOnce(DiscardRepository repository) {
+ // the recover task confirms A+B again
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
repository.completedBodies().isEmpty());
+ // let the recover task run completely at least once more (a pass is
complete when the next scan starts)
+ int scans = repository.scans.get();
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
repository.scans.get() >= scans + 2);
+
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ assertEquals(List.of(), mock.getReceivedExchanges().stream().map(e ->
e.getMessage().getBody(String.class)).toList(),
+ "The discarded group should not be sent");
+ assertEquals(0, repository.recovered.get(), "The discarded group
should not be recovered");
+ assertEquals(2, repository.confirms.get(), "A+B should be confirmed
twice");
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ // the timeout is long enough for A and B to be in one group
also on a loaded machine
+ from("direct:timeout")
+ .aggregate(header("id"), new
BodyInAggregatingStrategy()).aggregationRepository(timeoutRepository)
+
.completionSize(3).completionTimeout(1000).completionTimeoutCheckerInterval(10)
+ .discardOnCompletionTimeout()
+ .to("mock:result");
+
+ from("direct:failure")
+ .aggregate(header("id"), new
KaboomAggregationStrategy()).aggregationRepository(failureRepository)
+ .completionSize(3).discardOnAggregationFailure()
+ .to("mock:result");
+
+ from("direct:force")
+ .aggregate(header("id"), new
BodyInAggregatingStrategy()).aggregationRepository(forceRepository)
+ .completionSize(3).aggregateController(controller)
+ .to("mock:result");
+ }
+ };
+ }
+
+ private static final class KaboomAggregationStrategy implements
AggregationStrategy {
+ private final AggregationStrategy delegate = new
BodyInAggregatingStrategy();
+
+ @Override
+ public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
+ if
("Kaboom".equals(newExchange.getMessage().getBody(String.class))) {
+ throw new IllegalArgumentException("Simulated failure: cannot
aggregate Kaboom");
+ }
+ return delegate.aggregate(oldExchange, newExchange);
+ }
+ }
+
+ /**
+ * An in-memory recoverable repository which, like
JdbcAggregationRepository, moves the exchange of a completed
+ * group to a completed store, and deletes it from there when it is
confirmed. Its first confirm throws, optionally
+ * after a recover check has scanned the completed exchange (the check
then waits for the lock that the discard
+ * holds).
+ */
+ private static final class DiscardRepository extends ServiceSupport
implements RecoverableAggregationRepository {
+
+ private final Map<String, DefaultExchangeHolder> groups = new
HashMap<>();
+ private final Map<String, Completed> completed = new LinkedHashMap<>();
+ private final AtomicInteger throwingConfirms = new AtomicInteger();
+ private final AtomicInteger confirms = new AtomicInteger();
+ private final AtomicInteger scans = new AtomicInteger();
+ private final AtomicInteger recovered = new AtomicInteger();
+ private final CountDownLatch scanned = new CountDownLatch(1);
+ private volatile boolean throwAfterScan;
+ private volatile boolean scannedBeforeThrow;
+
+ void throwOnConfirm(boolean afterScan) {
+ throwingConfirms.set(1);
+ throwAfterScan = afterScan;
+ }
+
+ synchronized List<String> completedBodies() {
+ return completed.values().stream().map(Completed::body).toList();
+ }
+
+ @Override
+ public synchronized Exchange add(CamelContext camelContext, String
key, Exchange exchange) {
+ Exchange old = get(camelContext, key);
+ groups.put(key, DefaultExchangeHolder.marshal(exchange, true));
+ return old;
+ }
+
+ @Override
+ public synchronized Exchange get(CamelContext camelContext, String
key) {
+ DefaultExchangeHolder holder = groups.get(key);
+ return holder != null ? unmarshal(camelContext, holder) : null;
+ }
+
+ @Override
+ public synchronized void remove(CamelContext camelContext, String key,
Exchange exchange) {
+ groups.remove(key);
+ completed.put(exchange.getExchangeId(),
+ new Completed(DefaultExchangeHolder.marshal(exchange,
true), exchange.getIn().getBody(String.class)));
+ }
+
+ @Override
+ public void confirm(CamelContext camelContext, String exchangeId) {
+ confirmWithResult(camelContext, exchangeId);
+ }
+
+ @Override
+ public boolean confirmWithResult(CamelContext camelContext, String
exchangeId) {
+ synchronized (this) {
+ Completed entry = completed.get(exchangeId);
+ if (entry == null) {
+ return false;
+ }
+ confirms.incrementAndGet();
+ if (throwingConfirms.getAndUpdate(n -> n > 0 ? n - 1 : 0) ==
0) {
+ completed.remove(exchangeId);
+ return true;
+ }
+ }
+ // outside the lock of the repository, so the recover task can scan
+ if (throwAfterScan) {
+ try {
+ scannedBeforeThrow = scanned.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ // as JdbcAggregationRepository when its DELETE fails (the
database is not available)
+ throw new IllegalStateException("Simulated failure: the repository
cannot confirm " + exchangeId);
+ }
+
+ @Override
+ public synchronized Set<String> getKeys() {
+ return Set.copyOf(groups.keySet());
+ }
+
+ @Override
+ public synchronized Set<String> scan(CamelContext camelContext) {
+ scans.incrementAndGet();
+ if (!completed.isEmpty()) {
+ scanned.countDown();
+ }
+ return new LinkedHashSet<>(completed.keySet());
+ }
+
+ @Override
+ public synchronized Exchange recover(CamelContext camelContext, String
exchangeId) {
+ Completed entry = completed.get(exchangeId);
+ if (entry == null) {
+ return null;
+ }
+ recovered.incrementAndGet();
+ return unmarshal(camelContext, entry.holder());
+ }
+
+ private record Completed(DefaultExchangeHolder holder, String body) {
+ }
+
+ private static Exchange unmarshal(CamelContext camelContext,
DefaultExchangeHolder holder) {
+ Exchange answer = new DefaultExchange(camelContext);
+ DefaultExchangeHolder.unmarshal(answer, holder);
+ return answer;
+ }
+
+ @Override
+ public void setRecoveryInterval(long interval, TimeUnit timeUnit) {
+ }
+
+ @Override
+ public void setRecoveryInterval(long interval) {
+ }
+
+ @Override
+ public long getRecoveryInterval() {
+ return 100;
+ }
+
+ @Override
+ public void setUseRecovery(boolean useRecovery) {
+ }
+
+ @Override
+ public boolean isUseRecovery() {
+ return true;
+ }
+
+ @Override
+ public void setDeadLetterUri(String deadLetterUri) {
+ }
+
+ @Override
+ public String getDeadLetterUri() {
+ return "mock:dead";
+ }
+
+ @Override
+ public void setMaximumRedeliveries(int maximumRedeliveries) {
+ }
+
+ @Override
+ public int getMaximumRedeliveries() {
+ return 2;
+ }
+ }
+}