This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-26362-sjms-batch-shutdown-aware in repository https://gitbox.apache.org/repos/asf/camel.git
commit 3e1adc95bcecee8242dab82f682d86942a091bd7 Author: Claus Ibsen <[email protected]> AuthorDate: Thu Nov 26 16:47:53 2026 +0100 CAMEL-26362: camel-sjms - the graceful shutdown waits for the batch of a batching consumer The sjms (and sjms2) consumer is ShutdownAware. With batching, it reports the messages it still routes as pending exchanges: the batch being routed, and the buffered messages of an AUTO_ACKNOWLEDGE session. While the consumer is suspended (the first step of the graceful shutdown), those acknowledged messages are routed as a batch right away, so the graceful shutdown waits for them before it stops the consumer. Before, they were routed only during the stop of the consumer, within the 10 seconds shutdown wait of its executor, and a batch still routed after that was interrupted and lost. A transacted or CLIENT_ACKNOWLEDGE consumer starts no batch while suspended: its buffered messages are routed after a resume, or redelivered after a stop. So a stop does not close the session under a batch that started after the graceful shutdown stopped waiting, which would be routed again when redelivered. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../apache/camel/catalog/docs/sjms-component.adoc | 20 ++- .../camel-sjms/src/main/docs/sjms-component.adoc | 20 ++- .../apache/camel/component/sjms/SjmsConsumer.java | 28 +++- .../sjms/consumer/BatchConsumerWorker.java | 63 ++++++- .../consumer/BatchMessageListenerContainer.java | 24 ++- .../batch/BatchConsumerGracefulShutdownTest.java | 181 +++++++++++++++++++++ .../batch/BatchConsumerGracefulShutdownTest.java | 125 ++++++++++++++ 7 files changed, 440 insertions(+), 21 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sjms-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sjms-component.adoc index 5ae73b0dc59f..10efa704234e 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sjms-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/sjms-component.adoc @@ -384,13 +384,19 @@ set on the individual exchange and the body is set to the result of the `eagerPo each exchange of the batch for an exception (`Exchange.getException()`) and handle it. Do this before using `split(body())`, because the split copies only the message, not the exception. -When the route or the consumer is stopped, a partial batch (fewer than `batchSize` messages) is handled -according to the acknowledgement mode. With `transacted=true` or `CLIENT_ACKNOWLEDGE`, the partial batch is not -routed. Its messages are not acknowledged, so the broker redelivers them after the restart, with the -`JMSRedelivered` header set to `true`. The redelivery counts towards the broker's delivery limit. With -`AUTO_ACKNOWLEDGE`, the messages are already acknowledged, so the partial batch is routed during the stop, within -the 10-second shutdown wait of the consumer's executor. A batch that is still being processed when the wait -expires is lost. +When the route or the consumer is stopped, Camel's graceful shutdown first suspends the consumer, so no more +messages are received, and waits for the batch being routed before it stops the consumer. A partial batch (fewer +than `batchSize` messages) is handled according to the acknowledgement mode. With `transacted=true` or +`CLIENT_ACKNOWLEDGE`, the partial batch is not routed, and no new batch starts while the consumer is suspended. Its +messages are not acknowledged, so the broker redelivers them after the restart, with the `JMSRedelivered` header set +to `true`. The redelivery counts towards the broker's delivery limit. With `AUTO_ACKNOWLEDGE`, the messages are +already acknowledged, so the partial batch is routed as soon as the consumer is suspended, and the graceful shutdown +waits for it as well. The graceful shutdown waits up to its timeout (45 seconds by default, see +xref:manual::graceful-shutdown.adoc[Graceful Shutdown]); a batch that is still routed when the timeout is reached +is lost (`AUTO_ACKNOWLEDGE`) or redelivered (`transacted=true` and `CLIENT_ACKNOWLEDGE`). + +A suspended route (for example by a route policy) handles a partial batch in the same way: with `AUTO_ACKNOWLEDGE` +it is routed right away, and with `transacted=true` or `CLIENT_ACKNOWLEDGE` it is routed after the route is resumed. With `concurrentConsumers` greater than 1, each consumer collects and routes its own batches, so several batches are processed in parallel. diff --git a/components/camel-sjms/src/main/docs/sjms-component.adoc b/components/camel-sjms/src/main/docs/sjms-component.adoc index 5ae73b0dc59f..10efa704234e 100644 --- a/components/camel-sjms/src/main/docs/sjms-component.adoc +++ b/components/camel-sjms/src/main/docs/sjms-component.adoc @@ -384,13 +384,19 @@ set on the individual exchange and the body is set to the result of the `eagerPo each exchange of the batch for an exception (`Exchange.getException()`) and handle it. Do this before using `split(body())`, because the split copies only the message, not the exception. -When the route or the consumer is stopped, a partial batch (fewer than `batchSize` messages) is handled -according to the acknowledgement mode. With `transacted=true` or `CLIENT_ACKNOWLEDGE`, the partial batch is not -routed. Its messages are not acknowledged, so the broker redelivers them after the restart, with the -`JMSRedelivered` header set to `true`. The redelivery counts towards the broker's delivery limit. With -`AUTO_ACKNOWLEDGE`, the messages are already acknowledged, so the partial batch is routed during the stop, within -the 10-second shutdown wait of the consumer's executor. A batch that is still being processed when the wait -expires is lost. +When the route or the consumer is stopped, Camel's graceful shutdown first suspends the consumer, so no more +messages are received, and waits for the batch being routed before it stops the consumer. A partial batch (fewer +than `batchSize` messages) is handled according to the acknowledgement mode. With `transacted=true` or +`CLIENT_ACKNOWLEDGE`, the partial batch is not routed, and no new batch starts while the consumer is suspended. Its +messages are not acknowledged, so the broker redelivers them after the restart, with the `JMSRedelivered` header set +to `true`. The redelivery counts towards the broker's delivery limit. With `AUTO_ACKNOWLEDGE`, the messages are +already acknowledged, so the partial batch is routed as soon as the consumer is suspended, and the graceful shutdown +waits for it as well. The graceful shutdown waits up to its timeout (45 seconds by default, see +xref:manual::graceful-shutdown.adoc[Graceful Shutdown]); a batch that is still routed when the timeout is reached +is lost (`AUTO_ACKNOWLEDGE`) or redelivered (`transacted=true` and `CLIENT_ACKNOWLEDGE`). + +A suspended route (for example by a route policy) handles a partial batch in the same way: with `AUTO_ACKNOWLEDGE` +it is routed right away, and with `transacted=true` or `CLIENT_ACKNOWLEDGE` it is routed after the route is resumed. With `concurrentConsumers` greater than 1, each consumer collects and routes its own batches, so several batches are processed in parallel. diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsConsumer.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsConsumer.java index 419339348a64..f34e2cb67257 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsConsumer.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsConsumer.java @@ -24,8 +24,11 @@ import jakarta.jms.Connection; import org.apache.camel.Endpoint; import org.apache.camel.FailedToCreateConsumerException; import org.apache.camel.Processor; +import org.apache.camel.ShutdownRunningTask; import org.apache.camel.StatefulService; import org.apache.camel.Suspendable; +import org.apache.camel.component.sjms.consumer.BatchMessageListenerContainer; +import org.apache.camel.spi.ShutdownAware; import org.apache.camel.support.DefaultConsumer; import org.apache.camel.support.service.ServiceHelper; import org.slf4j.Logger; @@ -33,7 +36,7 @@ import org.slf4j.LoggerFactory; import static org.apache.camel.component.sjms.SjmsHelper.closeConnection; -public class SjmsConsumer extends DefaultConsumer implements Suspendable { +public class SjmsConsumer extends DefaultConsumer implements Suspendable, ShutdownAware { private static final Logger LOG = LoggerFactory.getLogger(SjmsConsumer.class); @@ -179,6 +182,29 @@ public class SjmsConsumer extends DefaultConsumer implements Suspendable { } } + @Override + public boolean deferShutdown(ShutdownRunningTask shutdownRunningTask) { + // not deferred: the graceful shutdown suspends this consumer, so no more messages are received, and then waits + // for the inflight and pending exchanges before it stops the consumer + return false; + } + + @Override + public int getPendingExchangesSize() { + // with batching, the messages that the listener container still routes before it stops: the batches being + // routed, and the buffered messages of an AUTO_ACKNOWLEDGE session, which are routed as a batch while the + // consumer is suspended (they are acknowledged on receipt, and would otherwise be lost) + if (listenerContainer instanceof BatchMessageListenerContainer batch) { + return batch.getPendingExchangesSize(); + } + return 0; + } + + @Override + public void prepareShutdown(boolean suspendOnly, boolean forced) { + // noop + } + public MessageListenerContainer getListenerContainer() { return listenerContainer; } diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchConsumerWorker.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchConsumerWorker.java index 900998daac7e..431f549f834c 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchConsumerWorker.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchConsumerWorker.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BooleanSupplier; import jakarta.jms.JMSException; import jakarta.jms.Message; @@ -45,15 +46,30 @@ public class BatchConsumerWorker implements Runnable { private final BatchEndpointMessageListener batchListener; private final MessageConsumer consumer; private final Session session; + private final BooleanSupplier suspended; private final AtomicBoolean running = new AtomicBoolean(true); private volatile boolean jmsUnhealthy; + // the messages that this worker still routes before it ends: the batch being routed, and the buffered messages + // of an AUTO_ACKNOWLEDGE session (acknowledged on receipt, so they are routed when suspended or stopped). Written + // by the worker only + private volatile int pendingMessages; BatchConsumerWorker(SjmsEndpoint endpoint, BatchEndpointMessageListener batchListener, - Session session, MessageConsumer consumer) { + Session session, MessageConsumer consumer, BooleanSupplier suspended) { this.endpoint = endpoint; this.batchListener = batchListener; this.session = session; this.consumer = consumer; + this.suspended = suspended; + } + + /** + * The number of messages that this worker still routes before it ends, for the graceful shutdown to wait for: the + * batch being routed, and the buffered messages of an AUTO_ACKNOWLEDGE session. The buffered messages of a + * transacted or CLIENT_ACKNOWLEDGE session are not counted, as they are redelivered when the consumer stops. + */ + int getPendingMessages() { + return pendingMessages; } void shutdown() { @@ -80,6 +96,7 @@ public class BatchConsumerWorker implements Runnable { LOG.trace("run START"); int batchSize = endpoint.getBatchSize(); long batchInterval = endpoint.getBatchInterval(); + boolean redeliverable = isRedeliverable(); List<Message> buffer = new ArrayList<>(); long batchStartTime = 0L; @@ -95,31 +112,67 @@ public class BatchConsumerWorker implements Runnable { batchStartTime = System.nanoTime(); } buffer.add(msg); + if (!redeliverable) { + pendingMessages = buffer.size(); + } } boolean sizeReached = batchSize > 0 && buffer.size() >= batchSize; boolean intervalElapsed = batchInterval > 0 && !buffer.isEmpty() && TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - batchStartTime) >= batchInterval; + boolean due = sizeReached || intervalElapsed; + if (due && redeliverable) { + // counted before the consumer is found not suspended, so that a graceful shutdown that suspends + // the consumer meanwhile sees this batch when it counts the pending messages + pendingMessages = buffer.size(); + } - if (sizeReached || intervalElapsed) { - dispatchOrDiscard(buffer); + boolean dispatch; + if (suspended.getAsBoolean()) { + // the consumer is suspended, such as by a graceful shutdown that waits for the pending messages. + // The buffered messages of an AUTO_ACKNOWLEDGE session are acknowledged already, so they are + // routed now, as no more messages may come to complete the batch. A transacted or + // CLIENT_ACKNOWLEDGE session starts no batch while suspended: its buffered messages are routed + // after a resume, or redelivered after a stop. So a stop does not close the session of a batch + // that started after the graceful shutdown stopped waiting (that batch would be routed again + // when redelivered) + dispatch = !redeliverable && !buffer.isEmpty(); + } else { + dispatch = due; + } + + if (dispatch) { + dispatchBatch(buffer); buffer = new ArrayList<>(); + } else if (redeliverable) { + pendingMessages = 0; } } if (!buffer.isEmpty()) { - dispatchOrDiscard(buffer); // graceful-stop drain + dispatchBatch(buffer); // graceful-stop drain } } catch (JMSException e) { jmsUnhealthy = true; if (!buffer.isEmpty()) { - dispatchOrDiscard(buffer); + dispatchBatch(buffer); } throw new BatchConsumerWorkerException(e); + } finally { + pendingMessages = 0; } LOG.trace("run STOP"); } + private void dispatchBatch(List<Message> batch) { + pendingMessages = batch.size(); + try { + dispatchOrDiscard(batch); + } finally { + pendingMessages = 0; + } + } + private void dispatchOrDiscard(List<Message> batch) { if (jmsUnhealthy) { if (isRedeliverable()) { diff --git a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchMessageListenerContainer.java b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchMessageListenerContainer.java index 33f29f764b32..7d24bf244025 100644 --- a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchMessageListenerContainer.java +++ b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchMessageListenerContainer.java @@ -81,8 +81,11 @@ public class BatchMessageListenerContainer extends SimpleMessageListenerContaine @Override protected void configureConsumer(MessageConsumer consumer, Session session) { + // a worker starts no batch of a transacted or CLIENT_ACKNOWLEDGE session while the container is suspended or + // stopping, and routes the buffered messages of an AUTO_ACKNOWLEDGE session right away BatchConsumerWorker worker = new BatchConsumerWorker( - this.endpoint, this.batchListener, session, consumer); + this.endpoint, this.batchListener, session, consumer, + () -> isSuspendingOrSuspended() || isStoppingOrStopped()); addWorker(worker); CompletableFuture.runAsync(worker, workerExecutorService) .whenComplete((v, ex) -> onWorkerExit(worker, ex)); @@ -101,6 +104,25 @@ public class BatchMessageListenerContainer extends SimpleMessageListenerContaine super.doStop(); } + /** + * The number of messages that the workers still route before they end, for the graceful shutdown to wait for: the + * batches being routed, and the buffered messages of an AUTO_ACKNOWLEDGE session (acknowledged on receipt). The + * buffered messages of a transacted or CLIENT_ACKNOWLEDGE session are not counted, as they are redelivered when the + * consumer stops. + */ + public int getPendingExchangesSize() { + workersLock.lock(); + try { + int answer = 0; + for (BatchConsumerWorker worker : workers) { + answer += worker.getPendingMessages(); + } + return answer; + } finally { + workersLock.unlock(); + } + } + private void invalidateWorkers() { workersLock.lock(); try { diff --git a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/batch/BatchConsumerGracefulShutdownTest.java b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/batch/BatchConsumerGracefulShutdownTest.java new file mode 100644 index 000000000000..52c840cef345 --- /dev/null +++ b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/batch/BatchConsumerGracefulShutdownTest.java @@ -0,0 +1,181 @@ +/* + * 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.sjms.batch; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.ServiceStatus; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.component.sjms.SjmsConsumer; +import org.apache.camel.component.sjms.support.JmsExclusiveTestSupport; +import org.apache.camel.test.infra.artemis.services.ArtemisService; +import org.apache.camel.test.infra.artemis.services.ArtemisServiceFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import static org.apache.camel.component.sjms.batch.BatchTestHelper.assertBatchSizesInOrder; +import static org.apache.camel.component.sjms.batch.BatchTestHelper.getBatchBodiesAsString; +import static org.apache.camel.component.sjms.batch.BatchTestHelper.sendMessagesWithText; +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.assertTrue; + +/** + * The graceful shutdown waits for the batch of a batching consumer: the consumer is suspended (no more messages are + * received), the batch being routed and the acknowledged messages of an AUTO_ACKNOWLEDGE session are routed, and only + * then the consumer is stopped. + */ +public class BatchConsumerGracefulShutdownTest extends JmsExclusiveTestSupport { + + private static final String QUEUE_NAME_TEMPLATE = "batch.consumer.%s.BatchConsumerGracefulShutdownTest"; + + @RegisterExtension + public static ArtemisService service = ArtemisServiceFactory.createVMService(); + + @Override + public ArtemisService getService() { + return service; + } + + @Test + public void testAutoAcknowledgePartialBatchRoutedBeforeConsumerStops() throws Exception { + String routeId = "auto-ack"; + String queue = String.format(QUEUE_NAME_TEMPLATE, routeId); + // batchInterval=0: a partial batch is only dispatched when the batch size is reached, or on shutdown + BlockingProcessor processor = addRoute(routeId, queue, + "batchSize=5&batchInterval=0&acknowledgementMode=AUTO_ACKNOWLEDGE"); + SjmsConsumer consumer = (SjmsConsumer) context.getRoute(routeId).getConsumer(); + + MockEndpoint mock = getMockEndpoint("mock:" + routeId); + mock.expectedMessageCount(1); + + // 3 of 5 messages: acknowledged on receipt, and buffered as a partial batch + sendMessagesWithText(template, "sjms:queue:" + queue, 3, "Before!"); + await().atMost(20, TimeUnit.SECONDS).until(() -> consumer.getPendingExchangesSize() == 3); + + CompletableFuture<Void> stop = stopRouteAsync(routeId); + + // the partial batch is routed while the consumer is suspended, and not by the stop of the consumer + assertTrue(processor.started.await(20, TimeUnit.SECONDS), "the partial batch was not routed"); + assertEquals(ServiceStatus.Suspended, processor.consumerStatus.get()); + assertEquals(3, consumer.getPendingExchangesSize()); + assertFalse(stop.isDone(), "the route stopped while its batch was routed"); + + processor.release.countDown(); + stop.get(30, TimeUnit.SECONDS); + assertEquals(ServiceStatus.Stopped, context.getRouteController().getRouteStatus(routeId)); + + mock.assertIsSatisfied(); + assertEquals(List.of("Before!", "Before!", "Before!"), getBatchBodiesAsString(mock.getExchanges().get(0))); + } + + @Test + public void testTransactedBatchCompletesBeforeConsumerStops() throws Exception { + String routeId = "tx"; + String queue = String.format(QUEUE_NAME_TEMPLATE, routeId); + BlockingProcessor processor = addRoute(routeId, queue, "batchSize=3&batchInterval=0&transacted=true"); + SjmsConsumer consumer = (SjmsConsumer) context.getRoute(routeId).getConsumer(); + + MockEndpoint mock = getMockEndpoint("mock:" + routeId); + mock.expectedMessageCount(1); + + sendMessagesWithText(template, "sjms:queue:" + queue, 3, "Before!"); + assertTrue(processor.started.await(20, TimeUnit.SECONDS), "the batch was not routed"); + + CompletableFuture<Void> stop = stopRouteAsync(routeId); + + // the graceful shutdown waits for the batch being routed + await().atMost(20, TimeUnit.SECONDS).until(consumer::isSuspended); + assertEquals(3, consumer.getPendingExchangesSize()); + assertFalse(stop.isDone(), "the route stopped while its batch was routed"); + + processor.release.countDown(); + stop.get(30, TimeUnit.SECONDS); + mock.assertIsSatisfied(); + assertEquals(List.of("Before!", "Before!", "Before!"), getBatchBodiesAsString(mock.getExchanges().get(0))); + + // the batch was committed before the session was closed, so it is not redelivered + mock.reset(); + mock.expectedMessageCount(1); + context.getRouteController().startRoute(routeId); + sendMessagesWithText(template, "sjms:queue:" + queue, 3, "After!"); + + mock.assertIsSatisfied(); + assertBatchSizesInOrder(mock, 3); + assertEquals(List.of("After!", "After!", "After!"), getBatchBodiesAsString(mock.getExchanges().get(0))); + } + + private CompletableFuture<Void> stopRouteAsync(String routeId) { + return CompletableFuture.runAsync(() -> { + try { + context.getRouteController().stopRoute(routeId); + } catch (Exception e) { + throw RuntimeCamelException.wrapRuntimeCamelException(e); + } + }); + } + + private BlockingProcessor addRoute(String routeId, String queue, String options) throws Exception { + BlockingProcessor processor = new BlockingProcessor(routeId); + context.addRoutes(new RouteBuilder() { + @Override + public void configure() { + from("sjms:queue:" + queue + "?batching=true&" + options) + .routeId(routeId) + .process(processor) + .to("mock:" + routeId); + } + }); + return processor; + } + + /** + * Blocks the first batch until it is released, and records the status of the consumer when the batch arrives. + */ + private class BlockingProcessor implements Processor { + + private final String routeId; + private final CountDownLatch started = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + private final AtomicReference<ServiceStatus> consumerStatus = new AtomicReference<>(); + + BlockingProcessor(String routeId) { + this.routeId = routeId; + } + + @Override + public void process(Exchange exchange) throws Exception { + if (started.getCount() == 0) { + return; + } + consumerStatus.set(((SjmsConsumer) context.getRoute(routeId).getConsumer()).getStatus()); + started.countDown(); + if (!release.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException("The batch was not released"); + } + } + } +} diff --git a/components/camel-sjms2/src/test/java/org/apache/camel/component/sjms2/batch/BatchConsumerGracefulShutdownTest.java b/components/camel-sjms2/src/test/java/org/apache/camel/component/sjms2/batch/BatchConsumerGracefulShutdownTest.java new file mode 100644 index 000000000000..20e982f40ee6 --- /dev/null +++ b/components/camel-sjms2/src/test/java/org/apache/camel/component/sjms2/batch/BatchConsumerGracefulShutdownTest.java @@ -0,0 +1,125 @@ +/* + * 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.sjms2.batch; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import jakarta.jms.ConnectionFactory; + +import org.apache.camel.Exchange; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.ServiceStatus; +import org.apache.camel.builder.RouteBuilder; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.component.sjms.SjmsConsumer; +import org.apache.camel.component.sjms2.support.Jms2TestSupport; +import org.apache.camel.test.infra.artemis.services.ArtemisService; +import org.apache.camel.test.infra.artemis.services.ArtemisServiceFactory; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +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.assertTrue; + +/** + * The graceful shutdown routes the acknowledged messages of a partial batch (AUTO_ACKNOWLEDGE) while the consumer is + * suspended, and stops the consumer after the batch is routed. + */ +public class BatchConsumerGracefulShutdownTest extends Jms2TestSupport { + + private static final String ROUTE_ID = "auto-ack"; + private static final String QUEUE = "sjms2.batch.consumer.BatchConsumerGracefulShutdownTest"; + + @RegisterExtension + public static ArtemisService service = ArtemisServiceFactory.createVMService(); + + private final CountDownLatch started = new CountDownLatch(1); + private final CountDownLatch release = new CountDownLatch(1); + private final AtomicReference<ServiceStatus> consumerStatus = new AtomicReference<>(); + + @Test + public void testAutoAcknowledgePartialBatchRoutedBeforeConsumerStops() throws Exception { + SjmsConsumer consumer = (SjmsConsumer) context.getRoute(ROUTE_ID).getConsumer(); + + MockEndpoint mock = getMockEndpoint("mock:result"); + mock.expectedMessageCount(1); + + // 3 of 5 messages: acknowledged on receipt, and buffered as a partial batch + for (int i = 0; i < 3; i++) { + template.sendBody("sjms2:queue:" + QUEUE, "Before!"); + } + await().atMost(20, TimeUnit.SECONDS).until(() -> consumer.getPendingExchangesSize() == 3); + + CompletableFuture<Void> stop = CompletableFuture.runAsync(() -> { + try { + context.getRouteController().stopRoute(ROUTE_ID); + } catch (Exception e) { + throw RuntimeCamelException.wrapRuntimeCamelException(e); + } + }); + + // the partial batch is routed while the consumer is suspended, and not by the stop of the consumer + assertTrue(started.await(20, TimeUnit.SECONDS), "the partial batch was not routed"); + assertEquals(ServiceStatus.Suspended, consumerStatus.get()); + assertFalse(stop.isDone(), "the route stopped while its batch was routed"); + + release.countDown(); + stop.get(30, TimeUnit.SECONDS); + assertEquals(ServiceStatus.Stopped, context.getRouteController().getRouteStatus(ROUTE_ID)); + + mock.assertIsSatisfied(); + List<?> batch = mock.getExchanges().get(0).getMessage().getBody(List.class); + assertEquals(3, batch.size()); + } + + @Override + protected ConnectionFactory getConnectionFactory() throws Exception { + return getConnectionFactory(service.serviceAddress()); + } + + @Override + protected RouteBuilder createRouteBuilder() { + return new RouteBuilder() { + @Override + public void configure() { + // batchInterval=0: a partial batch is only dispatched when the batch size is reached, or on shutdown + from("sjms2:queue:" + QUEUE + "?batching=true&batchSize=5&batchInterval=0" + + "&acknowledgementMode=AUTO_ACKNOWLEDGE") + .routeId(ROUTE_ID) + .process(this::blockFirstBatch) + .to("mock:result"); + } + + private void blockFirstBatch(Exchange exchange) throws Exception { + if (started.getCount() == 0) { + return; + } + consumerStatus.set(((SjmsConsumer) getContext().getRoute(ROUTE_ID).getConsumer()).getStatus()); + started.countDown(); + if (!release.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException("The batch was not released"); + } + } + }; + } +}
