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 4af41b994c55 CAMEL-27383: camel-vertx-mqtt - the consumer after a
restart on a shared connection, with a kept session, and when a redelivered
message fails again (#30701)
4af41b994c55 is described below
commit 4af41b994c55f3f93bf3d2a5e9aeed1d173de56a
Author: allthingssecurity <[email protected]>
AuthorDate: Tue Nov 24 13:16:33 2026 +0530
CAMEL-27383: camel-vertx-mqtt - the consumer after a restart on a shared
connection, with a kept session, and when a redelivered message fails again
(#30701)
- A consumer that stops pauses the client. When a producer of the same
endpoint keeps the connection, nothing resumed it: the restarted consumer
received nothing, the producer's QoS 1 and 2 publishes failed with the
ack timeout, and the keep alive dropped the connection again and again.
The consumer now resumes the connection once it has unsubscribed, when
a producer still holds it; a connection that stops with the consumer
stays paused, so that the messages waiting unread are not acknowledged.
- The consumer subscribed only after the connection had connected, so the
messages a session the broker kept sends right after the CONNACK found no
handler and were dropped (acknowledged with automatic acknowledgements,
left in flight with manual ones). Always so without automaticReconnect. A
connection the consumer starts now gets the subscription before it
connects.
- A failed message is redelivered by closing the connection once the
pending exchanges are done, but only the client of the first failure was
kept. When that was an earlier connection, a copy that failed again on
the current connection was not delivered again until the connection
dropped. The consumer now keeps every client a failed message arrived on,
and closes when one of them is the current client.
Found with a TLA+ model.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../component/vertx/mqtt/VertxMqttConnection.java | 20 +-
.../component/vertx/mqtt/VertxMqttConsumer.java | 52 ++--
.../component/vertx/mqtt/VertxMqttEndpoint.java | 28 ++-
.../vertx/mqtt/VertxMqttConsumerSessionTest.java | 277 +++++++++++++++++++++
4 files changed, 355 insertions(+), 22 deletions(-)
diff --git
a/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttConnection.java
b/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttConnection.java
index 4e36256d81cf..1b8b61903a42 100644
---
a/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttConnection.java
+++
b/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttConnection.java
@@ -465,6 +465,17 @@ final class VertxMqttConnection {
* @param handler called on the context for every message the broker sends
*/
void subscribe(final String filter, final int qos, final MessageHandler
handler) {
+ synchronized (this) {
+ if (context == null) {
+ // Not started yet: the first connect subscribes, and the
handler is there before the CONNACK, after
+ // which a session the broker kept sends the messages it holds
at once. start() runs the connect on
+ // the context after it took this lock
+ subscription = filter;
+ subscriptionQos = qos;
+ messageHandler = handler;
+ return;
+ }
+ }
run(() -> {
subscription = filter;
subscriptionQos = qos;
@@ -546,15 +557,18 @@ final class VertxMqttConnection {
/**
* Closes the connection without acknowledging a message, so that the
broker delivers it again after the reconnect,
* from the session it keeps. Needs automatic reconnect, does nothing
without it.
+ *
+ * @param receivers the clients the failed messages arrived on: only a
failure on the current client needs the
+ * close, a message of an earlier connection comes again
on the current one from the session
*/
- void redeliver(final MqttClient receiver) {
+ void redeliver(final List<MqttClient> receivers) {
run(() -> {
- if (receiver == client && connected && reconnector != null &&
!redelivering) {
+ if (connected && client != null && receivers.contains(client) &&
reconnector != null && !redelivering) {
redelivering = true;
LOG.warn("Closing the connection to the MQTT broker {}, so
that it delivers the messages whose exchange"
+ " failed again. A message that fails every time
comes back after every reconnect",
broker);
- receiver.disconnect();
+ client.disconnect();
}
});
}
diff --git
a/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttConsumer.java
b/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttConsumer.java
index cd09c76557d6..410b840e407e 100644
---
a/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttConsumer.java
+++
b/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttConsumer.java
@@ -16,6 +16,8 @@
*/
package org.apache.camel.component.vertx.mqtt;
+import java.util.ArrayList;
+import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
@@ -59,8 +61,9 @@ public class VertxMqttConsumer extends DefaultConsumer
implements ShutdownAware
private int pending;
private boolean paused;
private boolean draining;
- // A failed exchange asked for a reconnect, made once the exchanges
already received are done and acknowledged
- private MqttClient redeliveryFrom;
+ // Failed exchanges asked for a reconnect, made once the exchanges already
received are done and acknowledged: the
+ // clients their messages arrived on, as the reconnect is only needed when
one of them is the current client
+ private final List<MqttClient> redeliveryFrom = new ArrayList<>();
public VertxMqttConsumer(VertxMqttEndpoint endpoint, Processor processor) {
super(endpoint, processor);
@@ -86,16 +89,25 @@ public class VertxMqttConsumer extends DefaultConsumer
implements ShutdownAware
pending = 0;
paused = false;
draining = false;
- redeliveryFrom = null;
+ redeliveryFrom.clear();
}
// A pool of its own for every consumer: a shared worker executor of
the same name shares its threads
// A route may take long: no blocked thread warnings of Vert.x for the
worker
worker =
getEndpoint().getComponent().getVertx().createSharedWorkerExecutor(
"VertxMqttConsumer[%s]@%x".formatted(getEndpoint().getTopic(),
System.identityHashCode(this)), 1,
Long.MAX_VALUE, TimeUnit.NANOSECONDS);
- connection = getEndpoint().acquireConnection();
+ // Subscribed before a connection this consumer starts connects: a
session the broker kept sends the messages
+ // it holds right after the CONNACK, and they need the handler (and
this consumer the connection) by then
+ try {
+ getEndpoint().acquireConnection(acquired -> {
+ connection = acquired;
+ acquired.subscribe(getEndpoint().getTopic(),
getEndpoint().getConfiguration().getQos(), this::received);
+ });
+ } catch (Exception e) {
+ connection = null;
+ throw e;
+ }
connection.addFailureListener(failureListener);
- connection.subscribe(getEndpoint().getTopic(),
getEndpoint().getConfiguration().getQos(), this::received);
}
@Override
@@ -109,7 +121,13 @@ public class VertxMqttConsumer extends DefaultConsumer
implements ShutdownAware
// A session the broker keeps (no clean start) keeps the
subscription, messages wait there meanwhile
running.unsubscribe(getEndpoint().getConfiguration().isCleanStart());
connection = null;
- getEndpoint().releaseConnection();
+ // A producer of the endpoint may keep the connection: it must
read again, for its acknowledgements and the
+ // keep alive, and for a consumer started again on it. A
connection that stops with this consumer stays
+ // paused: read again, it would acknowledge and drop the messages
that wait unread, which a session the
+ // broker keeps (no clean start) delivers again after the next
connect
+ if (getEndpoint().releaseConnection()) {
+ running.pause(false);
+ }
}
final WorkerExecutor stopping = worker;
worker = null;
@@ -208,17 +226,17 @@ public class VertxMqttConsumer extends DefaultConsumer
implements ShutdownAware
if (running != null) {
running.pause(true);
}
- } else if (paused && !draining && redeliveryFrom == null && pending <=
maxPending / 2) {
+ } else if (paused && !draining && redeliveryFrom.isEmpty() && pending
<= maxPending / 2) {
paused = false;
if (running != null) {
running.pause(false);
}
}
if (pending == 0) {
- if (redeliveryFrom != null && running != null && !draining) {
+ if (!redeliveryFrom.isEmpty() && running != null && !draining) {
// Everything received before is done: close for the
redelivery, and read again on the next connection
- running.redeliver(redeliveryFrom);
- redeliveryFrom = null;
+ running.redeliver(List.copyOf(redeliveryFrom));
+ redeliveryFrom.clear();
paused = false;
running.pause(false);
}
@@ -249,12 +267,14 @@ public class VertxMqttConsumer extends DefaultConsumer
implements ShutdownAware
* deliver those again as well.
*/
private synchronized void requestRedelivery(VertxMqttConnection running,
MqttClient receiver) {
- if (redeliveryFrom == null) {
- redeliveryFrom = receiver;
- if (!paused) {
- paused = true;
- running.pause(true);
- }
+ // Every receiver, not only the first: a message that failed on an
earlier connection comes again on the
+ // current one, and when that copy fails too, the close has to happen
on the current client
+ if (!redeliveryFrom.contains(receiver)) {
+ redeliveryFrom.add(receiver);
+ }
+ if (!paused) {
+ paused = true;
+ running.pause(true);
}
}
diff --git
a/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttEndpoint.java
b/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttEndpoint.java
index 96d89ac6adf9..26db63cc0a84 100644
---
a/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttEndpoint.java
+++
b/components/camel-vertx/camel-vertx-mqtt/src/main/java/org/apache/camel/component/vertx/mqtt/VertxMqttEndpoint.java
@@ -16,11 +16,12 @@
*/
package org.apache.camel.component.vertx.mqtt;
+import java.util.function.Consumer;
+
import io.vertx.core.buffer.Buffer;
import io.vertx.mqtt.MqttClientOptions;
import io.vertx.mqtt.MqttClientWillOptions;
import org.apache.camel.Category;
-import org.apache.camel.Consumer;
import org.apache.camel.Processor;
import org.apache.camel.Producer;
import org.apache.camel.component.vertx.common.VertxHelper;
@@ -89,7 +90,7 @@ public class VertxMqttEndpoint extends DefaultEndpoint
implements EndpointServic
}
@Override
- public Consumer createConsumer(Processor processor) throws Exception {
+ public org.apache.camel.Consumer createConsumer(Processor processor)
throws Exception {
final VertxMqttConsumer consumer = new VertxMqttConsumer(this,
processor);
configureConsumer(consumer);
return consumer;
@@ -102,12 +103,30 @@ public class VertxMqttEndpoint extends DefaultEndpoint
implements EndpointServic
* @return the started connection
*/
synchronized VertxMqttConnection acquireConnection() throws Exception {
+ return acquireConnection(null);
+ }
+
+ /**
+ * Takes the connection of this endpoint, as {@link #acquireConnection()}.
+ *
+ * @param user given the connection before it is started, when this call
creates it, or else the started one: a
+ * consumer subscribes there, so that the messages a session
the broker kept sends right after the
+ * CONNACK find their handler
+ * @return the started connection
+ */
+ synchronized VertxMqttConnection acquireConnection(final
Consumer<VertxMqttConnection> user)
+ throws Exception {
if (connection == null) {
final VertxMqttConnection created = new VertxMqttConnection(
getComponent().getVertx(), broker,
createClientOptions(), configuration);
+ if (user != null) {
+ user.accept(created);
+ }
created.start();
connection = created;
+ } else if (user != null) {
+ user.accept(connection);
}
connectionUsers++;
return connection;
@@ -115,12 +134,15 @@ public class VertxMqttEndpoint extends DefaultEndpoint
implements EndpointServic
/**
* Gives back the connection taken with {@link #acquireConnection()},
stopping it with its last user.
+ *
+ * @return whether another user still holds the connection, which then
keeps running
*/
- synchronized void releaseConnection() {
+ synchronized boolean releaseConnection() {
if (connectionUsers > 0 && --connectionUsers == 0 && connection !=
null) {
connection.stop();
connection = null;
}
+ return connectionUsers > 0;
}
@Override
diff --git
a/components/camel-vertx/camel-vertx-mqtt/src/test/java/org/apache/camel/component/vertx/mqtt/VertxMqttConsumerSessionTest.java
b/components/camel-vertx/camel-vertx-mqtt/src/test/java/org/apache/camel/component/vertx/mqtt/VertxMqttConsumerSessionTest.java
new file mode 100644
index 000000000000..a0da974fd92b
--- /dev/null
+++
b/components/camel-vertx/camel-vertx-mqtt/src/test/java/org/apache/camel/component/vertx/mqtt/VertxMqttConsumerSessionTest.java
@@ -0,0 +1,277 @@
+/*
+ * 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.vertx.mqtt;
+
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.List;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import io.netty.handler.codec.mqtt.MqttQoS;
+import io.vertx.core.Handler;
+import io.vertx.core.Vertx;
+import io.vertx.core.buffer.Buffer;
+import io.vertx.mqtt.MqttEndpoint;
+import io.vertx.mqtt.MqttServer;
+import io.vertx.mqtt.MqttServerOptions;
+import io.vertx.mqtt.MqttTopicSubscription;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * The consumer across a restart on a connection its producer keeps, a session
the broker kept, and a redelivery after a
+ * reconnect.
+ */
+class VertxMqttConsumerSessionTest {
+
+ private static final Duration WAIT = Duration.ofSeconds(10);
+
+ private Vertx vertx;
+ private CamelContext context;
+ private TestBroker broker;
+ private MqttServer server;
+ private final Queue<String> received = new ConcurrentLinkedQueue<>();
+
+ @BeforeEach
+ void start() throws Exception {
+ vertx = Vertx.vertx();
+ context = new DefaultCamelContext();
+ context.getRegistry().bind("vertx", vertx);
+ context.start();
+ }
+
+ @AfterEach
+ void stop() throws Exception {
+ context.stop();
+ if (broker != null) {
+ broker.close();
+ }
+ if (server != null) {
+ server.close().toCompletionStage().toCompletableFuture().get(10,
TimeUnit.SECONDS);
+ }
+ vertx.close().toCompletionStage().toCompletableFuture().get(10,
TimeUnit.SECONDS);
+ }
+
+ /**
+ * A broker on the Vert.x MQTT server that kept the session of the client:
each endpoint is handed to the handler,
+ * which accepts it.
+ */
+ private int startServer(Handler<MqttEndpoint> handler) throws Exception {
+ server = MqttServer.create(vertx, new
MqttServerOptions().setHost("127.0.0.1").setPort(0));
+ server.endpointHandler(endpoint -> {
+ endpoint.publishAutoAck(false);
+ endpoint.subscribeHandler(subscribe ->
endpoint.subscribeAcknowledge(subscribe.messageId(),
+
subscribe.topicSubscriptions().stream().map(MqttTopicSubscription::qualityOfService).toList()));
+ handler.handle(endpoint);
+ });
+ server.listen().toCompletionStage().toCompletableFuture().get(10,
TimeUnit.SECONDS);
+ return server.actualPort();
+ }
+
+ @Test
+ void consumerStartedAgainOnTheConnectionOfItsProducerReadsAgain() throws
Exception {
+ broker = TestBroker.start(vertx);
+ final String uri = "vertx-mqtt:a?brokerUrl=" + broker.url() +
"&qos=1&ackTimeout=3";
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(uri).routeId("consumer").process(e ->
received.add(e.getMessage().getBody(String.class)));
+ from("direct:send").routeId("producer").to(uri);
+ }
+ });
+ await().atMost(WAIT).until(() -> broker.hasSubscription("a"));
+
+ // the producer keeps the connection while the consumer stops and
starts again
+ context.getRouteController().stopRoute("consumer");
+ context.getRouteController().startRoute("consumer");
+ await().atMost(WAIT).until(() -> broker.hasSubscription("a"));
+ assertEquals(1, broker.connects(), "The consumer and the producer
share one connection");
+
+ // the PUBACK of a publish of quality of service 1 must be read
+ final Exchange sent =
context.createProducerTemplate().send("direct:send",
+ e -> e.getMessage().setBody("out"));
+ assertNull(sent.getException(), "The broker acknowledged the message,
the producer must read the PUBACK");
+ broker.send("a", "after".getBytes(StandardCharsets.UTF_8), 1, false,
null);
+ await().atMost(WAIT).until(() -> received.contains("after"));
+ }
+
+ @Test
+ void
consumerStoppedAsTheLastUserOfItsConnectionLeavesTheMessagesItDidNotReadUnacknowledged()
throws Exception {
+ final Queue<Integer> acknowledged = new ConcurrentLinkedQueue<>();
+ final List<MqttEndpoint> endpoints = new CopyOnWriteArrayList<>();
+ final CountDownLatch subscribed = new CountDownLatch(1);
+ final CountDownLatch closed = new CountDownLatch(1);
+ final int port = startServer(endpoint -> {
+ endpoints.add(endpoint);
+ endpoint.publishAcknowledgeHandler(acknowledged::add);
+ endpoint.subscribeHandler(subscribe -> {
+ endpoint.subscribeAcknowledge(subscribe.messageId(),
+
subscribe.topicSubscriptions().stream().map(MqttTopicSubscription::qualityOfService).toList());
+ subscribed.countDown();
+ });
+ endpoint.closeHandler(v -> closed.countDown());
+ endpoint.accept(false);
+ });
+ final CountDownLatch firstStarted = new CountDownLatch(1);
+ final CountDownLatch releaseFirst = new CountDownLatch(1);
+ final String uri = "vertx-mqtt:a?brokerUrl=tcp://127.0.0.1:" + port +
"&clientId=alone&cleanStart=false&qos=1"
+ + "&automaticReconnect=false&maxPendingMessages=1";
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(uri).routeId("consumer").process(e -> {
+ final String body = e.getMessage().getBody(String.class);
+ received.add(body);
+ if ("first".equals(body)) {
+ firstStarted.countDown();
+ assertTrue(releaseFirst.await(20, TimeUnit.SECONDS));
+ }
+ });
+ }
+ });
+ final VertxMqttConsumer consumer = (VertxMqttConsumer)
context.getRoute("consumer").getConsumer();
+ assertTrue(subscribed.await(10, TimeUnit.SECONDS));
+
+ // the first message is processed, and at maxPendingMessages the
client stops reading: the other two wait
+ // unread (and so unacknowledged) on the connection
+ final MqttEndpoint endpoint = endpoints.get(0);
+ vertx.runOnContext(v -> endpoint.publish("a", Buffer.buffer("first"),
MqttQoS.AT_LEAST_ONCE, false, false));
+ assertTrue(firstStarted.await(10, TimeUnit.SECONDS));
+ vertx.runOnContext(v -> {
+ endpoint.publish("a", Buffer.buffer("second"),
MqttQoS.AT_LEAST_ONCE, false, false);
+ endpoint.publish("a", Buffer.buffer("third"),
MqttQoS.AT_LEAST_ONCE, false, false);
+ });
+
+ // the consumer stops: the connection has no other user and stops with
it, so the session the broker keeps
+ // must still hold the two messages for the next connect
+ consumer.prepareShutdown(false, false);
+ releaseFirst.countDown();
+ await().atMost(WAIT).until(() -> consumer.getPendingExchangesSize() ==
0);
+ final VertxMqttEndpoint endpointOfRoute = consumer.getEndpoint();
+ // the consumer itself, so that its doStop runs on this thread (a
route stop hands it to a shutdown thread)
+ final Thread stopper = new Thread(consumer::stop, "stop-consumer");
+ // the stop is held where it gives the connection back (as a busy
thread may be): the client must not read the
+ // waiting messages meanwhile, as it would acknowledge them
+ synchronized (endpointOfRoute) {
+ stopper.start();
+ await().atMost(WAIT).until(() -> stopper.getState() ==
Thread.State.BLOCKED);
+ await().during(Duration.ofSeconds(1)).atMost(WAIT).until(() ->
acknowledged.size() == 1);
+ }
+ stopper.join(WAIT.toMillis());
+ assertTrue(closed.await(10, TimeUnit.SECONDS));
+ assertEquals(List.of("first"), List.copyOf(received));
+ assertEquals(1, acknowledged.size(), "Only the message the consumer
processed may be acknowledged");
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = { false, true })
+ void messagesOfAKeptSessionRightAfterTheConnackReachTheConsumer(boolean
manualAcks) throws Exception {
+ final Queue<Integer> acknowledged = new ConcurrentLinkedQueue<>();
+ // the queued message comes in the same flush as the CONNACK
+ final int port = startServer(endpoint -> {
+ endpoint.publishAcknowledgeHandler(acknowledged::add);
+ endpoint.accept(true);
+ endpoint.publish("a", Buffer.buffer("queued"),
MqttQoS.AT_LEAST_ONCE, false, false);
+ });
+ // without automaticReconnect the start waits for the CONNACK
+ final String uri = "vertx-mqtt:a?brokerUrl=tcp://127.0.0.1:" + port +
"&clientId=kept&cleanStart=false&qos=1"
+ + "&automaticReconnect=false&manualAcksEnabled=" +
manualAcks;
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(uri).routeId("consumer").process(e ->
received.add(e.getMessage().getBody(String.class)));
+ }
+ });
+
+ await().atMost(WAIT).untilAsserted(() -> {
+ assertEquals(List.of("queued"), List.copyOf(received));
+ assertEquals(1, acknowledged.size(), "The message must be
acknowledged once");
+ });
+ }
+
+ @Test
+ void
messageFailingOnTheCurrentConnectionAfterAFailureOnAnEarlierOneIsDeliveredAgain()
throws Exception {
+ // a session for one client: the message stays until it is
acknowledged, and comes again on every connect
+ final AtomicBoolean acked = new AtomicBoolean();
+ final AtomicInteger connects = new AtomicInteger();
+ final List<MqttEndpoint> endpoints = new CopyOnWriteArrayList<>();
+ final int port = startServer(endpoint -> {
+ final int connect = connects.incrementAndGet();
+ endpoints.add(endpoint);
+ endpoint.publishAcknowledgeHandler(id -> acked.set(true));
+ endpoint.accept(connect > 1);
+ if (!acked.get()) {
+ endpoint.publish("a", Buffer.buffer("poison"),
MqttQoS.AT_LEAST_ONCE, connect > 1, false);
+ }
+ });
+ final CountDownLatch firstStarted = new CountDownLatch(1);
+ final CountDownLatch releaseFirst = new CountDownLatch(1);
+ final AtomicInteger attempts = new AtomicInteger();
+ final String uri = "vertx-mqtt:a?brokerUrl=tcp://127.0.0.1:" + port
+ +
"&clientId=redeliver&cleanStart=false&sessionExpiryInterval=60&qos=1&manualAcksEnabled=true"
+ + "&reconnectDelay=50&maxReconnectDelay=200";
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(uri).routeId("consumer").process(e -> {
+ final int attempt = attempts.incrementAndGet();
+ if (attempt == 1) {
+ firstStarted.countDown();
+ assertTrue(releaseFirst.await(20, TimeUnit.SECONDS));
+ }
+ // the copies of the first two connections fail, the third
succeeds
+ if (attempt <= 2) {
+ throw new IllegalStateException("Forced failure " +
attempt);
+ }
+ });
+ }
+ });
+ final VertxMqttConsumer consumer = (VertxMqttConsumer)
context.getRoute("consumer").getConsumer();
+
+ // the first copy is processed while connection 1 drops; the client
reconnects and reads the second copy
+ assertTrue(firstStarted.await(20, TimeUnit.SECONDS));
+ vertx.runOnContext(v -> endpoints.get(0).close());
+ await().atMost(WAIT).until(() -> connects.get() == 2 &&
consumer.getPendingExchangesSize() == 2);
+
+ // the first copy fails (connection 1), then the second copy fails on
connection 2: the consumer must close
+ // connection 2, and the broker sends the message again on connection 3
+ releaseFirst.countDown();
+ await().atMost(WAIT).untilAsserted(() -> {
+ assertTrue(acked.get(), "The message must be delivered again and
acknowledged");
+ assertEquals(3, attempts.get());
+ assertEquals(3, connects.get());
+ });
+ }
+}