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 fc900075cd45 CAMEL-27331: camel-core - Resequence EIP: batch mode
keeps the exchanges waiting for the batch over a route restart (#30573)
fc900075cd45 is described below
commit fc900075cd45d277ee8e0cc1407d0b3e2f9a343d
Author: allthingssecurity <[email protected]>
AuthorDate: Sun Nov 22 19:09:15 2026 +0530
CAMEL-27331: camel-core - Resequence EIP: batch mode keeps the exchanges
waiting for the batch over a route restart (#30573)
The batch resequencer completes an exchange when it queues it. The queue was
a field of the BatchSender thread, and each start creates a new sender, so
the exchanges still waiting for the current batch were lost when the route
was stopped and started. The queue, its lock and flags are now fields of the
processor, shared by the senders like the sorted collection, so the sender
of
the next start delivers them. A stopped processor rejects new exchanges
with a
RejectedExecutionException instead of failing with a NullPointerException.
Found with a TLA+ model.
Since CAMEL-25502 an exchange cut off by a route or context stop fails with
RouteStoppingException, as in the stream resequencer, the Throttle and the
Delay EIPs. The batch resequencer now does the same. RouteStoppingException
extends RejectedExecutionException, so existing handlers still match.
The tests use a 5 second batch timeout and wait up to 20 seconds for the
batch, so the sends and restarts of a test fit in one batch on a slow CI
agent, and a new test checks the exception.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../org/apache/camel/processor/Resequencer.java | 70 ++++++------
.../BatchResequencerRestartKeepsQueueTest.java | 120 +++++++++++++++++++++
2 files changed, 159 insertions(+), 31 deletions(-)
diff --git
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/Resequencer.java
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/Resequencer.java
index 14f0540baed9..e042633b6e7f 100644
---
a/core/camel-core-processor/src/main/java/org/apache/camel/processor/Resequencer.java
+++
b/core/camel-core-processor/src/main/java/org/apache/camel/processor/Resequencer.java
@@ -42,6 +42,7 @@ import org.apache.camel.Expression;
import org.apache.camel.Navigate;
import org.apache.camel.Predicate;
import org.apache.camel.Processor;
+import org.apache.camel.RouteStoppingException;
import org.apache.camel.Traceable;
import org.apache.camel.spi.ExceptionHandler;
import org.apache.camel.spi.IdAware;
@@ -90,6 +91,13 @@ public class Resequencer extends BaseProcessorSupport
private BatchSender sender;
// the sender of the last start, which may still be delivering an exchange
when the route is started again
private BatchSender stoppedSender;
+ // the exchanges waiting for the current batch to complete; like the
collection, they are kept when the route is
+ // stopped, so the sender of the next start delivers them (the callers
were already told that they succeeded)
+ private final Queue<Exchange> queue = new LinkedList<>();
+ private final Lock queueLock = new ReentrantLock();
+ private final Condition exchangeEnqueuedCondition =
queueLock.newCondition();
+ private final AtomicBoolean exchangeEnqueued = new AtomicBoolean();
+ private final Queue<String> completionPredicateMatched = new
ConcurrentLinkedQueue<>();
public Resequencer(CamelContext camelContext, Processor processor,
Expression expression) {
this(camelContext, processor, createSet(expression, false, false),
expression);
@@ -389,7 +397,10 @@ public class Resequencer extends BaseProcessorSupport
}
// validate that the exchange can be used
- if (!isValid(exchange)) {
+ if (!isRunAllowed()) {
+ // no sender would deliver the exchange unless the route is
started again
+ throw new RouteStoppingException("Resequencer is stopped: " +
this);
+ } else if (!isValid(exchange)) {
if (isIgnoreInvalidExchanges()) {
LOG.debug("Invalid Exchange. This Exchange will be
ignored: {}", exchange);
} else {
@@ -397,7 +408,7 @@ public class Resequencer extends BaseProcessorSupport
}
} else {
// exchange is valid so enqueue the exchange
- sender.enqueueExchange(exchange);
+ enqueueExchange(exchange);
}
} catch (Exception e) {
exchange.setException(e);
@@ -422,22 +433,42 @@ public class Resequencer extends BaseProcessorSupport
return result != null;
}
+ /**
+ * Queues a copy of the exchange for the current batch. The queue is
shared by the senders of all starts.
+ */
+ private void enqueueExchange(Exchange exchange) {
+ LOG.debug("Received exchange to be batched: {}", exchange);
+ queueLock.lock();
+ try {
+ // pre test whether the completion predicate matched
+ if (completionPredicate != null) {
+ boolean matches = completionPredicate.matches(exchange);
+ if (matches) {
+ LOG.trace("Exchange matched completion predicate: {}",
exchange);
+ // add this exchange to the list of exchanges which marks
the batch as complete
+ completionPredicateMatched.add(exchange.getExchangeId());
+ }
+ }
+ // need to make defensive copy that are put on the sequencer queue
+ Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange,
true);
+ queue.add(copy);
+ exchangeEnqueued.set(true);
+ exchangeEnqueuedCondition.signal();
+ } finally {
+ queueLock.unlock();
+ }
+ }
+
/**
* Sender thread for queued-up exchanges.
*/
private class BatchSender extends Thread {
- private final Queue<Exchange> queue;
- private final Lock queueLock = new ReentrantLock();
- private final AtomicBoolean exchangeEnqueued = new AtomicBoolean();
- private final Queue<String> completionPredicateMatched = new
ConcurrentLinkedQueue<>();
- private final Condition exchangeEnqueuedCondition =
queueLock.newCondition();
private volatile boolean cancelled;
private BatchSender previous;
BatchSender(BatchSender previous) {
super(camelContext.getExecutorServiceManager().resolveThreadName("Batch
Sender"));
- this.queue = new LinkedList<>();
this.previous = previous;
}
@@ -587,29 +618,6 @@ public class Resequencer extends BaseProcessorSupport
interrupt();
}
- public void enqueueExchange(Exchange exchange) {
- LOG.debug("Received exchange to be batched: {}", exchange);
- queueLock.lock();
- try {
- // pre test whether the completion predicate matched
- if (completionPredicate != null) {
- boolean matches = completionPredicate.matches(exchange);
- if (matches) {
- LOG.trace("Exchange matched completion predicate: {}",
exchange);
- // add this exchange to the list of exchanges which
marks the batch as complete
-
completionPredicateMatched.add(exchange.getExchangeId());
- }
- }
- // need to make defensive copy that are put on the sequencer
queue
- Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange,
true);
- queue.add(copy);
- exchangeEnqueued.set(true);
- exchangeEnqueuedCondition.signal();
- } finally {
- queueLock.unlock();
- }
- }
-
private void sendExchanges() {
Iterator<Exchange> iter = collection.iterator();
while (iter.hasNext()) {
diff --git
a/core/camel-core/src/test/java/org/apache/camel/processor/BatchResequencerRestartKeepsQueueTest.java
b/core/camel-core/src/test/java/org/apache/camel/processor/BatchResequencerRestartKeepsQueueTest.java
new file mode 100644
index 000000000000..f5494107078c
--- /dev/null
+++
b/core/camel-core/src/test/java/org/apache/camel/processor/BatchResequencerRestartKeepsQueueTest.java
@@ -0,0 +1,120 @@
+/*
+ * 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.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.Exchange;
+import org.apache.camel.RouteStoppingException;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.builder.ExpressionBuilder;
+import org.apache.camel.support.service.ServiceHelper;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The batch resequencer completes an exchange as soon as it is queued for the
current batch. The exchanges still
+ * waiting for the batch to complete (size or timeout) must be delivered after
the route is stopped and started again,
+ * as the exchanges of a batch being delivered are
(BatchResequencerRestartTest).
+ */
+class BatchResequencerRestartKeepsQueueTest extends ContextTestSupport {
+
+ @Test
+ void testQueuedExchangesAreDeliveredAfterRestart() throws Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("1", "2");
+
+ // both are accepted, and the batch (size 10, timeout 5 seconds) is
not complete yet
+ assertNull(send("2", 2).getException());
+ assertNull(send("1", 1).getException());
+
+ // stop and start the route before the batch timeout
+ context.getRouteController().stopRoute("batch");
+ context.getRouteController().startRoute("batch");
+
+ MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void testQueuedExchangesAreDeliveredWithLaterOnesAfterTwoRestarts() throws
Exception {
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("1", "2", "3", "4");
+
+ assertNull(send("4", 4).getException());
+ assertNull(send("2", 2).getException());
+ context.getRouteController().stopRoute("batch");
+ context.getRouteController().startRoute("batch");
+ context.getRouteController().stopRoute("batch");
+ context.getRouteController().startRoute("batch");
+ assertNull(send("3", 3).getException());
+ assertNull(send("1", 1).getException());
+
+ // one batch, in order, with the exchanges queued before and after the
restarts
+ MockEndpoint.assertIsSatisfied(context, 20, TimeUnit.SECONDS);
+ }
+
+ @Test
+ void testStoppedResequencerRejectsWithRouteStoppingException() throws
Exception {
+ Resequencer resequencer = new Resequencer(context, e -> {
+ }, ExpressionBuilder.headerExpression("seq"));
+ resequencer.setId("resequence1");
+ ServiceHelper.startService(resequencer);
+ ServiceHelper.stopService(resequencer);
+ try {
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getMessage().setHeader("seq", 1);
+ AtomicBoolean done = new AtomicBoolean();
+
+ assertTrue(resequencer.process(exchange, done::set));
+
+ assertTrue(done.get());
+ RouteStoppingException e =
assertInstanceOf(RouteStoppingException.class, exchange.getException());
+ assertEquals("Resequencer is stopped: " + resequencer,
e.getMessage());
+ } finally {
+ ServiceHelper.stopAndShutdownService(resequencer);
+ }
+ }
+
+ private Exchange send(String body, int seq) {
+ return template.send("direct:start", e -> {
+ e.getMessage().setBody(body);
+ e.getMessage().setHeader("seq", seq);
+ });
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from("direct:start").routeId("batch")
+ .resequence(header("seq")).batch().size(10)
+ // the sends and restarts of a test must fit in one
batch timeout, with margin for a slow CI
+ .timeout(5000)
+ .to("mock:result");
+ }
+ };
+ }
+}