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 aeda9605a3f3 CAMEL-27355: camel-rocketmq - every InOut request
completes when the reply manager stops, and no reply manager is created after
the stop (#30697)
aeda9605a3f3 is described below
commit aeda9605a3f35afa249c725dbf7c509144c0983a
Author: allthingssecurity <[email protected]>
AuthorDate: Tue Nov 24 12:15:04 2026 +0530
CAMEL-27355: camel-rocketmq - every InOut request completes when the reply
manager stops, and no reply manager is created after the stop (#30697)
The producer registers the handler of an InOut request in the onSuccess
callback of the asynchronous send. A handler added while
ReplyTimeoutMap.doStop ran (after the drain, before DefaultTimeoutMap
cleared the map) was removed without being completed, and one added
after the stop stayed in the stopped map: the exchange never completed.
ReplyTimeoutMap now closes itself under its lock before the drain, and
completes a handler added to a closed map at once, as the drain does.
A request that passed the running check just before the stop created a
new reply manager (a push consumer on the reply topic and a timeout
checker thread) after the stop, which nothing stopped.
initReplyManager now checks isRunAllowed() under the producer's lock
and fails the request with RejectedExecutionException.
createReplyManager is protected (as in JmsProducer), so the test can
count the reply managers without a name server.
These are the gaps that CAMEL-27321 and CAMEL-27339 close in camel-jms
and camel-sjms.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../camel/component/rocketmq/RocketMQProducer.java | 11 +-
.../component/rocketmq/reply/ReplyTimeoutMap.java | 83 +++++++++--
.../RocketMQProducerStopReplyManagerTest.java | 160 +++++++++++++++++++++
.../reply/RocketMQReplyManagerStopTest.java | 131 +++++++++++++++++
4 files changed, 375 insertions(+), 10 deletions(-)
diff --git
a/components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/RocketMQProducer.java
b/components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/RocketMQProducer.java
index 989985a34be4..690d0f8ba94d 100644
---
a/components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/RocketMQProducer.java
+++
b/components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/RocketMQProducer.java
@@ -145,6 +145,11 @@ public class RocketMQProducer extends DefaultAsyncProducer
{
if (started.get()) {
return;
}
+ if (!isRunAllowed()) {
+ // this request passed the check in process() before the
producer was stopped: do not create a reply
+ // manager that nothing would stop (the lock is the one of
the producer's start and stop)
+ throw new RejectedExecutionException("Producer is not
running: " + this);
+ }
LOG.debug("Starting reply manager");
ClassLoader current =
Thread.currentThread().getContextClassLoader();
ClassLoader ac =
getEndpoint().getCamelContext().getApplicationContextClassLoader();
@@ -187,7 +192,11 @@ public class RocketMQProducer extends DefaultAsyncProducer
{
}
}
- private ReplyManager createReplyManager() {
+ /**
+ * Creates and starts the reply manager of this producer (protected so
that tests can replace it, as in
+ * JmsProducer).
+ */
+ protected ReplyManager createReplyManager() {
RocketMQReplyManagerSupport replyManager = new
RocketMQReplyManagerSupport(getEndpoint().getCamelContext());
replyManager.setEndpoint(getEndpoint());
String name = "RocketMQReplyManagerTimeoutChecker[" +
getEndpoint().getTopicName() + "]";
diff --git
a/components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/reply/ReplyTimeoutMap.java
b/components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/reply/ReplyTimeoutMap.java
index c567ef363b1b..57e98a589986 100644
---
a/components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/reply/ReplyTimeoutMap.java
+++
b/components/camel-rocketmq/src/main/java/org/apache/camel/component/rocketmq/reply/ReplyTimeoutMap.java
@@ -18,13 +18,30 @@
package org.apache.camel.component.rocketmq.reply;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.support.DefaultTimeoutMap;
+/**
+ * The handlers of the requests that wait for a reply, by message key. Every
handler that is added to the map is
+ * completed once: by its reply, by its timeout, or when the map stops. Once
the map has stopped, no handler is added
+ * any more: a handler that is added then (the send of its request succeeded
after the stop) is completed at once.
+ */
public class ReplyTimeoutMap extends DefaultTimeoutMap<String, ReplyHandler> {
+ // the lock of the map, which also guards closed
+ private final Lock lock;
+ // set when the map stops, before the drain, so a handler can no longer be
added after the drain
+ private boolean closed;
+
public ReplyTimeoutMap(ScheduledExecutorService executor, long
requestMapPollTimeMillis) {
- super(executor, requestMapPollTimeMillis);
+ this(executor, requestMapPollTimeMillis, new ReentrantLock());
+ }
+
+ private ReplyTimeoutMap(ScheduledExecutorService executor, long
requestMapPollTimeMillis, Lock lock) {
+ super(executor, requestMapPollTimeMillis, lock);
+ this.lock = lock;
addListener(this::listener);
}
@@ -41,31 +58,79 @@ public class ReplyTimeoutMap extends
DefaultTimeoutMap<String, ReplyHandler> {
log.trace("Removed messageKey: {}", key);
break;
case Evict:
- try {
- handler.onTimeout(key);
- } catch (Exception e) {
- log.warn("Error processing onTimeout for messageKey: {}
due: {}. This exception is ignored.",
- key, e.getLocalizedMessage(), e);
- }
+ onTimeout(key, handler);
log.trace("Evicted messageKey: {}", key);
break;
default:
}
}
+ private void onTimeout(String key, ReplyHandler handler) {
+ try {
+ handler.onTimeout(key);
+ } catch (Exception e) {
+ log.warn("Error processing onTimeout for messageKey: {} due: {}.
This exception is ignored.",
+ key, e.getLocalizedMessage(), e);
+ }
+ }
+
+ @Override
+ protected void doStart() throws Exception {
+ lock.lock();
+ try {
+ closed = false;
+ } finally {
+ lock.unlock();
+ }
+ super.doStart();
+ }
+
@Override
protected void doStop() throws Exception {
+ // close the map before the drain: a handler added after the drain
would be cleared by super.doStop() (or stay
+ // in the stopped map), and its exchange would never complete
+ lock.lock();
+ try {
+ closed = true;
+ } finally {
+ lock.unlock();
+ }
drainAndEvictAll();
super.doStop();
}
@Override
public ReplyHandler put(String key, ReplyHandler value, long
timeoutMillis) {
- return super.put(key, value, encode(timeoutMillis));
+ lock.lock();
+ try {
+ if (!closed) {
+ return super.put(key, value, encode(timeoutMillis));
+ }
+ } finally {
+ lock.unlock();
+ }
+ completeClosed(key, value);
+ return null;
}
@Override
public ReplyHandler putIfAbsent(String key, ReplyHandler value, long
timeoutMillis) {
- return super.putIfAbsent(key, value, encode(timeoutMillis));
+ lock.lock();
+ try {
+ if (!closed) {
+ return super.putIfAbsent(key, value, encode(timeoutMillis));
+ }
+ } finally {
+ lock.unlock();
+ }
+ completeClosed(key, value);
+ return null;
+ }
+
+ private void completeClosed(String key, ReplyHandler handler) {
+ // the map has stopped and was drained: the request has been sent, but
this handler is in no map, so it is
+ // completed here as the drain would have done
+ log.debug("Cannot add messageKey: {} as the reply manager is stopped.
Completing its exchange.", key);
+ onTimeout(key, handler);
}
}
diff --git
a/components/camel-rocketmq/src/test/java/org/apache/camel/component/rocketmq/RocketMQProducerStopReplyManagerTest.java
b/components/camel-rocketmq/src/test/java/org/apache/camel/component/rocketmq/RocketMQProducerStopReplyManagerTest.java
new file mode 100644
index 000000000000..70985d7d7a2e
--- /dev/null
+++
b/components/camel-rocketmq/src/test/java/org/apache/camel/component/rocketmq/RocketMQProducerStopReplyManagerTest.java
@@ -0,0 +1,160 @@
+/*
+ * 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.rocketmq;
+
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.AsyncCallback;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.TypeConversionException;
+import org.apache.camel.component.rocketmq.reply.ReplyHolder;
+import org.apache.camel.component.rocketmq.reply.ReplyManager;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.TypeConverterSupport;
+import org.apache.camel.support.service.ServiceHelper;
+import org.apache.camel.support.service.ServiceSupport;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+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.assertTrue;
+
+/**
+ * An InOut request that passed the running check of the producer just before
the producer was stopped must not create a
+ * reply manager (a consumer of the reply topic and a timeout checker thread)
that nothing would stop.
+ */
+class RocketMQProducerStopReplyManagerTest extends CamelTestSupport {
+
+ private static final String ROCKETMQ_URI =
"rocketmq:STOP_TOPIC?namesrvAddr=localhost:9876&producerGroup=p1"
+ +
"&replyToTopic=REPLY_TOPIC&replyToConsumerGroup=g1";
+
+ private final CountDownLatch converting = new CountDownLatch(1);
+ private final CountDownLatch continueConverting = new CountDownLatch(1);
+ // the reply managers that the producer created
+ private final List<TestReplyManager> replyManagers = new
CopyOnWriteArrayList<>();
+ private RocketMQProducer producer;
+
+ @AfterEach
+ void stopProducer() {
+ continueConverting.countDown();
+ ServiceHelper.stopService(producer);
+ replyManagers.forEach(ServiceHelper::stopService);
+ }
+
+ @Test
+ void testNoReplyManagerAfterStop() throws Exception {
+ // the body of the request is converted after the running check, and
before the reply manager is created
+ context.getTypeConverterRegistry().addTypeConverter(byte[].class,
SlowBody.class, new TypeConverterSupport() {
+ @Override
+ public <T> T convertTo(Class<T> type, Exchange exchange, Object
value) throws TypeConversionException {
+ converting.countDown();
+ try {
+ continueConverting.await(10, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ return type.cast(new byte[] { 1 });
+ }
+ });
+ startProducer();
+
+ Exchange exchange = new DefaultExchange(context,
ExchangePattern.InOut);
+ exchange.getIn().setBody(new SlowBody());
+ CountDownLatch done = new CountDownLatch(1);
+ Thread request = new Thread(() -> producer.process(exchange, doneSync
-> done.countDown()), "request");
+ request.start();
+ assertTrue(converting.await(10, TimeUnit.SECONDS), "The request should
convert its body");
+
+ // the producer is stopped while the request converts its body, and
then the request continues
+ ServiceHelper.stopService(producer);
+ continueConverting.countDown();
+ assertTrue(done.await(10, TimeUnit.SECONDS), "The exchange should be
completed");
+
+ assertEquals(0, replyManagers.size(), "No reply manager should be
created after the producer stopped");
+ assertInstanceOf(RejectedExecutionException.class,
exchange.getException());
+ }
+
+ @Test
+ void testReplyManagerCreatedWhileRunning() throws Exception {
+ // control (passes without the change): a running producer creates its
reply manager once, and the stop of the
+ // producer stops it
+ startProducer();
+
+ producer.initReplyManager();
+ producer.initReplyManager();
+ assertEquals(1, replyManagers.size(), "The reply manager should be
created once");
+ assertTrue(replyManagers.get(0).isStarted());
+
+ ServiceHelper.stopService(producer);
+ assertTrue(replyManagers.get(0).isStopped(), "The stop of the producer
should stop its reply manager");
+ }
+
+ private void startProducer() {
+ producer = new RocketMQProducer((RocketMQEndpoint)
context.getEndpoint(ROCKETMQ_URI)) {
+ @Override
+ protected ReplyManager createReplyManager() {
+ // the real reply manager starts a consumer of the reply
topic, which needs a name server
+ TestReplyManager replyManager = new TestReplyManager();
+ ServiceHelper.startService(replyManager);
+ replyManagers.add(replyManager);
+ return replyManager;
+ }
+ };
+ ServiceHelper.startService(producer);
+ }
+
+ private static final class SlowBody {
+ }
+
+ private static final class TestReplyManager extends ServiceSupport
implements ReplyManager {
+
+ @Override
+ public void setEndpoint(RocketMQEndpoint endpoint) {
+ }
+
+ @Override
+ public void setReplyToTopic(String replyToTopic) {
+ }
+
+ @Override
+ public String registerReply(
+ ReplyManager replyManager, Exchange exchange, AsyncCallback
callback, String messageKey,
+ long requestTimeout) {
+ return messageKey;
+ }
+
+ @Override
+ public void setScheduledExecutorService(ScheduledExecutorService
executorService) {
+ }
+
+ @Override
+ public void processReply(ReplyHolder holder) {
+ }
+
+ @Override
+ public void cancelMessageKey(String messageKey) {
+ }
+ }
+}
diff --git
a/components/camel-rocketmq/src/test/java/org/apache/camel/component/rocketmq/reply/RocketMQReplyManagerStopTest.java
b/components/camel-rocketmq/src/test/java/org/apache/camel/component/rocketmq/reply/RocketMQReplyManagerStopTest.java
new file mode 100644
index 000000000000..fc442c3dd5fc
--- /dev/null
+++
b/components/camel-rocketmq/src/test/java/org/apache/camel/component/rocketmq/reply/RocketMQReplyManagerStopTest.java
@@ -0,0 +1,131 @@
+/*
+ * 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.rocketmq.reply;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.TimeoutMap;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.service.ServiceHelper;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+
+/**
+ * Every request that the reply manager registers completes: also a request
whose send succeeds while, or after, the
+ * reply manager stops (the producer registers the reply in the callback of
the send).
+ */
+class RocketMQReplyManagerStopTest {
+
+ private final Map<String, AtomicInteger> completions = new
ConcurrentHashMap<>();
+ private CamelContext context;
+ private ScheduledExecutorService executorService;
+ private TestReplyManager replyManager;
+
+ @BeforeEach
+ void setUp() {
+ context = new DefaultCamelContext();
+ context.start();
+ executorService = Executors.newSingleThreadScheduledExecutor();
+ replyManager = new TestReplyManager(context, executorService);
+ ServiceHelper.startService(replyManager);
+ }
+
+ @AfterEach
+ void tearDown() {
+ ServiceHelper.stopService(replyManager);
+ executorService.shutdownNow();
+ context.stop();
+ }
+
+ @Test
+ void testRequestWaitingWhenTheReplyManagerStopsIsCompleted() {
+ // control (passes without the change): the stop completes the
requests that wait for their reply
+ Exchange exchange = register("camel-rocketmq-key-1");
+
+ ServiceHelper.stopService(replyManager);
+
+ assertCompletedOnce("camel-rocketmq-key-1", exchange);
+ }
+
+ @Test
+ void testRequestRegisteredAfterTheStopIsCompleted() {
+ ServiceHelper.stopService(replyManager);
+
+ // the send of the request succeeded after the stop
+ Exchange exchange = register("camel-rocketmq-key-1");
+
+ assertCompletedOnce("camel-rocketmq-key-1", exchange);
+ }
+
+ @Test
+ void testRequestRegisteredWhileTheStopDrainsIsCompleted() {
+ Exchange first = register("camel-rocketmq-key-1");
+ Exchange[] second = new Exchange[1];
+ // the send of the second request succeeds while the stop completes
the first request (after the drain took the
+ // entries out of the map, and before the map is cleared)
+ replyManager.timeoutMap.addListener((type, key, value) -> {
+ if (type == TimeoutMap.Listener.Type.Evict &&
"camel-rocketmq-key-1".equals(key)) {
+ second[0] = register("camel-rocketmq-key-2");
+ }
+ });
+
+ ServiceHelper.stopService(replyManager);
+
+ assertCompletedOnce("camel-rocketmq-key-1", first);
+ assertCompletedOnce("camel-rocketmq-key-2", second[0]);
+ }
+
+ private Exchange register(String key) {
+ Exchange exchange = new DefaultExchange(context);
+ AtomicInteger count = completions.computeIfAbsent(key, k -> new
AtomicInteger());
+ replyManager.registerReply(replyManager, exchange, doneSync ->
count.incrementAndGet(), key, 60000);
+ return exchange;
+ }
+
+ private void assertCompletedOnce(String key, Exchange exchange) {
+ assertEquals(1, completions.get(key).get(), "The exchange of " + key +
" should be completed once");
+ assertInstanceOf(RejectedExecutionException.class,
exchange.getException());
+ }
+
+ private static final class TestReplyManager extends
RocketMQReplyManagerSupport {
+
+ TestReplyManager(CamelContext camelContext, ScheduledExecutorService
executorService) {
+ super(camelContext);
+ setScheduledExecutorService(executorService);
+ }
+
+ @Override
+ protected void doStart() throws Exception {
+ // no consumer of the reply topic (it needs a broker): the
requests do not get a reply in this test, and the
+ // purge task does not run during the test (the requests do not
time out)
+ timeoutMap = new ReplyTimeoutMap(executorService, 3600000);
+ ServiceHelper.startService(timeoutMap);
+ }
+ }
+}