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 387e1d761388 CAMEL-27333: camel-sjms - a request waiting for the new 
temporary reply queue ends at the request timeout or when the producer stops 
(#30625)
387e1d761388 is described below

commit 387e1d761388f5012fb51c987f4b6e30c4db25b0
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 23 15:35:38 2026 +0530

    CAMEL-27333: camel-sjms - a request waiting for the new temporary reply 
queue ends at the request timeout or when the producer stops (#30625)
    
    After the connection of the temporary reply queue's listener fails, every
    InOut request waits in getReplyTo until the recovery creates a new temporary
    queue. The wait had no timeout and nothing signalled it on stop: a stop 
during
    the wait (which cancels the recovery) left the request thread waiting for 
ever
    with its JMS session, and its exchange never completed, as it was not
    registered yet. The wait now loops with the endpoint's requestTimeout as
    deadline and ends when the reply manager stops; then getReplyTo throws and 
the
    producer completes the exchange without sending the request.
    
    A request that waits for the new temporary reply queue fails with
    RejectedExecutionException when the producer stops, the same exception as a
    request that reaches the stopped reply manager when it registers
    (CAMEL-27321). A request whose wait reaches the request timeout fails with
    ExchangeTimedOutException; the message says the request was not sent. As
    that exception is checked and getReplyTo declares none, the reply manager
    throws it wrapped, and SjmsProducer completes the exchange with the cause.
    
    The control test uses a request timeout of 20 s on the endpoint (the wait)
    and 500 ms in the CamelJmsRequestTimeout header (the registered request), 
and
    checks the timeout of the exception.
    
    Found with a TLA+ model.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../apache/camel/component/sjms/SjmsProducer.java  |   9 +-
 .../sjms/reply/TemporaryQueueReplyManager.java     |  81 ++++++++--
 .../TemporaryQueueReplyManagerRefreshTest.java     | 177 +++++++++++++++++++++
 3 files changed, 256 insertions(+), 11 deletions(-)

diff --git 
a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsProducer.java
 
b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsProducer.java
index de9f68474171..6cc1c4c25162 100644
--- 
a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsProducer.java
+++ 
b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/SjmsProducer.java
@@ -29,6 +29,7 @@ import jakarta.jms.Session;
 
 import org.apache.camel.AsyncCallback;
 import org.apache.camel.Exchange;
+import org.apache.camel.ExchangeTimedOutException;
 import org.apache.camel.FailedToCreateProducerException;
 import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.RuntimeExchangeException;
@@ -345,7 +346,13 @@ public class SjmsProducer extends DefaultAsyncProducer {
                         registered, e.getMessage(), e);
                 return false;
             }
-            exchange.setException(e);
+            if (e instanceof RuntimeCamelException && e.getCause() instanceof 
ExchangeTimedOutException timedOut) {
+                // no new temporary reply queue within the request timeout 
(TemporaryQueueReplyManager.getReplyTo):
+                // the request was not sent
+                exchange.setException(timedOut);
+            } else {
+                exchange.setException(e);
+            }
             callback.done(true);
             return true;
         }
diff --git 
a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/TemporaryQueueReplyManager.java
 
b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/TemporaryQueueReplyManager.java
index 804d2eb7b97b..b71020c65031 100644
--- 
a/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/TemporaryQueueReplyManager.java
+++ 
b/components/camel-sjms/src/main/java/org/apache/camel/component/sjms/reply/TemporaryQueueReplyManager.java
@@ -16,6 +16,8 @@
  */
 package org.apache.camel.component.sjms.reply;
 
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
@@ -28,6 +30,8 @@ import jakarta.jms.Session;
 import jakarta.jms.TemporaryQueue;
 
 import org.apache.camel.CamelContext;
+import org.apache.camel.ExchangeTimedOutException;
+import org.apache.camel.RuntimeCamelException;
 import org.apache.camel.component.sjms.MessageListenerContainer;
 import org.apache.camel.component.sjms.jms.DestinationCreationStrategy;
 
