This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch camel-4.22.x
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/camel-4.22.x by this push:
new 7f3789e7d67a [backport camel-4.22.x] CAMEL-24523: Restart Paho
consumer after resubscribe failure (#30898)
7f3789e7d67a is described below
commit 7f3789e7d67ac641cb9ec31d4fd8e32913bddc89
Author: Guillaume Nodet <[email protected]>
AuthorDate: Mon Nov 30 09:34:19 2026 +0100
[backport camel-4.22.x] CAMEL-24523: Restart Paho consumer after
resubscribe failure (#30898)
* CAMEL-24523: camel-paho - restart the consumer route when resubscribe
fails after reconnect
* fix: fix broken backport - correct PahoConsumer.java structure for
camel-4.22.x
* fix: add missing test dependencies to camel-paho pom.xml
* CAMEL-24523: address review feedback
* CAMEL-24523: add PahoConsumerLifecycleTest from CAMEL-24465 backport
* docs: expand camel-paho upgrade note with restart-failure and
SupervisingRouteController info
Co-authored-by: Copilot <[email protected]>
---
components/camel-paho/pom.xml | 5 +
.../apache/camel/component/paho/PahoConsumer.java | 218 +++++++++++++-----
.../component/paho/PahoConsumerLifecycleTest.java | 158 +++++++++++++
.../component/paho/PahoResubscribeFailureTest.java | 250 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_22.adoc | 21 ++
5 files changed, 596 insertions(+), 56 deletions(-)
diff --git a/components/camel-paho/pom.xml b/components/camel-paho/pom.xml
index bcf4b9c75bb7..7c11e85de0a8 100644
--- a/components/camel-paho/pom.xml
+++ b/components/camel-paho/pom.xml
@@ -73,6 +73,11 @@
<version>${project.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
diff --git
a/components/camel-paho/src/main/java/org/apache/camel/component/paho/PahoConsumer.java
b/components/camel-paho/src/main/java/org/apache/camel/component/paho/PahoConsumer.java
index 4bde73ec28e8..6173e46f28b6 100644
---
a/components/camel-paho/src/main/java/org/apache/camel/component/paho/PahoConsumer.java
+++
b/components/camel-paho/src/main/java/org/apache/camel/component/paho/PahoConsumer.java
@@ -16,6 +16,9 @@
*/
package org.apache.camel.component.paho;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicBoolean;
+
import org.apache.camel.AsyncCallback;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
@@ -40,6 +43,7 @@ public class PahoConsumer extends DefaultConsumer {
private volatile String clientId;
private volatile boolean stopClient;
private volatile MqttConnectOptions connectOptions;
+ private final AtomicBoolean restarting = new AtomicBoolean(false);
public PahoConsumer(Endpoint endpoint, Processor processor) {
super(endpoint, processor);
@@ -57,81 +61,183 @@ public class PahoConsumer extends DefaultConsumer {
protected void doStart() throws Exception {
super.doStart();
- connectOptions =
PahoEndpoint.createMqttConnectOptions(getEndpoint().getConfiguration());
+ stopClient = client == null;
+ try {
+ connectOptions =
PahoEndpoint.createMqttConnectOptions(getEndpoint().getConfiguration());
- if (client == null) {
- clientId = getEndpoint().getConfiguration().getClientId();
- if (clientId == null) {
- clientId = "camel-" + MqttClient.generateClientId();
+ if (stopClient) {
+ clientId = getEndpoint().getConfiguration().getClientId();
+ if (clientId == null) {
+ clientId = "camel-" + MqttClient.generateClientId();
+ }
+ client = createClient();
+ LOG.debug("Connecting client: {} to broker: {}", clientId,
getEndpoint().getConfiguration().getBrokerUrl());
+ if (getEndpoint().getConfiguration().isManualAcksEnabled()) {
+ client.setManualAcks(true);
+ }
+ client.connect(connectOptions);
}
- stopClient = true;
- client = new MqttClient(
- getEndpoint().getConfiguration().getBrokerUrl(),
- clientId,
-
PahoEndpoint.createMqttClientPersistence(getEndpoint().getConfiguration()));
- LOG.debug("Connecting client: {} to broker: {}", clientId,
getEndpoint().getConfiguration().getBrokerUrl());
- if (getEndpoint().getConfiguration().isManualAcksEnabled()) {
- client.setManualAcks(true);
- }
- client.connect(connectOptions);
- }
+ MqttClient callbackClient = client;
+ boolean isOwnedClient = stopClient;
+ callbackClient.setCallback(new MqttCallbackExtended() {
+
+ @Override
+ public void connectComplete(boolean reconnect, String
serverURI) {
+ if (reconnect && isRunAllowed() && callbackClient ==
client) {
+ try {
+ callbackClient.subscribe(getEndpoint().getTopic(),
getEndpoint().getConfiguration().getQos());
+ } catch (MqttException e) {
+ if (isOwnedClient) {
+ LOG.warn("MQTT resubscribe failed on
reconnect, restarting route for recovery: {}",
+ e.getMessage(), e);
+ restartRouteAsync();
+ } else {
+ LOG.error(
+ "MQTT resubscribe failed on reconnect
with externally provided client,"
+ + " route will not be
auto-restarted: {}",
+ e.getMessage(), e);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void connectionLost(Throwable cause) {
+ LOG.debug("MQTT broker connection lost due {}",
cause.getMessage(), cause);
+ }
+
+ @Override
+ public void messageArrived(String topic, MqttMessage message)
throws Exception {
+ LOG.debug("Message arrived on topic: {} -> {}", topic,
message);
+ Exchange exchange = createExchange(message, topic);
+
+ // use default consumer callback
+ AsyncCallback cb = defaultConsumerCallback(exchange, true);
+ getAsyncProcessor().process(exchange, cb);
+ }
- client.setCallback(new MqttCallbackExtended() {
+ @Override
+ public void deliveryComplete(IMqttDeliveryToken token) {
+ LOG.debug("Delivery complete. Token: {}", token);
+ }
+ });
- @Override
- public void connectComplete(boolean reconnect, String serverURI) {
- if (reconnect) {
+ LOG.debug("Subscribing client: {} to topic: {}", clientId,
getEndpoint().getTopic());
+ callbackClient.subscribe(getEndpoint().getTopic(),
getEndpoint().getConfiguration().getQos());
+ } catch (Exception startException) {
+ MqttClient ownedClient = stopClient ? client : null;
+ if (ownedClient != null) {
+ client = null;
+ stopClient = false;
+ if (ownedClient.isConnected()) {
try {
- client.subscribe(getEndpoint().getTopic(),
getEndpoint().getConfiguration().getQos());
- } catch (MqttException e) {
- LOG.error("MQTT resubscribe failed {}",
e.getMessage(), e);
+ ownedClient.disconnect();
+ } catch (Exception disconnectException) {
+ startException.addSuppressed(disconnectException);
}
}
+ closeOwnedClient(ownedClient, startException);
}
+ throw startException;
+ }
+ }
- @Override
- public void connectionLost(Throwable cause) {
- LOG.debug("MQTT broker connection lost due {}",
cause.getMessage(), cause);
+ MqttClient createClient() throws MqttException {
+ return new MqttClient(
+ getEndpoint().getConfiguration().getBrokerUrl(),
+ clientId,
+
PahoEndpoint.createMqttClientPersistence(getEndpoint().getConfiguration()));
+ }
+
+ private void restartRouteAsync() {
+ if (!restarting.compareAndSet(false, true)) {
+ LOG.debug("Route restart already in progress, skipping duplicate
restart");
+ return;
+ }
+ String threadName = "Paho-RestartRoute-" + getRouteId();
+ ExecutorService executor = null;
+ try {
+ executor
+ =
getEndpoint().getCamelContext().getExecutorServiceManager().newSingleThreadExecutor(this,
threadName);
+ ExecutorService restartExecutor = executor;
+ restartExecutor.submit(() -> {
+ try {
+ if (!isRunAllowed() ||
!getEndpoint().getCamelContext().isRunAllowed()) {
+ LOG.debug("Consumer or Camel context is stopping,
skipping route restart");
+ return;
+ }
+ String routeId = getRouteId();
+ LOG.info("Stopping route {} for restart after resubscribe
failure", routeId);
+
getEndpoint().getCamelContext().getRouteController().stopRoute(routeId);
+ if (!getEndpoint().getCamelContext().isRunAllowed()) {
+ LOG.debug("Camel context is stopping, not restarting
route {}", routeId);
+ return;
+ }
+ LOG.info("Restarting route {}", routeId);
+
getEndpoint().getCamelContext().getRouteController().startRoute(routeId);
+ } catch (Exception e) {
+ getExceptionHandler().handleException(
+ "Failed to restart route after resubscribe
failure", e);
+ } finally {
+ restarting.set(false);
+
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(restartExecutor);
+ }
+ });
+ } catch (RuntimeException e) {
+ restarting.set(false);
+ if (executor != null) {
+
getEndpoint().getCamelContext().getExecutorServiceManager().shutdownNow(executor);
}
+ getExceptionHandler().handleException(
+ "Failed to schedule route restart after resubscribe
failure", e);
+ }
+ }
- @Override
- public void messageArrived(String topic, MqttMessage message)
throws Exception {
- LOG.debug("Message arrived on topic: {} -> {}", topic,
message);
- Exchange exchange = createExchange(message, topic);
+ @Override
+ protected void doStop() throws Exception {
+ MqttClient ownedClient = stopClient ? client : null;
+ Exception stopException = null;
+ try {
+ super.doStop();
- // use default consumer callback
- AsyncCallback cb = defaultConsumerCallback(exchange, true);
- getAsyncProcessor().process(exchange, cb);
+ if (ownedClient != null && ownedClient.isConnected()) {
+ String topic = getEndpoint().getTopic();
+ // only unsubscribe if we are not durable
+ if (getEndpoint().getConfiguration().isCleanSession()) {
+ LOG.debug("Unsubscribing client: {} from topic: {}",
clientId, topic);
+ ownedClient.unsubscribe(topic);
+ } else {
+ LOG.debug("Client: {} is durable so will not unsubscribe
from topic: {}", clientId, topic);
+ }
+ LOG.debug("Disconnecting client: {} from broker: {}", clientId,
+ getEndpoint().getConfiguration().getBrokerUrl());
+ ownedClient.disconnect();
}
-
- @Override
- public void deliveryComplete(IMqttDeliveryToken token) {
- LOG.debug("Delivery complete. Token: {}", token);
+ } catch (Exception e) {
+ stopException = e;
+ } finally {
+ client = null;
+ stopClient = false;
+ if (ownedClient != null) {
+ stopException = closeOwnedClient(ownedClient, stopException);
}
- });
-
- LOG.debug("Subscribing client: {} to topic: {}", clientId,
getEndpoint().getTopic());
- client.subscribe(getEndpoint().getTopic(),
getEndpoint().getConfiguration().getQos());
+ }
+ if (stopException != null) {
+ throw stopException;
+ }
}
- @Override
- protected void doStop() throws Exception {
- super.doStop();
-
- if (stopClient && client != null && client.isConnected()) {
- String topic = getEndpoint().getTopic();
- // only unsubscribe if we are not durable
- if (getEndpoint().getConfiguration().isCleanSession()) {
- LOG.debug("Unsubscribing client: {} from topic: {}", clientId,
topic);
- client.unsubscribe(topic);
- } else {
- LOG.debug("Client: {} is durable so will not unsubscribe from
topic: {}", clientId, topic);
+ private Exception closeOwnedClient(MqttClient ownedClient, Exception
primaryException) {
+ try {
+ ownedClient.close(true);
+ } catch (Exception closeException) {
+ if (primaryException == null) {
+ return closeException;
}
- LOG.debug("Disconnecting client: {} from broker: {}", clientId,
getEndpoint().getConfiguration().getBrokerUrl());
- client.disconnect();
+ primaryException.addSuppressed(closeException);
}
- client = null;
+ return primaryException;
}
@Override
diff --git
a/components/camel-paho/src/test/java/org/apache/camel/component/paho/PahoConsumerLifecycleTest.java
b/components/camel-paho/src/test/java/org/apache/camel/component/paho/PahoConsumerLifecycleTest.java
new file mode 100644
index 000000000000..05ccce1025a0
--- /dev/null
+++
b/components/camel-paho/src/test/java/org/apache/camel/component/paho/PahoConsumerLifecycleTest.java
@@ -0,0 +1,158 @@
+/*
+ * 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.paho;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.ExtendedCamelContext;
+import org.apache.camel.Processor;
+import org.apache.camel.spi.ExchangeFactory;
+import org.eclipse.paho.client.mqttv3.MqttClient;
+import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
+import org.eclipse.paho.client.mqttv3.MqttException;
+import org.junit.jupiter.api.Test;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.catchThrowableOfType;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class PahoConsumerLifecycleTest {
+
+ @Test
+ void failedStartForceClosesOwnedClient() throws Exception {
+ MqttClient client = mock(MqttClient.class);
+ MqttException connectException = new
MqttException(MqttException.REASON_CODE_CLIENT_EXCEPTION);
+
doThrow(connectException).when(client).connect(any(MqttConnectOptions.class));
+ PahoConsumer consumer = createConsumer(new PahoConfiguration(),
client);
+
+ MqttException thrown = catchThrowableOfType(MqttException.class,
consumer::doStart);
+
+ assertThat(thrown).isSameAs(connectException);
+ verify(client).close(true);
+ }
+
+ @Test
+ void failedStartSuppressesCloseFailure() throws Exception {
+ MqttClient client = mock(MqttClient.class);
+ MqttException connectException = new
MqttException(MqttException.REASON_CODE_CLIENT_EXCEPTION);
+ MqttException closeException = new
MqttException(MqttException.REASON_CODE_CLIENT_DISCONNECTING);
+
doThrow(connectException).when(client).connect(any(MqttConnectOptions.class));
+ doThrow(closeException).when(client).close(true);
+ PahoConsumer consumer = createConsumer(new PahoConfiguration(),
client);
+
+ MqttException thrown = catchThrowableOfType(MqttException.class,
consumer::doStart);
+
+ assertThat(thrown).isSameAs(connectException);
+ assertThat(thrown.getSuppressed()).containsExactly(closeException);
+ }
+
+ @Test
+ void failedStartAfterConnectDisconnectsAndClosesOwnedClient() throws
Exception {
+ MqttClient client = mock(MqttClient.class);
+ MqttException subscribeException = new
MqttException(MqttException.REASON_CODE_CLIENT_EXCEPTION);
+ PahoConfiguration configuration = new PahoConfiguration();
+ when(client.isConnected()).thenReturn(true);
+ doThrow(subscribeException).when(client).subscribe("test",
configuration.getQos());
+ PahoConsumer consumer = createConsumer(configuration, client);
+
+ MqttException thrown = catchThrowableOfType(MqttException.class,
consumer::doStart);
+
+ assertThat(thrown).isSameAs(subscribeException);
+ verify(client).disconnect();
+ verify(client).close(true);
+ }
+
+ @Test
+ void stopForceClosesOwnedClientWhenDisconnected() throws Exception {
+ MqttClient client = mock(MqttClient.class);
+ PahoConsumer consumer = createConsumer(new PahoConfiguration(),
client);
+ consumer.doStart();
+
+ consumer.doStop();
+
+ verify(client, never()).disconnect();
+ verify(client).close(true);
+ }
+
+ @Test
+ void failedStopSuppressesCloseFailure() throws Exception {
+ MqttClient client = mock(MqttClient.class);
+ MqttException disconnectException = new
MqttException(MqttException.REASON_CODE_CLIENT_DISCONNECTING);
+ MqttException closeException = new
MqttException(MqttException.REASON_CODE_CLIENT_EXCEPTION);
+ when(client.isConnected()).thenReturn(true);
+ doThrow(disconnectException).when(client).disconnect();
+ doThrow(closeException).when(client).close(true);
+ PahoConfiguration configuration = new PahoConfiguration();
+ configuration.setCleanSession(false);
+ PahoConsumer consumer = createConsumer(configuration, client);
+ consumer.doStart();
+
+ MqttException thrown = catchThrowableOfType(MqttException.class,
consumer::doStop);
+
+ assertThat(thrown).isSameAs(disconnectException);
+ assertThat(thrown.getSuppressed()).containsExactly(closeException);
+ }
+
+ @Test
+ void durableConnectedClientDisconnectsAndClosesWithoutUnsubscribe() throws
Exception {
+ MqttClient client = mock(MqttClient.class);
+ when(client.isConnected()).thenReturn(true);
+ PahoConfiguration configuration = new PahoConfiguration();
+ configuration.setCleanSession(false);
+ PahoConsumer consumer = createConsumer(configuration, client);
+ consumer.doStart();
+
+ consumer.doStop();
+
+ verify(client, never()).unsubscribe("test");
+ verify(client).disconnect();
+ verify(client).close(true);
+ }
+
+ @Test
+ void sharedClientIsNotClosed() throws Exception {
+ MqttClient client = mock(MqttClient.class);
+ PahoConsumer consumer = createConsumer(new PahoConfiguration(),
mock(MqttClient.class));
+ consumer.setClient(client);
+
+ consumer.doStart();
+ consumer.doStop();
+
+ verify(client, never()).close(true);
+ }
+
+ private static PahoConsumer createConsumer(PahoConfiguration
configuration, MqttClient createdClient) {
+ CamelContext context = mock(CamelContext.class);
+ ExtendedCamelContext extension = mock(ExtendedCamelContext.class);
+ ExchangeFactory exchangeFactory = mock(ExchangeFactory.class);
+ when(context.getCamelContextExtension()).thenReturn(extension);
+ when(extension.getExchangeFactory()).thenReturn(exchangeFactory);
+
when(exchangeFactory.newExchangeFactory(any())).thenReturn(exchangeFactory);
+ PahoEndpoint endpoint = new PahoEndpoint(
+ "paho:test", "test", new PahoComponent(context),
configuration);
+ return new PahoConsumer(endpoint, mock(Processor.class)) {
+ @Override
+ MqttClient createClient() {
+ return createdClient;
+ }
+ };
+ }
+}
diff --git
a/components/camel-paho/src/test/java/org/apache/camel/component/paho/PahoResubscribeFailureTest.java
b/components/camel-paho/src/test/java/org/apache/camel/component/paho/PahoResubscribeFailureTest.java
new file mode 100644
index 000000000000..612304586bc8
--- /dev/null
+++
b/components/camel-paho/src/test/java/org/apache/camel/component/paho/PahoResubscribeFailureTest.java
@@ -0,0 +1,250 @@
+/*
+ * 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.paho;
+
+import java.util.ArrayDeque;
+import java.util.Arrays;
+import java.util.Deque;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.CyclicBarrier;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.Consumer;
+import org.apache.camel.Endpoint;
+import org.apache.camel.Processor;
+import org.apache.camel.ServiceStatus;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
+import org.eclipse.paho.client.mqttv3.MqttClient;
+import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
+import org.eclipse.paho.client.mqttv3.MqttException;
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.awaitility.Awaitility.await;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class PahoResubscribeFailureTest extends CamelTestSupport {
+
+ private static final String ROUTE_ID = "mqtt-consumer";
+
+ @Override
+ public boolean isUseAdviceWith() {
+ return true;
+ }
+
+ @Override
+ protected RouteBuilder createRouteBuilder() {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ }
+ };
+ }
+
+ @Test
+ void successfulResubscribeOnReconnectShouldKeepRouteStarted() throws
Exception {
+ MqttClient client = mock(MqttClient.class);
+ MqttCallbackExtended callback = startRouteWithExternalClient(client);
+
+ callback.connectComplete(true, "tcp://localhost:1883");
+
+ verify(client, times(2)).subscribe("test", 2);
+
assertThat(context.getRouteController().getRouteStatus(ROUTE_ID)).isEqualTo(ServiceStatus.Started);
+ }
+
+ @Test
+ void
resubscribeFailureWithOwnedClientShouldRestartRouteAndReplaceOwnedClient()
throws Exception {
+ MqttClient failedClient = connectedClient();
+ MqttClient recoveredClient = connectedClient();
+ AtomicInteger createdClients = new AtomicInteger();
+ MqttCallbackExtended callback =
startRouteWithOwnedClients(createdClients, failedClient, recoveredClient);
+ doThrow(new MqttException(MqttException.REASON_CODE_CLIENT_EXCEPTION))
+ .when(failedClient).subscribe(anyString(), anyInt());
+
+ callback.connectComplete(true, "tcp://localhost:1883");
+
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
+
assertThat(context.getRouteController().getRouteStatus(ROUTE_ID)).isEqualTo(ServiceStatus.Started);
+ assertThat(createdClients).hasValue(2);
+ verify(failedClient).close(true);
+ verify(recoveredClient).connect(any(MqttConnectOptions.class));
+ verify(recoveredClient).subscribe("test", 2);
+ verify(recoveredClient, never()).close(true);
+ });
+
+ callback.connectComplete(true, "tcp://localhost:1883");
+
+ assertThat(createdClients).hasValue(2);
+ verify(failedClient, times(2)).subscribe("test", 2);
+ }
+
+ @Test
+ void resubscribeFailureWithExternalClientShouldNotRestartOrCloseClient()
throws Exception {
+ MqttClient client = connectedClient();
+ MqttCallbackExtended callback = startRouteWithExternalClient(client);
+ doThrow(new MqttException(MqttException.REASON_CODE_CLIENT_EXCEPTION))
+ .when(client).subscribe(anyString(), anyInt());
+
+ callback.connectComplete(true, "tcp://localhost:1883");
+
+
assertThat(context.getRouteController().getRouteStatus(ROUTE_ID)).isEqualTo(ServiceStatus.Started);
+ verify(client, times(2)).subscribe("test", 2);
+ verify(client, never()).connect(any(MqttConnectOptions.class));
+ verify(client, never()).close(true);
+ }
+
+ @Test
+ void concurrentReconnectFailuresShouldTriggerOnlyOneRestart() throws
Exception {
+ MqttClient failedClient = connectedClient();
+ MqttClient recoveredClient = connectedClient();
+ AtomicInteger createdClients = new AtomicInteger();
+ MqttCallbackExtended callback =
startRouteWithOwnedClients(createdClients, failedClient, recoveredClient);
+ CyclicBarrier subscribeBarrier = new CyclicBarrier(2);
+ CountDownLatch closeEntered = new CountDownLatch(1);
+ CountDownLatch releaseClose = new CountDownLatch(1);
+ doAnswer(invocation -> {
+ subscribeBarrier.await(5, TimeUnit.SECONDS);
+ throw new
MqttException(MqttException.REASON_CODE_CLIENT_EXCEPTION);
+ }).when(failedClient).subscribe(anyString(), anyInt());
+ doAnswer(invocation -> {
+ closeEntered.countDown();
+ assertThat(releaseClose.await(5, TimeUnit.SECONDS)).isTrue();
+ return null;
+ }).when(failedClient).close(true);
+
+ CompletableFuture<Void> first = CompletableFuture.runAsync(
+ () -> callback.connectComplete(true, "tcp://localhost:1883"));
+ CompletableFuture<Void> second = CompletableFuture.runAsync(
+ () -> callback.connectComplete(true, "tcp://localhost:1883"));
+
+ assertThat(closeEntered.await(5, TimeUnit.SECONDS)).isTrue();
+ first.get(5, TimeUnit.SECONDS);
+ second.get(5, TimeUnit.SECONDS);
+ releaseClose.countDown();
+
+ await().atMost(10, TimeUnit.SECONDS).untilAsserted(() -> {
+
assertThat(context.getRouteController().getRouteStatus(ROUTE_ID)).isEqualTo(ServiceStatus.Started);
+ assertThat(createdClients).hasValue(2);
+ verify(failedClient).close(true);
+ verify(recoveredClient).connect(any(MqttConnectOptions.class));
+ });
+ }
+
+ @Test
+ void reconnectCallbackAfterShutdownShouldNotResubscribeOrRestart() throws
Exception {
+ MqttClient client = connectedClient();
+ AtomicInteger createdClients = new AtomicInteger();
+ MqttCallbackExtended callback =
startRouteWithOwnedClients(createdClients, client);
+
+ context.getRouteController().stopRoute(ROUTE_ID);
+ callback.connectComplete(true, "tcp://localhost:1883");
+
+
assertThat(context.getRouteController().getRouteStatus(ROUTE_ID)).isEqualTo(ServiceStatus.Stopped);
+ assertThat(createdClients).hasValue(1);
+ verify(client, times(1)).subscribe("test", 2);
+ verify(client).close(true);
+ }
+
+ @Test
+ void initialConnectShouldNotResubscribe() throws Exception {
+ MqttClient client = mock(MqttClient.class);
+ MqttCallbackExtended callback = startRouteWithExternalClient(client);
+
+ callback.connectComplete(false, "tcp://localhost:1883");
+
+ verify(client, times(1)).subscribe("test", 2);
+
assertThat(context.getRouteController().getRouteStatus(ROUTE_ID)).isEqualTo(ServiceStatus.Started);
+ }
+
+ private MqttCallbackExtended startRouteWithExternalClient(MqttClient
client) throws Exception {
+ PahoEndpoint endpoint = context.getEndpoint(
+ "paho:test?brokerUrl=tcp://localhost:1883",
PahoEndpoint.class);
+ endpoint.setClient(client);
+
context.addRoutes(createRoute("paho:test?brokerUrl=tcp://localhost:1883"));
+ context.start();
+ return captureCallback(client);
+ }
+
+ private MqttCallbackExtended startRouteWithOwnedClients(
+ AtomicInteger createdClients, MqttClient... clients)
+ throws Exception {
+ PahoConfiguration configuration = new PahoConfiguration();
+ configuration.setAutomaticReconnect(true);
+ configuration.setBrokerUrl("tcp://localhost:1883");
+ Deque<MqttClient> availableClients = new
ArrayDeque<>(Arrays.asList(clients));
+ PahoComponent component = new PahoComponent(context) {
+ @Override
+ protected Endpoint createEndpoint(String uri, String remaining,
Map<String, Object> parameters) {
+ PahoEndpoint endpoint = new PahoEndpoint(uri, remaining, this,
configuration.copy()) {
+ @Override
+ public Consumer createConsumer(Processor processor) throws
Exception {
+ PahoConsumer consumer = new PahoConsumer(this,
processor) {
+ @Override
+ MqttClient createClient() {
+ createdClients.incrementAndGet();
+ return availableClients.removeFirst();
+ }
+ };
+ configureConsumer(consumer);
+ return consumer;
+ }
+ };
+ return endpoint;
+ }
+ };
+ context.addComponent("paho-owned", component);
+ context.addRoutes(createRoute("paho-owned:test"));
+ context.start();
+ return captureCallback(clients[0]);
+ }
+
+ private RouteBuilder createRoute(String uri) {
+ return new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(uri).id(ROUTE_ID).to("mock:result");
+ }
+ };
+ }
+
+ private MqttCallbackExtended captureCallback(MqttClient client) throws
Exception {
+ ArgumentCaptor<MqttCallbackExtended> callbackCaptor =
ArgumentCaptor.forClass(MqttCallbackExtended.class);
+ verify(client).setCallback(callbackCaptor.capture());
+ return callbackCaptor.getValue();
+ }
+
+ private static MqttClient connectedClient() {
+ MqttClient client = mock(MqttClient.class);
+ when(client.isConnected()).thenReturn(true);
+ return client;
+ }
+}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc
index 7ab9b1821e45..a508283900f6 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_22.adoc
@@ -13,6 +13,27 @@ See the xref:camel-upgrade-recipes-tool.adoc[documentation]
page for details.
== Upgrading from 4.22.3 to 4.22.4
+=== camel-paho - consumer restarts route after resubscribe failure on reconnect
+
+When `automaticReconnect=true` and the MQTT broker reconnects, the consumer
now restarts the route
+if the post-reconnect `subscribe()` call fails. Previously a failed
resubscription (for example,
+when the broker does not send a SUBACK and the Paho keepAlive timer triggers
`MqttException 32000`)
+was only logged at ERROR level with no recovery action, leaving the route in
`Started` state while
+silently consuming no messages (zombie state).
+
+If the resubscribe fails and the consumer owns the MQTT client (the default),
it automatically stops
+and restarts the route to force a clean reconnect. If the restart also fails
(for example, the broker
+is still unavailable), the route is left in `Stopped` state. Routes using a
user-provided client are
+not affected by this change. Configuring Camel's `SupervisingRouteController`
allows the framework to
+keep retrying with exponential backoff until the broker recovers:
+
+[source,properties]
+----
+camel.routeController.enabled = true
+camel.routeController.backOffDelay = 2000
+camel.routeController.backOffMaxDelay = 60000
+----
+
=== Weighted Load Balancer EIP
The distribution ratios of the weighted load balancer are now validated when
the route starts. A negative ratio,