gnodet commented on code in PR #27173:
URL: https://github.com/apache/camel/pull/27173#discussion_r4238814494


##########
components/camel-sjms/src/test/java/org/apache/camel/component/sjms/batch/BatchConsumerReconnectTest.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * 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.TimeUnit;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+import org.apache.camel.CamelContext;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.sjms.SjmsComponent;
+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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.lang.String.format;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.BATCH_ROUTEBUILDER_MOCK_FINISH;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.createBatchRoute;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.getBatchBodiesAsString;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.getBatchExchanges;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.sendMessagesWithText;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.triggerConnectionFailure;
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class BatchConsumerReconnectTest extends JmsExclusiveTestSupport {
+
+    private static final String SJMS_QUEUE_NAME_TEMPLATE = 
"batch.consumer.%s.BatchConsumerReconnectTest";
+    private static final String ROUTE_ID_SESSION_TX = "tx";
+    private static final String ROUTE_ID_CLIENT_ACK_NO_TX = "no-tx-client-ack";
+    private static final String ROUTE_ID_AUTO_ACK_NO_TX = "no-tx-auto";
+
+    @RegisterExtension
+    public static ArtemisService service = 
ArtemisServiceFactory.createVMService();
+
+    private BatchTestHelper.CountingConnectionFactory countingFactory;
+
+    protected final Logger log = LoggerFactory.getLogger(getClass());
+
+    @Override
+    public ArtemisService getService() {
+        return service;
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        addSjmsComponent = false;
+        CamelContext camelContext = super.createCamelContext();
+
+        ActiveMQConnectionFactory connectionFactory = new 
ActiveMQConnectionFactory(service.serviceAddress());
+        connectionFactory.setReconnectAttempts(0);
+
+        countingFactory = new 
BatchTestHelper.CountingConnectionFactory(connectionFactory);
+
+        SjmsComponent sjms = new SjmsComponent();
+        sjms.setConnectionFactory(countingFactory);
+        camelContext.addComponent("sjms", sjms);
+
+        return camelContext;
+    }
+
+    @Test
+    public void testReconnectAutoAcknowledgedNotTransacted() throws Exception {
+        final String queueName = format(SJMS_QUEUE_NAME_TEMPLATE, 
ROUTE_ID_AUTO_ACK_NO_TX);
+        final String endpointUri = "sjms:queue:" + queueName;
+
+        MockEndpoint mock = 
getMockEndpoint(format(BATCH_ROUTEBUILDER_MOCK_FINISH, 
ROUTE_ID_AUTO_ACK_NO_TX));
+        mock.expectedMessageCount(1);
+
+        sendMessagesWithText(template, endpointUri, 2, "Before!");
+
+        int connectionsBefore = countingFactory.getCreateCount();
+        triggerConnectionFailure(context, ROUTE_ID_AUTO_ACK_NO_TX);
+        await().atMost(30, TimeUnit.SECONDS)
+                .until(() -> countingFactory.getCreateCount() > 
connectionsBefore);
+
+        mock.assertIsSatisfied();
+        assertEquals(2, getBatchExchanges(mock.getExchanges().get(0)).size());
+        assertEquals(List.of("Before!", "Before!"), 
getBatchBodiesAsString(mock.getExchanges().get(0)));
+
+        mock.reset();
+
+        // test with an incomplete batch - to check timing
+        mock.expectedMessageCount(1);
+        mock.setResultWaitTime(15000);
+        sendMessagesWithText(template, endpointUri, 3, "After!");
+
+        mock.assertIsSatisfied();
+        assertEquals(3, getBatchExchanges(mock.getExchanges().get(0)).size());
+        assertEquals(List.of("After!", "After!", "After!"), 
getBatchBodiesAsString(mock.getExchanges().get(0)));
+    }
+
+    @Test
+    public void testSessionTransacted() throws Exception {
+        final String queueName = format(SJMS_QUEUE_NAME_TEMPLATE, 
ROUTE_ID_SESSION_TX);
+        final String endpointUri = "sjms:queue:" + queueName;
+
+        MockEndpoint mock = 
getMockEndpoint(format(BATCH_ROUTEBUILDER_MOCK_FINISH, ROUTE_ID_SESSION_TX));
+        mock.expectedMessageCount(0);
+
+        sendMessagesWithText(template, endpointUri, 2, "Before!");
+
+        int connectionsBefore = countingFactory.getCreateCount();
+        triggerConnectionFailure(context, ROUTE_ID_AUTO_ACK_NO_TX);
+        await().atMost(30, TimeUnit.SECONDS)
+                .until(() -> countingFactory.getCreateCount() > 
connectionsBefore);
+
+        mock.assertIsSatisfied();
+        mock.reset();
+
+        // we want to test with 1 complete (incl. the messages prior to 
reconnect) and 1 incomplete batch
+        mock.expectedMessageCount(2);
+        mock.setResultWaitTime(15000);
+        sendMessagesWithText(template, endpointUri, 7, "After!");
+
+        mock.assertIsSatisfied();
+        // fist batch
+        assertEquals(5, getBatchExchanges(mock.getExchanges().get(0)).size());
+        assertEquals(List.of("Before!", "Before!", "After!", "After!", 
"After!"),
+                getBatchBodiesAsString(mock.getExchanges().get(0)));
+        // second batch
+        assertEquals(4, getBatchExchanges(mock.getExchanges().get(1)).size());
+        assertEquals(List.of("After!", "After!", "After!", "After!"), 
getBatchBodiesAsString(mock.getExchanges().get(1)));
+    }
+
+    @Test
+    public void testClientAcknowledge() throws Exception {
+        final String queueName = format(SJMS_QUEUE_NAME_TEMPLATE, 
ROUTE_ID_CLIENT_ACK_NO_TX);
+        final String endpointUri = "sjms:queue:" + queueName;
+
+        MockEndpoint mock = 
getMockEndpoint(format(BATCH_ROUTEBUILDER_MOCK_FINISH, 
ROUTE_ID_CLIENT_ACK_NO_TX));
+        mock.expectedMessageCount(0);
+
+        sendMessagesWithText(template, endpointUri, 2, "Before!");
+
+        int connectionsBefore = countingFactory.getCreateCount();
+        triggerConnectionFailure(context, ROUTE_ID_AUTO_ACK_NO_TX);

Review Comment:
   ⚠️ **Wrong route ID: testing reconnect on the wrong consumer.**
   
   `testClientAcknowledge()` triggers `ROUTE_ID_AUTO_ACK_NO_TX` instead of 
`ROUTE_ID_CLIENT_ACK_NO_TX`. CLIENT_ACKNOWLEDGE recovery is not exercised.
   
   ```suggestion
           triggerConnectionFailure(context, ROUTE_ID_CLIENT_ACK_NO_TX);
   ```



##########
components/camel-sjms/src/test/java/org/apache/camel/component/sjms/batch/BatchConsumerReconnectTest.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * 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.TimeUnit;
+
+import org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory;
+import org.apache.camel.CamelContext;
+import org.apache.camel.RoutesBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.component.sjms.SjmsComponent;
+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 org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.lang.String.format;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.BATCH_ROUTEBUILDER_MOCK_FINISH;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.createBatchRoute;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.getBatchBodiesAsString;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.getBatchExchanges;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.sendMessagesWithText;
+import static 
org.apache.camel.component.sjms.batch.BatchTestHelper.triggerConnectionFailure;
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+public class BatchConsumerReconnectTest extends JmsExclusiveTestSupport {
+
+    private static final String SJMS_QUEUE_NAME_TEMPLATE = 
"batch.consumer.%s.BatchConsumerReconnectTest";
+    private static final String ROUTE_ID_SESSION_TX = "tx";
+    private static final String ROUTE_ID_CLIENT_ACK_NO_TX = "no-tx-client-ack";
+    private static final String ROUTE_ID_AUTO_ACK_NO_TX = "no-tx-auto";
+
+    @RegisterExtension
+    public static ArtemisService service = 
ArtemisServiceFactory.createVMService();
+
+    private BatchTestHelper.CountingConnectionFactory countingFactory;
+
+    protected final Logger log = LoggerFactory.getLogger(getClass());
+
+    @Override
+    public ArtemisService getService() {
+        return service;
+    }
+
+    @Override
+    protected CamelContext createCamelContext() throws Exception {
+        addSjmsComponent = false;
+        CamelContext camelContext = super.createCamelContext();
+
+        ActiveMQConnectionFactory connectionFactory = new 
ActiveMQConnectionFactory(service.serviceAddress());
+        connectionFactory.setReconnectAttempts(0);
+
+        countingFactory = new 
BatchTestHelper.CountingConnectionFactory(connectionFactory);
+
+        SjmsComponent sjms = new SjmsComponent();
+        sjms.setConnectionFactory(countingFactory);
+        camelContext.addComponent("sjms", sjms);
+
+        return camelContext;
+    }
+
+    @Test
+    public void testReconnectAutoAcknowledgedNotTransacted() throws Exception {
+        final String queueName = format(SJMS_QUEUE_NAME_TEMPLATE, 
ROUTE_ID_AUTO_ACK_NO_TX);
+        final String endpointUri = "sjms:queue:" + queueName;
+
+        MockEndpoint mock = 
getMockEndpoint(format(BATCH_ROUTEBUILDER_MOCK_FINISH, 
ROUTE_ID_AUTO_ACK_NO_TX));
+        mock.expectedMessageCount(1);
+
+        sendMessagesWithText(template, endpointUri, 2, "Before!");
+
+        int connectionsBefore = countingFactory.getCreateCount();
+        triggerConnectionFailure(context, ROUTE_ID_AUTO_ACK_NO_TX);
+        await().atMost(30, TimeUnit.SECONDS)
+                .until(() -> countingFactory.getCreateCount() > 
connectionsBefore);
+
+        mock.assertIsSatisfied();
+        assertEquals(2, getBatchExchanges(mock.getExchanges().get(0)).size());
+        assertEquals(List.of("Before!", "Before!"), 
getBatchBodiesAsString(mock.getExchanges().get(0)));
+
+        mock.reset();
+
+        // test with an incomplete batch - to check timing
+        mock.expectedMessageCount(1);
+        mock.setResultWaitTime(15000);
+        sendMessagesWithText(template, endpointUri, 3, "After!");
+
+        mock.assertIsSatisfied();
+        assertEquals(3, getBatchExchanges(mock.getExchanges().get(0)).size());
+        assertEquals(List.of("After!", "After!", "After!"), 
getBatchBodiesAsString(mock.getExchanges().get(0)));
+    }
+
+    @Test
+    public void testSessionTransacted() throws Exception {
+        final String queueName = format(SJMS_QUEUE_NAME_TEMPLATE, 
ROUTE_ID_SESSION_TX);
+        final String endpointUri = "sjms:queue:" + queueName;
+
+        MockEndpoint mock = 
getMockEndpoint(format(BATCH_ROUTEBUILDER_MOCK_FINISH, ROUTE_ID_SESSION_TX));
+        mock.expectedMessageCount(0);
+
+        sendMessagesWithText(template, endpointUri, 2, "Before!");
+
+        int connectionsBefore = countingFactory.getCreateCount();
+        triggerConnectionFailure(context, ROUTE_ID_AUTO_ACK_NO_TX);

Review Comment:
   ⚠️ **Wrong route ID: testing reconnect on the wrong consumer.**
   
   `testSessionTransacted()` triggers `ROUTE_ID_AUTO_ACK_NO_TX` instead of 
`ROUTE_ID_SESSION_TX`. The transacted consumer is never disconnected, so 
transacted recovery is never exercised. False confidence.
   
   ```suggestion
           triggerConnectionFailure(context, ROUTE_ID_SESSION_TX);
   ```



##########
components/camel-sjms/src/main/java/org/apache/camel/component/sjms/consumer/BatchConsumerWorker.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * 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.consumer;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import jakarta.jms.JMSException;
+import jakarta.jms.Message;
+import jakarta.jms.MessageConsumer;
+import jakarta.jms.Session;
+
+import org.apache.camel.component.sjms.SjmsEndpoint;
+import org.apache.camel.component.sjms.jms.SessionAcknowledgementType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.camel.component.sjms.SjmsHelper.commitIfNeeded;
+import static org.apache.camel.component.sjms.SjmsHelper.rollbackIfNeeded;
+
+public class BatchConsumerWorker implements Runnable {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(BatchConsumerWorker.class);
+
+    private static final long JMS_CONSUMER_RECEIVE_WAKE_INTERVAL_TIMEOUT = 
1000L;
+    private static final long JMS_CONSUMER_RECEIVE_MIN_TIMEOUT = 100L;
+
+    private final SjmsEndpoint endpoint;
+    private final BatchEndpointMessageListener batchListener;
+    private final MessageConsumer consumer;
+    private final Session session;
+    private final AtomicBoolean running = new AtomicBoolean(true);
+    private volatile boolean jmsUnhealthy;
+
+    BatchConsumerWorker(SjmsEndpoint endpoint, BatchEndpointMessageListener 
batchListener,
+                        Session session, MessageConsumer consumer) {
+        this.endpoint = endpoint;
+        this.batchListener = batchListener;
+        this.session = session;
+        this.consumer = consumer;
+    }
+
+    void shutdown() {
+        LOG.debug("Shutdown requested");
+        running.set(false);
+    }
+
+    boolean isShutdownRequested() {
+        return !running.get();
+    }
+
+    void invalidate() {
+        jmsUnhealthy = true;
+        shutdown();
+    }
+
+    private boolean isRedeliverable() {
+        return endpoint.isTransacted()
+                || endpoint.getAcknowledgementMode() == 
SessionAcknowledgementType.CLIENT_ACKNOWLEDGE;
+    }
+
+    @Override
+    public void run() {
+        LOG.debug("run START");
+        int batchSize = endpoint.getBatchSize();
+        long batchInterval = endpoint.getBatchInterval();
+        List<Message> buffer = new ArrayList<>();
+        long batchStartTime = 0L;
+
+        try {
+            while (running.get()) {
+                long waitMillis
+                        = computeWaitMillis(buffer.isEmpty(), batchStartTime, 
batchInterval);
+
+                Message msg = consumer.receive(waitMillis);
+
+                if (msg != null) {
+                    if (buffer.isEmpty()) {
+                        batchStartTime = System.nanoTime();
+                    }
+                    buffer.add(msg);
+                }
+
+                boolean sizeReached = batchSize > 0 && buffer.size() >= 
batchSize;
+                boolean intervalElapsed = batchInterval > 0 && 
!buffer.isEmpty()
+                        && TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - 
batchStartTime) >= batchInterval;
+
+                if (sizeReached || intervalElapsed) {
+                    dispatchOrDiscard(buffer);
+                    buffer = new ArrayList<>();
+                }
+            }
+
+            if (!buffer.isEmpty()) {
+                dispatchOrDiscard(buffer); // graceful-stop drain
+            }
+        } catch (JMSException e) {
+            jmsUnhealthy = true;
+            if (!buffer.isEmpty()) {
+                dispatchOrDiscard(buffer);
+            }
+            throw new BatchConsumerWorkerException(e);
+        }
+        LOG.info("run STOP");
+    }
+
+    private void dispatchOrDiscard(List<Message> batch) {
+        if (jmsUnhealthy) {
+            if (isRedeliverable()) {
+                LOG.warn("JMS is unhealthy on {}: discarding {} buffered 
message(s); "
+                         + "unacknowledged/uncommitted, will be redelivered",
+                        endpoint.getEndpointUri(), batch.size());
+                return;
+            }
+            LOG.warn("JMS is unhealthy on {}: attempting best-effort dispatch 
of {} already-acknowledged "
+                     + "message(s) since they cannot be redelivered",
+                    endpoint.getEndpointUri(), batch.size());
+        }
+        onBatch(batch);
+    }
+
+    private void onBatch(List<Message> batch) {
+        try {
+            doOnBatch(batch);
+        } catch (Exception e) {
+            if (e instanceof JMSException jmsException) {
+                if (endpoint.getExceptionListener() != null) {
+                    endpoint.getExceptionListener().onException(jmsException);
+                }
+            } else {
+                batchListener.handleException(
+                        "Execution of JMS message listener failed. This 
exception is ignored.",
+                        e);
+            }

Review Comment:
   💡 **Silent drop when `exceptionListener` is null.**
   
   A `JMSException` from `commitIfNeeded()` or `rollbackIfNeeded()` inside 
`doOnBatch()` is only forwarded to `endpoint.getExceptionListener()`, which is 
null by default. When null, the exception is dropped with no log. The worker 
will attempt the next `receive()` which will fail and trigger recovery, so this 
is not a stuck-loop — but a commit failure with zero diagnostic trace is 
confusing in production.
   
   Add a warn in the null branch so operators see it:
   ```suggestion
               if (endpoint.getExceptionListener() != null) {
                       
endpoint.getExceptionListener().onException(jmsException);
                   } else {
                       LOG.warn("JMS exception on {} (no ExceptionListener 
configured); recovery will be attempted",
                               endpoint.getEndpointUri(), jmsException);
                   }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to