@@ -45,7 +49,23 @@ public class TemporaryQueueReplyManager extends 
ReplyManagerSupport {
     @Override
     public Destination getReplyTo() {
         try {
-            destResolver.destinationReady();
+            // wait at most the request timeout, as the request is not 
registered yet, so neither its timeout nor the
+            // stop of the reply manager would complete it
+            long timeout = endpoint.getRequestTimeout();
+            if (!destResolver.destinationReady(timeout)) {
+                if (destResolver.isStopped()) {
+                    // the same exception as a request that reaches the 
stopped reply manager when it registers
+                    throw new RejectedExecutionException(
+                            "The reply manager was stopped while waiting for a 
new temporary JMSReplyTo queue."
+                                                         + " The request was 
not sent.");
+                }
+                // ExchangeTimedOutException is checked: SjmsProducer 
completes the exchange with the cause
+                throw new RuntimeCamelException(
+                        new ExchangeTimedOutException(
+                                null, timeout,
+                                "to no new temporary JMSReplyTo queue being 
created after the connection of the reply"
+                                               + " listener failed. The 
request was not sent."));
+            }
         } catch (InterruptedException e) {
             log.warn("Interrupted while waiting for JMSReplyTo destination 
refresh", e);
             Thread.currentThread().interrupt();
@@ -53,6 +73,14 @@ public class TemporaryQueueReplyManager extends 
ReplyManagerSupport {
         return super.getReplyTo();
     }
 
+    @Override
+    protected void doStop() throws Exception {
+        // release the requests waiting for a new temporary queue: the 
listener container is stopped next, so no new
+        // queue would be created for them
+        destResolver.stop();
+        super.doStop();
+    }
+
     @Override
     public void updateCorrelationId(String correlationId, String 
newCorrelationId, long requestTimeout) {
         log.trace("Updated provisional correlationId [{}] to expected 
correlationId [{}]", correlationId, newCorrelationId);
@@ -116,6 +144,7 @@ public class TemporaryQueueReplyManager extends 
ReplyManagerSupport {
         private final Condition condition = lock.newCondition();
         private TemporaryQueue queue;
         private volatile boolean refreshWanted;
+        private volatile boolean stopped;
 
         @Override
         public Destination createDestination(Session session, String name, 
boolean topic) throws JMSException {
@@ -145,18 +174,50 @@ public class TemporaryQueueReplyManager extends 
ReplyManagerSupport {
             refreshWanted = true;
         }
 
-        public void destinationReady() throws InterruptedException {
-            if (refreshWanted) {
-                lock.lock();
-                try {
-                    //check if requestWanted is still true
-                    if (refreshWanted) {
-                        log.debug("Waiting for new Temporary ReplyTo queue to 
be assigned before we can continue");
+        /**
+         * Waits until no refresh of the temporary queue is wanted any more.
+         *
+         * @param  timeoutMillis the longest time to wait, zero or negative to 
wait until the queue is refreshed or the
+         *                       reply manager is stopped
+         * @return               {@code true} when the queue is ready, {@code 
false} when the time ran out or the reply
+         *                       manager was stopped
+         */
+        public boolean destinationReady(long timeoutMillis) throws 
InterruptedException {
+            if (!refreshWanted) {
+                return true;
+            }
+            lock.lock();
+            try {
+                long nanos = TimeUnit.MILLISECONDS.toNanos(timeoutMillis);
+                // check if refreshWanted is still true
+                while (refreshWanted) {
+                    if (stopped || (timeoutMillis > 0 && nanos <= 0)) {
+                        return false;
+                    }
+                    log.debug("Waiting for new Temporary ReplyTo queue to be 
assigned before we can continue");
+                    if (timeoutMillis > 0) {
+                        nanos = condition.awaitNanos(nanos);
+                    } else {
                         condition.await();
                     }
-                } finally {
-                    lock.unlock();
                 }
+                return true;
+            } finally {
+                lock.unlock();
+            }
+        }
+
+        public boolean isStopped() {
+            return stopped;
+        }
+
+        public void stop() {
+            lock.lock();
+            try {
+                stopped = true;
+                condition.signalAll();
+            } finally {
+                lock.unlock();
             }
         }
 
diff --git 
a/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/reply/TemporaryQueueReplyManagerRefreshTest.java
 
b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/reply/TemporaryQueueReplyManagerRefreshTest.java
new file mode 100644
index 000000000000..6fbeb9e13ac0
--- /dev/null
+++ 
b/components/camel-sjms/src/test/java/org/apache/camel/component/sjms/reply/TemporaryQueueReplyManagerRefreshTest.java
@@ -0,0 +1,177 @@
+/*
+ * 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.reply;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import jakarta.jms.JMSException;
+
+import org.apache.camel.AsyncProcessor;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.ExchangeTimedOutException;
+import org.apache.camel.component.sjms.SjmsConstants;
+import org.apache.camel.component.sjms.SjmsProducer;
+import org.apache.camel.component.sjms.consumer.SimpleMessageListenerContainer;
+import org.apache.camel.component.sjms.support.JmsTestSupport;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.service.ServiceHelper;
+import org.junit.jupiter.api.AfterEach;
+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.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * After the connection of the temporary reply queue's listener fails, an 
InOut request waits for the new temporary
+ * queue before it is sent. It is not registered yet, so neither its request 
timeout nor the stop of the reply manager
+ * completes it: the wait itself must end when the reply manager stops, and 
after the request timeout.
+ */
+class TemporaryQueueReplyManagerRefreshTest extends JmsTestSupport {
+
+    private Thread sender;
+
+    @AfterEach
+    void interruptSender() {
+        if (sender != null) {
+            sender.interrupt();
+        }
+    }
+
+    @Test
+    void testStopReleasesRequestWaitingForNewTemporaryQueue() throws Exception 
{
+        SjmsProducer producer = 
startProducer("sjms:queue:TemporaryQueueRefresh.stop?requestTimeout=60000");
+        // the connection failed, and no recovery creates a new temporary queue
+        scheduleRefresh(producer);
+
+        Exchange exchange = inOut("Hello");
+        AtomicInteger done = sendAsync(producer, exchange);
+        awaitWaitingForTemporaryQueue();
+
+        ServiceHelper.stopService(producer);
+
+        await().atMost(5, TimeUnit.SECONDS).until(() -> done.get() > 0);
+        assertEquals(1, done.get());
+        // the same exception as a request that reaches the stopped reply 
manager when it registers (CAMEL-27321)
+        assertInstanceOf(RejectedExecutionException.class, 
exchange.getException());
+        assertTrue(exchange.getException().getMessage().contains("stopped"), 
exchange.getException().getMessage());
+    }
+
+    @Test
+    void testRequestFailsWhenNoNewTemporaryQueueWithinRequestTimeout() throws 
Exception {
+        SjmsProducer producer = 
startProducer("sjms:queue:TemporaryQueueRefresh.timeout?requestTimeout=1000");
+        scheduleRefresh(producer);
+
+        Exchange exchange = inOut("Hello");
+        AtomicInteger done = sendAsync(producer, exchange);
+
+        await().atMost(10, TimeUnit.SECONDS).until(() -> done.get() > 0);
+        assertEquals(1, done.get());
+        ExchangeTimedOutException e = 
assertInstanceOf(ExchangeTimedOutException.class, exchange.getException());
+        assertEquals(1000, e.getTimeout());
+        assertTrue(e.getMessage().contains("temporary JMSReplyTo queue"), 
e.getMessage());
+        assertTrue(e.getMessage().contains("not sent"), e.getMessage());
+        ServiceHelper.stopService(producer);
+    }
+
+    @Test
+    void testRequestIsSentWhenTheRecoveryCreatesTheNewTemporaryQueue() throws 
Exception {
+        // the wait for the new queue uses the endpoint's requestTimeout, 
which leaves a wide margin over the fixed 1 s
+        // delay of the recovery; the registered request uses the timeout of 
the header
+        SjmsProducer producer
+                = 
startProducer("sjms:queue:TemporaryQueueRefresh.recover?requestTimeout=20000&recoveryInterval=200");
+        TemporaryQueueReplyManager replyManager = replyManager(producer);
+        // the connection fails: the exception listener wants a refresh, and 
the recovery creates the new queue
+        ((SimpleMessageListenerContainer) replyManager.listenerContainer)
+                .onException(new JMSException("simulated connection failure"));
+
+        Exchange exchange = inOut("Hello");
+        exchange.getIn().setHeader(SjmsConstants.JMS_REQUEST_TIMEOUT, 500L);
+        AtomicInteger done = sendAsync(producer, exchange);
+
+        // the recovery runs after 1 second, then the request is sent; nothing 
replies, so it times out as usual, after
+        // the 500 ms of the header
+        await().atMost(15, TimeUnit.SECONDS).until(() -> done.get() > 0);
+        assertEquals(1, done.get());
+        ExchangeTimedOutException e = 
assertInstanceOf(ExchangeTimedOutException.class, exchange.getException());
+        assertEquals(500, e.getTimeout());
+        assertFalse(e.getMessage().contains("not sent"), e.getMessage());
+        ServiceHelper.stopService(producer);
+    }
+
+    private SjmsProducer startProducer(String uri) throws Exception {
+        SjmsProducer producer = (SjmsProducer) 
context.getEndpoint(uri).createProducer();
+        ServiceHelper.startService(producer);
+        // a first request creates the reply manager and its temporary queue; 
nothing replies, so it times out
+        Exchange first = inOut("first");
+        first.getIn().setHeader(SjmsConstants.JMS_REQUEST_TIMEOUT, 200L);
+        AtomicInteger done = new AtomicInteger();
+        ((AsyncProcessor) producer).process(first, doneSync -> 
done.incrementAndGet());
+        await().atMost(10, TimeUnit.SECONDS).until(() -> done.get() == 1);
+        return producer;
+    }
+
+    private Exchange inOut(String body) {
+        Exchange exchange = new DefaultExchange(context, 
ExchangePattern.InOut);
+        exchange.getIn().setBody(body);
+        return exchange;
+    }
+
+    private AtomicInteger sendAsync(SjmsProducer producer, Exchange exchange) {
+        AtomicInteger done = new AtomicInteger();
+        sender = new Thread(
+                () -> ((AsyncProcessor) producer).process(exchange, doneSync 
-> done.incrementAndGet()),
+                "TemporaryQueueRefreshSender");
+        sender.start();
+        return done;
+    }
+
+    private void awaitWaitingForTemporaryQueue() {
+        await().atMost(10, TimeUnit.SECONDS).until(() -> {
+            for (StackTraceElement element : sender.getStackTrace()) {
+                if ("destinationReady".equals(element.getMethodName())) {
+                    return sender.getState() == Thread.State.WAITING || 
sender.getState() == Thread.State.TIMED_WAITING;
+                }
+            }
+            return false;
+        });
+    }
+
+    private static TemporaryQueueReplyManager replyManager(SjmsProducer 
producer) throws Exception {
+        Field field = SjmsProducer.class.getDeclaredField("replyManager");
+        field.setAccessible(true);
+        return (TemporaryQueueReplyManager) field.get(producer);
+    }
+
+    /**
+     * What the exception listener of the reply listener does when its 
connection fails, without the recovery that would
+     * create the new queue.
+     */
+    private static void scheduleRefresh(SjmsProducer producer) throws 
Exception {
+        Object resolver = replyManager(producer).destResolver;
+        Method method = 
resolver.getClass().getDeclaredMethod("scheduleRefresh");
+        method.setAccessible(true);
+        method.invoke(resolver);
+    }
+}

Reply via email to