fix(iot): keep MQTT persistent sessions across reconnects (#8915)

This commit is contained in:
rajp33 authored and GitHub committed 2026-11-19 13:01:44 -04:00
1 parent f94b28e702
commit 623be62f3a
7 files changed
+715 -56

No files matched your search

@@ -526,12 +526,40 @@ def test_mqtt_shadow_reserved_topics(unique_name):
assert deleted["clientToken"] == "delete-token"
def mqtt_connect(client_id):
def test_mqtt_persistent_session_receives_qos1_messages_queued_while_offline(unique_name):
client_id = f"{unique_name}-persistent"
topic = f"devices/{unique_name}/commands"
try:
with mqtt_connect(f"{unique_name}-watcher") as watcher:
mqtt_subscribe(watcher, f"$aws/events/presence/disconnected/{client_id}")
with mqtt_connect(client_id, clean_session=False) as device:
mqtt_subscribe(device, topic, qos=1)
device.sendall(b"\xe0\x00")
mqtt_read_publish(watcher)
with mqtt_connect(f"{unique_name}-pub") as publisher:
mqtt_publish(publisher, topic, b"offline-qos0")
mqtt_publish(publisher, topic, b"offline-qos1", qos=1)
with mqtt_connect(client_id, clean_session=False, session_present=True) as device:
packet = mqtt_read_packet(device)
assert (packet[0] >> 1) & 0x03 == 1
assert mqtt_parse_publish(packet) == (topic, b"offline-qos1")
finally:
try:
mqtt_connect(client_id).close()
except (OSError, AssertionError):
pass
def mqtt_connect(client_id, clean_session=True, session_present=False):
client = socket.create_connection(("floci", 1883), timeout=5)
client.settimeout(5)
body = mqtt_utf8("MQTT") + bytes([4, 2, 0, 60]) + mqtt_utf8(client_id)
flags = 0x02 if clean_session else 0x00
body = mqtt_utf8("MQTT") + bytes([4, flags, 0, 60]) + mqtt_utf8(client_id)
client.sendall(bytes([0x10]) + mqtt_remaining_length(len(body)) + body)
assert mqtt_read_packet(client) == b"\x20\x02\x00\x00"
assert mqtt_read_packet(client) == bytes([0x20, 0x02, 0x01 if session_present else 0x00, 0x00])
return client
@@ -554,19 +582,27 @@ def mqtt_assert_v5_connack(packet):
assert packet[index + 1] == 0x00
def mqtt_subscribe(client, topic):
body = b"\x00\x01" + mqtt_utf8(topic) + b"\x00"
def mqtt_subscribe(client, topic, qos=0):
body = b"\x00\x01" + mqtt_utf8(topic) + bytes([qos])
client.sendall(bytes([0x82]) + mqtt_remaining_length(len(body)) + body)
assert mqtt_read_packet(client) == b"\x90\x03\x00\x01\x00"
assert mqtt_read_packet(client) == b"\x90\x03\x00\x01" + bytes([qos])
def mqtt_publish(client, topic, payload):
body = mqtt_utf8(topic) + payload
client.sendall(bytes([0x30]) + mqtt_remaining_length(len(body)) + body)
def mqtt_publish(client, topic, payload, qos=0):
if qos == 0:
body = mqtt_utf8(topic) + payload
client.sendall(bytes([0x30]) + mqtt_remaining_length(len(body)) + body)
return
body = mqtt_utf8(topic) + b"\x00\x01" + payload
client.sendall(bytes([0x32]) + mqtt_remaining_length(len(body)) + body)
assert mqtt_read_packet(client) == b"\x40\x02\x00\x01"
def mqtt_read_publish(client):
packet = mqtt_read_packet(client)
return mqtt_parse_publish(mqtt_read_packet(client))
def mqtt_parse_publish(packet):
assert packet[0] & 0xF0 == 0x30
index = 1
while packet[index] & 0x80:
@@ -576,6 +612,8 @@ def mqtt_read_publish(client):
index += 2
topic = packet[index:index + topic_length].decode()
index += topic_length
if packet[0] & 0x06:
index += 2
return topic, packet[index:]
+5 -4
View File
@@ -34,8 +34,9 @@ Supported MVP 2 behavior:
- Jobs data plane: pending-job listing, `StartNextPendingJobExecution`, `DescribeJobExecution`, and `UpdateJobExecution` with version conflicts and terminal-state checks.
- Endpoint discovery accepts `iot:Jobs` and `iot:CredentialProvider` in addition to IoT Data endpoint types.
- MQTT clients can use QoS 1 subscribe/publish paths with broker PUBACK and delivery behavior.
- IoT Data connection APIs for live MQTT sessions: `GetConnection`, `DeleteConnection`, `ListSubscriptions`, and `SendDirectMessage`.
- `DeleteConnection` closes active MQTT client sessions through the embedded broker and optionally purges broker session state for `cleanSession=true`.
- MQTT persistent sessions: a connection with MQTT 3.1.1 `cleanSession=0`, or MQTT 5 with a Session Expiry Interval above 0, keeps its subscriptions when it disconnects, and each QoS 1 message matching one of its QoS 1 subscriptions is stored for it. A reconnect with `cleanSession=0` (MQTT 5 `Clean Start=0`) gets `sessionPresent=1` and the stored messages after the `CONNACK`, without subscribing again; a clean connect discards the session. An MQTT 3.1.1 session expires after AWS's default persistent session expiry period of one hour, an MQTT 5 session after its Session Expiry Interval, at most that hour; a longer interval is lowered to it and the `CONNACK` reports the lowered value. An MQTT 5 `DISCONNECT` with a Session Expiry Interval replaces the one from `CONNECT`, and 0 ends the session, but cannot make a session that connected with 0 persistent. As on AWS, a session is resumed only from the account and Region that created it and over the MQTT version that created it, and QoS 0 messages are not stored.
- IoT Data connection APIs for live MQTT sessions: `GetConnection`, `DeleteConnection`, `ListSubscriptions`, and `SendDirectMessage`. `ListSubscriptions` also answers for a disconnected persistent session in the caller's account and Region.
- `DeleteConnection` closes active MQTT client sessions through the embedded broker. A persistent session is kept for its reconnect unless `cleanSession=true`, which discards it.
- IoT rules can dispatch matching payloads to SQS, SNS, S3, DynamoDB v2, Kinesis, Lambda, Kinesis Data Firehose, CloudWatch Logs, and MQTT republish targets.
Current MVP 2 limitations:
@@ -45,7 +46,8 @@ Current MVP 2 limitations:
- A retained message is also sent on a subscription to a wildcard filter that matches its topic. AWS sends it only to a subscription naming its exact topic.
- A QoS 1 copy sent to a subscriber is never retried, and no limit applies to how many stay unacknowledged. AWS holds further copies once a client has 100 unacknowledged and retries them for up to an hour (16 minutes for MQTT 5).
- `SendDirectMessage` publishes to the requested MQTT topic through the embedded broker. Unlike AWS IoT Core, it does not yet bypass subscription matching to deliver to a client that is not subscribed to that topic.
- `GetConnection` and `ListSubscriptions` report live in-memory broker state only; offline persistent session subscription reporting is not modeled yet.
- `GetConnection` reports live sessions only. `ListSubscriptions` also reports the subscriptions of a disconnected persistent session.
- A persistent session does not store the QoS 1 copies that were sent but not acknowledged when its connection dropped. Stored messages are sent all at once on reconnect, not at AWS's 10 per second, do not expire by their MQTT 5 Message Expiry Interval, and are not limited by AWS's queued messages per second quota. Sessions are in memory only: a broker restart or an emulator reset discards them.
- Jobs reserved MQTT topics remain follow-up scope; Jobs Data HTTP APIs are implemented first.
- Dynamic thing groups, job rollouts, cancellations, documents from S3, and advanced job scheduling are not yet modeled. Fleet indexing has its configuration and a bounded `SearchIndex` subset, see [Fleet Indexing](#fleet-indexing).
@@ -367,7 +369,6 @@ Implementation notes:
Current accepted limitation:
- Certificate and `iot:Connect` checks are enforced on 8883 only; topic-level authorization is not enforced on either port yet.
- Persistent offline sessions are not modeled yet.
- QoS 2 and advanced MQTT 5 property semantics remain follow-up scope.
- At most 1,000 MQTT publishes are pending rule evaluation, running or waiting. While that many are pending, further publishes are still delivered to subscribers but their topic rules are skipped, with one warning logged until the backlog drains.
- REST shadow errors are not published to `rejected`.
@@ -109,10 +109,12 @@ public class IotDataController {
@GET
@Path("/connections/{clientId: .+}/subscriptions")
public Response listSubscriptions(@PathParam("clientId") String clientId,
public Response listSubscriptions(@Context HttpHeaders headers,
@PathParam("clientId") String clientId,
@QueryParam("maxResults") Integer maxResults,
@QueryParam("nextToken") String nextToken) {
IotService.Page<String> page = iotService.listSubscriptions(clientId, maxResults, nextToken);
IotService.Page<String> page = iotService.listSubscriptions(clientId, maxResults, nextToken,
regionResolver.resolveRegion(headers));
ObjectNode response = objectMapper.createObjectNode();
ArrayNode subscriptions = response.putArray("subscriptions");
for (String topicFilter : page.items()) {
@@ -117,6 +117,9 @@ public class IotMqttBrokerService implements Resettable {
/** AWS IoT Core's MQTT packet quota, counted as Netty's decoder counts: variable header plus payload. */
private static final int MAX_PACKET_SIZE = 146 * 1024;
/** AWS IoT Core's default persistent session expiry period quota, which also bounds an MQTT 5 Session Expiry Interval. */
static final long PERSISTENT_SESSION_EXPIRY_SECONDS = 3600;
private static final Pattern IPV4_LITERAL = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}");
static final int MAX_PENDING_RULE_EVALUATIONS = 1_000;
@@ -143,6 +146,7 @@ public class IotMqttBrokerService implements Resettable {
final WorkerExecutor ruleWorker;
private final Map<String, ClientSession> sessionsByClient = new ConcurrentHashMap<>();
private final Map<String, Map<String, Subscription>> subscriptionsByClient = new ConcurrentHashMap<>();
private final Map<HistoryKey, StoredSession> storedSessions = new ConcurrentHashMap<>();
/** Serializes admitting and ending sessions and the versionNumbers they take; never held across endpoint I/O. */
private final Object sessionLock = new Object();
/** The last lifecycle event versionNumber per client id; neither a state reset nor a broker restart clears it. */
@@ -223,13 +227,16 @@ public class IotMqttBrokerService implements Resettable {
}
/**
* The broker keeps nothing in Floci storage; a reset forgets how earlier sessions ended, and
* suspends rules in {@link #beforeReset()}. Live sessions stay connected.
* The broker keeps nothing in Floci storage; a reset forgets how earlier sessions ended and
* discards disconnected persistent sessions, and suspends rules in {@link #beforeReset()}.
* Live sessions stay connected.
*/
@Override
public void clear() {
synchronized (sessionLock) {
lastDisconnects.clear();
storedSessions.values().forEach(stored -> vertx.cancelTimer(stored.expiryTimer()));
storedSessions.clear();
}
}
@@ -344,6 +351,8 @@ public class IotMqttBrokerService implements Resettable {
});
sessionsByClient.clear();
subscriptionsByClient.clear();
storedSessions.values().forEach(stored -> vertx.cancelTimer(stored.expiryTimer()));
storedSessions.clear();
if (mqttServer != null) {
mqttServer.close().toCompletionStage().toCompletableFuture().join();
}
@@ -390,6 +399,7 @@ public class IotMqttBrokerService implements Resettable {
return false;
}
if (cleanSession) {
discardStoredSession(session.historyKey());
subscriptionsByClient.remove(clientId);
}
}
@@ -435,8 +445,16 @@ public class IotMqttBrokerService implements Resettable {
}
}
List<String> listSubscriptions(String clientId) {
return subscriptionsByClient.getOrDefault(clientId, Map.of()).keySet().stream()
boolean hasSession(String accountId, String region, String clientId) {
return getConnection(clientId).isPresent() || storedSessions.containsKey(new HistoryKey(accountId, region, clientId));
}
List<String> listSubscriptions(String accountId, String region, String clientId) {
StoredSession stored = storedSessions.get(new HistoryKey(accountId, region, clientId));
Map<String, Subscription> subscriptions = sessionsByClient.containsKey(clientId) || stored == null
? subscriptionsByClient.getOrDefault(clientId, Map.of())
: stored.subscriptions();
return subscriptions.keySet().stream()
.sorted()
.toList();
}
@@ -527,15 +545,24 @@ public class IotMqttBrokerService implements Resettable {
* {@code clientIp} and {@code clientPort} are the address the client connected from: the
* socket's, or for a WebSocket client the one the bridge recorded at the upgrade, as the
* bridge's own socket is loopback. {@code connectNanos} is when the CONNECT arrived, which
* the keep-alive runs from.
* the keep-alive runs from. A CONNECT without a clean session resumes the client id's
* persistent session created in the same account and region over the same MQTT version: the
* CONNACK reports it present and its stored messages follow; any other CONNECT from that
* account and region discards it, and one from elsewhere leaves it stored.
*/
private void admit(MqttEndpoint endpoint, IotService.RegisteredDevice device, String clientIp, int clientPort,
long connectNanos) {
String clientId = endpoint.clientIdentifier();
boolean cleanSession = endpoint.isCleanSession();
int protocolVersion = endpoint.protocolVersion();
long requestedSessionExpiry = protocolVersion == 5
? sessionExpiryInterval(endpoint.connectProperties(), 0)
: cleanSession ? 0 : PERSISTENT_SESSION_EXPIRY_SECONDS;
long sessionExpirySeconds = Math.min(requestedSessionExpiry, PERSISTENT_SESSION_EXPIRY_SECONDS);
String principal = device == null ? null : device.certificate().getCertificateId();
ClientSession session;
ClientSession replaced = null;
boolean sessionPresent;
synchronized (sessionLock) {
long versionNumber = presenceVersions.merge(clientId, 0L, (last, unused) -> last + 1);
session = new ClientSession(
@@ -544,6 +571,8 @@ public class IotMqttBrokerService implements Resettable {
clientIp,
clientPort,
cleanSession,
protocolVersion,
sessionExpirySeconds,
UUID.randomUUID().toString(),
principal,
versionNumber,
@@ -555,7 +584,19 @@ public class IotMqttBrokerService implements Resettable {
endpoint.keepAliveTimeSeconds(),
new AtomicInteger());
ClientSession previous = sessionsByClient.put(clientId, session);
if (previous != null && previous.endpoint() != endpoint) {
boolean takeover = previous != null && previous.endpoint() != endpoint;
StoredSession stored = storedSessions.get(session.historyKey());
sessionPresent = !cleanSession && (takeover
? previous.sessionExpirySeconds() > 0 && previous.historyKey().equals(session.historyKey())
&& sameMqttVersion(previous.protocolVersion(), protocolVersion)
: stored != null && sameMqttVersion(stored.protocolVersion(), protocolVersion));
if (!sessionPresent) {
discardStoredSession(session.historyKey());
subscriptionsByClient.remove(clientId);
} else if (!takeover) {
subscriptionsByClient.put(clientId, stored.subscriptions());
}
if (takeover) {
endSession(previous, DUPLICATE_CLIENTID);
replaced = previous;
}
@@ -579,9 +620,27 @@ public class IotMqttBrokerService implements Resettable {
endpoint.publishHandler(message -> handlePublish(session, message));
endpoint.pingHandler(ignored -> received(session));
endpoint.publishAcknowledgeHandler(ignored -> received(session));
endpoint.disconnectHandler(ignored -> endSession(session, CLIENT_INITIATED_DISCONNECT));
endpoint.disconnectMessageHandler(message -> endSession(session, CLIENT_INITIATED_DISCONNECT,
session.sessionExpirySeconds() == 0 ? 0 : Math.min(PERSISTENT_SESSION_EXPIRY_SECONDS,
sessionExpiryInterval(message.properties(), session.sessionExpirySeconds()))));
endpoint.closeHandler(ignored -> endSession(session, keepAliveExpired(session) ? MQTT_KEEP_ALIVE_TIMEOUT : CONNECTION_LOST));
endpoint.accept();
MqttProperties connack = new MqttProperties();
if (requestedSessionExpiry > sessionExpirySeconds) {
connack.add(new MqttProperties.IntegerProperty(
MqttProperties.MqttPropertyType.SESSION_EXPIRY_INTERVAL.value(), (int) sessionExpirySeconds));
}
endpoint.accept(sessionPresent, connack);
List<QueuedMessage> resumed = List.of();
synchronized (sessionLock) {
if (sessionsByClient.get(clientId) == session) {
StoredSession stored = discardStoredSession(session.historyKey());
resumed = stored == null ? List.of() : stored.queued();
}
}
for (QueuedMessage message : resumed) {
endpoint.publish(message.topic(), Buffer.buffer(message.payload()), MqttQoS.AT_LEAST_ONCE, false, false,
session.packetId(MqttQoS.AT_LEAST_ONCE), message.properties());
}
} catch (IllegalStateException e) {
// Only another thread closes the endpoint here: a takeover, DeleteConnection or stop,
// each of which has already ended the session, so its connected event pairs with that.
@@ -593,6 +652,17 @@ public class IotMqttBrokerService implements Resettable {
publishPresence(session, "connected", null);
}
private static long sessionExpiryInterval(MqttProperties properties, long absent) {
MqttProperties.MqttProperty<?> interval = properties == null ? null
: properties.getProperty(MqttProperties.MqttPropertyType.SESSION_EXPIRY_INTERVAL.value());
return interval == null ? absent : Integer.toUnsignedLong((Integer) interval.value());
}
/** AWS IoT resumes an MQTT 3 session only over MQTT 3, and an MQTT 5 session only over MQTT 5. */
private static boolean sameMqttVersion(int stored, int connecting) {
return (stored == 5) == (connecting == 5);
}
/**
* The registered device behind the connection when it may connect, otherwise null.
* A failure while deciding refuses the client rather than leaving the CONNECT unanswered. A
@@ -806,10 +876,23 @@ public class IotMqttBrokerService implements Resettable {
/**
* Delivers a live copy, RETAIN 0 as on AWS, to each subscriber with a matching subscription, at the
* lower of {@code qos} and the highest QoS among its matching subscriptions. Netty encodes
* {@code properties} only for an MQTT 5 subscriber.
* {@code properties} only for an MQTT 5 subscriber. A QoS 1 publish matching a QoS 1
* subscription of a disconnected persistent session is stored for it instead.
*/
private void fanOut(String topic, byte[] payload, int qos, MqttProperties properties) {
byte[] safePayload = payload == null ? new byte[0] : payload.clone();
if (qos > 0) {
storedSessions.forEach((key, stored) -> {
if (grantedQos(stored.subscriptions().values(), topic) < 1) {
return;
}
synchronized (sessionLock) {
if (storedSessions.get(key) == stored) {
stored.queued().add(new QueuedMessage(topic, safePayload, properties));
}
}
});
}
for (ClientSession session : sessionsByClient.values()) {
Map<String, Subscription> subscriptions = subscriptionsByClient.get(session.clientId());
int granted = subscriptions == null ? -1 : grantedQos(subscriptions.values(), topic);
@@ -859,9 +942,14 @@ public class IotMqttBrokerService implements Resettable {
* Ends the session once: the first reason reported wins, and only that one publishes the
* disconnected event, records how the session ended for fleet indexing, and gets true. The
* versionNumber counts up only while the session is still the client id's current one, so a
* session replaced by a newer connection leaves it alone.
* session replaced by a newer connection leaves it alone. A current session with a session
* expiry is stored for its reconnect with its subscriptions; one without drops them.
*/
private boolean endSession(ClientSession session, String reason) {
return endSession(session, reason, session.sessionExpirySeconds());
}
private boolean endSession(ClientSession session, String reason, long sessionExpirySeconds) {
synchronized (sessionLock) {
if (!session.ended().compareAndSet(false, true)) {
return false;
@@ -869,8 +957,13 @@ public class IotMqttBrokerService implements Resettable {
lastDisconnects.put(session.historyKey(), session.disconnected(reason));
if (sessionsByClient.remove(session.clientId(), session)) {
presenceVersions.computeIfPresent(session.clientId(), (id, version) -> version + 1);
if (sessionExpirySeconds > 0) {
store(session, sessionExpirySeconds);
} else {
discardStoredSession(session.historyKey());
}
}
if (session.cleanSession()) {
if (sessionExpirySeconds == 0) {
subscriptionsByClient.remove(session.clientId());
}
publishPresence(session, "disconnected", reason);
@@ -878,6 +971,32 @@ public class IotMqttBrokerService implements Resettable {
}
}
private void store(ClientSession session, long sessionExpirySeconds) {
HistoryKey key = session.historyKey();
StoredSession unresumed = discardStoredSession(key);
long expiryTimer = vertx.setTimer(TimeUnit.SECONDS.toMillis(sessionExpirySeconds), timer -> {
synchronized (sessionLock) {
StoredSession stored = storedSessions.get(key);
ClientSession live = sessionsByClient.get(key.clientId());
if (stored != null && stored.expiryTimer() == timer && (live == null || !live.historyKey().equals(key))) {
storedSessions.remove(key);
}
}
});
Map<String, Subscription> subscriptions = subscriptionsByClient.remove(key.clientId());
storedSessions.put(key, new StoredSession(session.protocolVersion(),
subscriptions == null ? new ConcurrentHashMap<>() : subscriptions,
unresumed == null ? new ArrayList<>() : unresumed.queued(), expiryTimer));
}
private StoredSession discardStoredSession(HistoryKey key) {
StoredSession stored = storedSessions.remove(key);
if (stored != null) {
vertx.cancelTimer(stored.expiryTimer());
}
return stored;
}
/**
* Publishes the AWS lifecycle event of a session the way a client publish goes: recorded, run
* through every region's topic rules on the rule worker, then fanned out to subscribers. A
@@ -977,6 +1096,8 @@ public class IotMqttBrokerService implements Resettable {
String sourceIp,
int sourcePort,
boolean cleanSession,
int protocolVersion,
long sessionExpirySeconds,
String sessionIdentifier,
String principalIdentifier,
long versionNumber,
@@ -1017,6 +1138,14 @@ public class IotMqttBrokerService implements Resettable {
private record Subscription(String topicFilter, int qos) {
}
/** A disconnected persistent session; its queue is only touched under the session lock. */
private record StoredSession(int protocolVersion, Map<String, Subscription> subscriptions, List<QueuedMessage> queued,
long expiryTimer) {
}
private record QueuedMessage(String topic, byte[] payload, MqttProperties properties) {
}
record ConnectionInfo(String clientId, String address, int port) {
}
@@ -1222,9 +1222,13 @@ public class IotService {
.orElseThrow(() -> new AwsException("ResourceNotFoundException", "MQTT client is not connected: " + clientId, 404));
}
public Page<String> listSubscriptions(String clientId, Integer maxResults, String nextToken) {
getConnection(clientId);
return paginate(mqttBrokerService.listSubscriptions(clientId), maxResults, nextToken);
public Page<String> listSubscriptions(String clientId, Integer maxResults, String nextToken, String region) {
validateMqttClientId(clientId);
String accountId = regionResolver.getAccountId();
if (!mqttBrokerService.hasSession(accountId, region, clientId)) {
throw new AwsException("ResourceNotFoundException", "MQTT client has no session: " + clientId, 404);
}
return paginate(mqttBrokerService.listSubscriptions(accountId, region, clientId), maxResults, nextToken);
}
public void sendDirectMessage(String clientId, String topic, byte[] payload) {
@@ -41,9 +41,11 @@ import io.vertx.core.net.PemKeyCertOptions;
import io.vertx.core.net.SocketAddress;
import io.vertx.mqtt.MqttEndpoint;
import io.vertx.mqtt.MqttTopicSubscription;
import io.vertx.mqtt.messages.MqttDisconnectMessage;
import io.vertx.mqtt.messages.MqttPublishMessage;
import io.vertx.mqtt.messages.MqttSubscribeMessage;
import io.vertx.mqtt.messages.MqttUnsubscribeMessage;
import io.vertx.mqtt.messages.codes.MqttDisconnectReasonCode;
import jakarta.enterprise.inject.Instance;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
@@ -122,6 +124,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
@@ -160,6 +163,8 @@ class IotMqttBrokerServiceTest {
"TLS_RSA_WITH_AES_128_GCM_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA",
"TLS_RSA_WITH_AES_256_GCM_SHA384", "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA");
private static final MqttDisconnectMessage DISCONNECT =
MqttDisconnectMessage.create(MqttDisconnectReasonCode.NORMAL, MqttProperties.NO_PROPERTIES);
private static Vertx vertx;
private static FlociCertificateAuthority ca;
private static CertificateGenerator.GeneratedCertificate bootLeaf;
@@ -754,13 +759,258 @@ class IotMqttBrokerServiceTest {
assertDoesNotThrow(() -> broker.handleEndpoint(replacement, false));
verify(replacement).accept();
verify(replacement).accept(anyBoolean(), any(MqttProperties.class));
awaitPresence("connected", "closed-takeover", 2);
List<JsonNode> events = presenceOf("closed-takeover");
assertEquals(List.of("connected", "disconnected", "connected"), eventTypes(events), events.toString());
assertEquals("DUPLICATE_CLIENTID", events.get(1).get("disconnectReason").asText());
}
@Test
void aConnectTakingOverALivePersistentSessionReportsTheSessionPresent() throws Exception {
startBrokerRecordingPublishes();
MqttEndpoint first = persistentEndpoint("resumed-takeover");
broker.handleEndpoint(first, false);
MqttEndpoint second = persistentEndpoint("resumed-takeover");
broker.handleEndpoint(second, false);
verify(first).accept(eq(false), any(MqttProperties.class));
verify(second).accept(eq(true), any(MqttProperties.class));
}
@Test
void deleteConnectionKeepsAPersistentSessionUnlessAskedToCleanIt() throws Exception {
startBrokerRecordingPublishes();
broker.handleEndpoint(persistentEndpoint("deleted-persistent"), false);
assertTrue(broker.disconnectClient("deleted-persistent", false));
MqttEndpoint resumed = persistentEndpoint("deleted-persistent");
broker.handleEndpoint(resumed, false);
verify(resumed).accept(eq(true), any(MqttProperties.class));
assertTrue(broker.disconnectClient("deleted-persistent", true));
MqttEndpoint fresh = persistentEndpoint("deleted-persistent");
broker.handleEndpoint(fresh, false);
verify(fresh).accept(eq(false), any(MqttProperties.class));
}
@Test
void aPersistentSessionIsResumedOnlyFromTheAccountAndRegionThatCreatedIt() throws Exception {
startBrokerRecordingPublishes();
when(config.defaultRegion()).thenReturn("us-east-1");
when(config.defaultAccountId()).thenReturn("111111111111");
String topic = "devices/scoped/commands";
MqttEndpoint first = persistentEndpoint("scoped");
broker.handleEndpoint(first, false);
subscribeQos1(first, topic);
broker.disconnectClient("scoped", false);
broker.publish(topic, "stored".getBytes(StandardCharsets.UTF_8), 1);
when(config.defaultAccountId()).thenReturn("222222222222");
MqttEndpoint otherAccount = persistentEndpoint("scoped");
broker.handleEndpoint(otherAccount, false);
broker.disconnectClient("scoped", true);
assertFalse(broker.hasSession("222222222222", "us-east-1", "scoped"));
assertTrue(broker.hasSession("111111111111", "us-east-1", "scoped"));
assertEquals(List.of(topic), broker.listSubscriptions("111111111111", "us-east-1", "scoped"));
when(config.defaultAccountId()).thenReturn("111111111111");
MqttEndpoint resumed = persistentEndpoint("scoped");
broker.handleEndpoint(resumed, false);
verify(otherAccount).accept(eq(false), any(MqttProperties.class));
verify(otherAccount, never()).publish(eq(topic), any(), any(), anyBoolean(), anyBoolean(), anyInt(),
any(MqttProperties.class));
verify(resumed).accept(eq(true), any(MqttProperties.class));
verify(resumed).publish(eq(topic), eq(Buffer.buffer("stored")), eq(MqttQoS.AT_LEAST_ONCE),
eq(false), eq(false), anyInt(), any(MqttProperties.class));
}
@Test
void aResetDiscardsADisconnectedPersistentSession() throws Exception {
startBrokerRecordingPublishes();
String topic = "devices/reset-persistent/commands";
MqttEndpoint first = persistentEndpoint("reset-persistent");
broker.handleEndpoint(first, false);
subscribeQos1(first, topic);
broker.disconnectClient("reset-persistent", false);
broker.publish(topic, "stored".getBytes(StandardCharsets.UTF_8), 1);
broker.clear();
broker.publish(topic, "after-reset".getBytes(StandardCharsets.UTF_8), 1);
MqttEndpoint reconnected = persistentEndpoint("reset-persistent");
broker.handleEndpoint(reconnected, false);
verify(reconnected).accept(eq(false), any(MqttProperties.class));
verify(reconnected, never()).publish(eq(topic), any(), any(), anyBoolean(), anyBoolean(), anyInt(),
any(MqttProperties.class));
}
@Test
void aStoredSessionEndsWhenItsExpiryTimerFires() throws Exception {
List<ExpiryTimer> timers = brokerCapturingExpiryTimers();
broker.handleEndpoint(mqtt5Endpoint("expired", 60), false);
broker.disconnectClient("expired", false);
assertEquals(List.of(60_000L), delays(timers));
timers.get(0).fire();
MqttEndpoint reconnected = mqtt5Endpoint("expired", 60);
broker.handleEndpoint(reconnected, false);
verify(reconnected).accept(eq(false), any(MqttProperties.class));
}
@Test
void anEarlierSessionsExpiryDoesNotEndASessionStoredAfterIt() throws Exception {
List<ExpiryTimer> timers = brokerCapturingExpiryTimers();
broker.handleEndpoint(mqtt5Endpoint("re-expiring", 60), false);
broker.disconnectClient("re-expiring", false);
broker.handleEndpoint(mqtt5Endpoint("re-expiring", 120), false);
broker.disconnectClient("re-expiring", false);
assertEquals(List.of(60_000L, 120_000L), delays(timers));
timers.get(0).fire();
MqttEndpoint resumed = mqtt5Endpoint("re-expiring", 120);
broker.handleEndpoint(resumed, false);
verify(resumed).accept(eq(true), any(MqttProperties.class));
}
@Test
void aQos1PublishWhileAResumedSessionIsBeingAcceptedIsDelivered() throws Exception {
startBrokerRecordingPublishes();
String topic = "devices/resuming/commands";
MqttEndpoint first = persistentEndpoint("resuming");
broker.handleEndpoint(first, false);
subscribeQos1(first, topic);
broker.disconnectClient("resuming", false);
MqttEndpoint resuming = persistentEndpoint("resuming");
AtomicBoolean accepted = new AtomicBoolean();
when(resuming.isConnected()).thenAnswer(invocation -> accepted.get());
when(resuming.accept(anyBoolean(), any())).thenAnswer(invocation -> {
broker.publish(topic, "during-accept".getBytes(StandardCharsets.UTF_8), 1);
accepted.set(true);
return resuming;
});
broker.handleEndpoint(resuming, false);
verify(resuming).publish(eq(topic), eq(Buffer.buffer("during-accept")), eq(MqttQoS.AT_LEAST_ONCE),
eq(false), eq(false), anyInt(), any(MqttProperties.class));
}
@Test
void aTakeoverBeforeAResumedSessionIsAcceptedReceivesItsStoredMessages() throws Exception {
startBrokerRecordingPublishes();
String topic = "devices/taken-over/commands";
MqttEndpoint first = persistentEndpoint("taken-over");
broker.handleEndpoint(first, false);
subscribeQos1(first, topic);
broker.disconnectClient("taken-over", false);
broker.publish(topic, "stored".getBytes(StandardCharsets.UTF_8), 1);
MqttEndpoint resuming = persistentEndpoint("taken-over");
MqttEndpoint replacement = persistentEndpoint("taken-over");
when(resuming.accept(anyBoolean(), any())).thenAnswer(invocation -> {
broker.handleEndpoint(replacement, false);
return resuming;
});
broker.handleEndpoint(resuming, false);
verify(replacement).accept(eq(true), any(MqttProperties.class));
verify(replacement).publish(eq(topic), eq(Buffer.buffer("stored")), eq(MqttQoS.AT_LEAST_ONCE),
eq(false), eq(false), anyInt(), any(MqttProperties.class));
verify(resuming, never()).publish(eq(topic), any(), any(), anyBoolean(), anyBoolean(), anyInt(),
any(MqttProperties.class));
}
@Test
void aSessionResumedAsItsExpiryRunsOutKeepsItsMessagesAndSubscriptions() throws Exception {
List<ExpiryTimer> timers = brokerCapturingExpiryTimers();
String topic = "devices/expiring/commands";
MqttEndpoint first = mqtt5Endpoint("resumed-expiring", 60);
broker.handleEndpoint(first, false);
subscribeQos1(first, topic);
broker.disconnectClient("resumed-expiring", false);
broker.publish(topic, "stored".getBytes(StandardCharsets.UTF_8), 1);
MqttEndpoint resuming = mqtt5Endpoint("resumed-expiring", 60);
when(resuming.accept(anyBoolean(), any())).thenAnswer(invocation -> {
timers.get(0).fire();
return resuming;
});
broker.handleEndpoint(resuming, false);
broker.publish(topic, "live".getBytes(StandardCharsets.UTF_8), 1);
verify(resuming).accept(eq(true), any(MqttProperties.class));
verify(resuming).publish(eq(topic), eq(Buffer.buffer("stored")), eq(MqttQoS.AT_LEAST_ONCE),
eq(false), eq(false), anyInt(), any(MqttProperties.class));
verify(resuming).publish(eq(topic), eq(Buffer.buffer("live")), eq(MqttQoS.AT_LEAST_ONCE),
eq(false), eq(false), anyInt(), any(MqttProperties.class));
}
@Test
void aDisconnectSessionExpiryOfZeroEndsAPersistentSession() throws Exception {
startBrokerRecordingPublishes();
MqttEndpoint device = mqtt5Endpoint("disconnect-ends", 3600);
broker.handleEndpoint(device, false);
disconnectWithSessionExpiry(device, 0);
MqttEndpoint reconnected = mqtt5Endpoint("disconnect-ends", 3600);
broker.handleEndpoint(reconnected, false);
verify(reconnected).accept(eq(false), any(MqttProperties.class));
}
@Test
void aDisconnectSessionExpiryReplacesTheOneFromConnect() throws Exception {
List<ExpiryTimer> timers = brokerCapturingExpiryTimers();
MqttEndpoint device = mqtt5Endpoint("disconnect-extends", 1);
broker.handleEndpoint(device, false);
disconnectWithSessionExpiry(device, 60);
assertEquals(List.of(60_000L), delays(timers));
MqttEndpoint reconnected = mqtt5Endpoint("disconnect-extends", 60);
broker.handleEndpoint(reconnected, false);
verify(reconnected).accept(eq(true), any(MqttProperties.class));
}
@Test
void aDisconnectSessionExpiryCannotPersistASessionThatConnectedWithoutOne() throws Exception {
startBrokerRecordingPublishes();
MqttEndpoint device = mqtt5Endpoint("disconnect-ephemeral", 0);
broker.handleEndpoint(device, false);
disconnectWithSessionExpiry(device, 60);
MqttEndpoint reconnected = mqtt5Endpoint("disconnect-ephemeral", 60);
broker.handleEndpoint(reconnected, false);
verify(reconnected).accept(eq(false), any(MqttProperties.class));
}
@Test
void connackReportsASessionExpiryIntervalOnlyWhenItLowersTheRequestedOne() throws Exception {
List<ExpiryTimer> timers = brokerCapturingExpiryTimers();
MqttEndpoint capped = mqtt5Endpoint("expiry-capped", 7200);
MqttEndpoint kept = mqtt5Endpoint("expiry-kept", 60);
broker.handleEndpoint(capped, false);
broker.handleEndpoint(kept, false);
ArgumentCaptor<MqttProperties> cappedConnack = ArgumentCaptor.forClass(MqttProperties.class);
verify(capped).accept(eq(false), cappedConnack.capture());
assertEquals(3600, cappedConnack.getValue()
.getProperty(MqttProperties.MqttPropertyType.SESSION_EXPIRY_INTERVAL.value()).value());
ArgumentCaptor<MqttProperties> keptConnack = ArgumentCaptor.forClass(MqttProperties.class);
verify(kept).accept(eq(false), keptConnack.capture());
assertNull(keptConnack.getValue().getProperty(MqttProperties.MqttPropertyType.SESSION_EXPIRY_INTERVAL.value()));
broker.disconnectClient("expiry-capped", false);
broker.disconnectClient("expiry-kept", false);
assertEquals(List.of(3_600_000L, 60_000L), delays(timers), "the stored sessions expire after the granted interval");
}
/**
* Two CONNECTs for one client id admitted at once on two event loops: the first is held after it
* took its versionNumber while the second completes. The session left current is the one with
@@ -882,7 +1132,7 @@ class IotMqttBrokerServiceTest {
deleting.shutdown();
reconnecting.shutdown();
}
assertEquals(List.of("devices/reconnecting/commands"), racing.listSubscriptions("reconnecting"));
assertEquals(List.of("devices/reconnecting/commands"), racing.listSubscriptions(config.defaultAccountId(), config.defaultRegion(), "reconnecting"));
}
@Test
@@ -1122,8 +1372,8 @@ class IotMqttBrokerServiceTest {
subscribeHandler.get().handle(subscribe);
MqttEndpoint departing = mock(MqttEndpoint.class);
when(departing.clientIdentifier()).thenReturn("departing");
AtomicReference<Handler<Void>> disconnectHandler = new AtomicReference<>();
when(departing.disconnectHandler(any())).thenAnswer(invocation -> {
AtomicReference<Handler<MqttDisconnectMessage>> disconnectHandler = new AtomicReference<>();
when(departing.disconnectMessageHandler(any())).thenAnswer(invocation -> {
disconnectHandler.set(invocation.getArgument(0));
return departing;
});
@@ -1134,7 +1384,7 @@ class IotMqttBrokerServiceTest {
ExecutorService departingEventLoop = Executors.newSingleThreadExecutor();
subscriberMonitor.lock();
try {
Future<?> callback = departingEventLoop.submit(() -> disconnectHandler.get().handle(null));
Future<?> callback = departingEventLoop.submit(() -> disconnectHandler.get().handle(DISCONNECT));
assertDoesNotThrow(() -> callback.get(5, TimeUnit.SECONDS),
"the disconnect callback returned while the subscriber's monitor is held");
@@ -1277,9 +1527,9 @@ class IotMqttBrokerServiceTest {
void connectivityHistoryOfAClientIdIsKeptPerAccountAndRegion() {
when(config.defaultRegion()).thenReturn("us-east-1");
when(config.defaultAccountId()).thenReturn("111111111111");
AtomicReference<Handler<Void>> disconnectInA = new AtomicReference<>();
AtomicReference<Handler<MqttDisconnectMessage>> disconnectInA = new AtomicReference<>();
broker.handleEndpoint(endpointCapturing("device-1", disconnectInA, new AtomicReference<>()), false);
disconnectInA.get().handle(null);
disconnectInA.get().handle(DISCONNECT);
when(config.defaultAccountId()).thenReturn("222222222222");
AtomicReference<Handler<Void>> closeInB = new AtomicReference<>();
@@ -1355,17 +1605,17 @@ class IotMqttBrokerServiceTest {
void aResetForgetsEndedSessionsButNotLiveOnes() {
when(config.defaultRegion()).thenReturn("us-east-1");
when(config.defaultAccountId()).thenReturn("111111111111");
AtomicReference<Handler<Void>> disconnectGone = new AtomicReference<>();
AtomicReference<Handler<MqttDisconnectMessage>> disconnectGone = new AtomicReference<>();
broker.handleEndpoint(endpointCapturing("gone", disconnectGone, new AtomicReference<>()), false);
disconnectGone.get().handle(null);
AtomicReference<Handler<Void>> disconnectLive = new AtomicReference<>();
disconnectGone.get().handle(DISCONNECT);
AtomicReference<Handler<MqttDisconnectMessage>> disconnectLive = new AtomicReference<>();
broker.handleEndpoint(endpointCapturing("live", disconnectLive, new AtomicReference<>()), false);
broker.clear();
assertTrue(broker.connectivity("111111111111", "us-east-1", "gone").isEmpty());
assertTrue(broker.connectivity("111111111111", "us-east-1", "live").orElseThrow().connected());
disconnectLive.get().handle(null);
disconnectLive.get().handle(DISCONNECT);
assertEquals("CLIENT_INITIATED_DISCONNECT",
broker.connectivity("111111111111", "us-east-1", "live").orElseThrow().disconnectReason());
}
@@ -1435,12 +1685,12 @@ class IotMqttBrokerServiceTest {
}
}
private static MqttEndpoint endpointCapturing(String clientId, AtomicReference<Handler<Void>> disconnect,
private static MqttEndpoint endpointCapturing(String clientId, AtomicReference<Handler<MqttDisconnectMessage>> disconnect,
AtomicReference<Handler<Void>> close) {
MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.clientIdentifier()).thenReturn(clientId);
when(endpoint.isConnected()).thenReturn(true);
when(endpoint.disconnectHandler(any())).thenAnswer(invocation -> {
when(endpoint.disconnectMessageHandler(any())).thenAnswer(invocation -> {
disconnect.set(invocation.getArgument(0));
return endpoint;
});
@@ -1814,6 +2064,11 @@ class IotMqttBrokerServiceTest {
/** Starts the broker over a real {@link IotService} whose one rule writes every metrics publish to DynamoDB. */
private void startBrokerWithRuleWriting(DynamoDbItemAccess items) throws Exception {
serveIotWithRuleWriting(items);
broker.startIfEnabled();
}
private void serveIotWithRuleWriting(DynamoDbItemAccess items) throws Exception {
StorageFactory storageFactory = mock(StorageFactory.class);
when(storageFactory.create(anyString(), anyString(), any()))
.thenAnswer(invocation -> AccountAwareStorageBackend.inMemory("000000000000"));
@@ -1833,7 +2088,31 @@ class IotMqttBrokerServiceTest {
{"sql": "SELECT * FROM 'devices/+/metrics'",
"actions": [{"dynamoDBv2": {"putItem": {"tableName": "metrics"}, "roleArn": "r"}}]}
"""), "eu-west-1");
broker.startIfEnabled();
}
private record ExpiryTimer(long delayMillis, long id, Handler<Long> handler) {
void fire() {
handler.handle(id);
}
}
private List<ExpiryTimer> brokerCapturingExpiryTimers() throws Exception {
List<ExpiryTimer> timers = new CopyOnWriteArrayList<>();
Vertx timerVertx = mock(Vertx.class, AdditionalAnswers.delegatesTo(vertx));
doAnswer(invocation -> {
long delay = invocation.getArgument(0);
Handler<Long> handler = invocation.getArgument(1);
long id = vertx.setTimer(delay, handler);
timers.add(new ExpiryTimer(delay, id, handler));
return id;
}).when(timerVertx).setTimer(anyLong(), any());
broker = new IotMqttBrokerService(config, timerVertx, iotService, customAuthorizer, registry, nanoTime::get);
serveIotWithRuleWriting(mock(DynamoDbItemAccess.class));
return timers;
}
private static List<Long> delays(List<ExpiryTimer> timers) {
return timers.stream().map(ExpiryTimer::delayMillis).toList();
}
/** Starts the broker over a real {@link IotService} whose recorder sees every publish the broker hands it. */
@@ -1894,9 +2173,13 @@ class IotMqttBrokerServiceTest {
}
private static MqttSubscribeMessage subscribeMessage(String topicFilter) {
return subscribeMessage(topicFilter, MqttQoS.AT_MOST_ONCE);
}
private static MqttSubscribeMessage subscribeMessage(String topicFilter, MqttQoS qos) {
MqttTopicSubscription requested = mock(MqttTopicSubscription.class);
when(requested.topicName()).thenReturn(topicFilter);
when(requested.qualityOfService()).thenReturn(MqttQoS.AT_MOST_ONCE);
when(requested.qualityOfService()).thenReturn(qos);
MqttSubscribeMessage message = mock(MqttSubscribeMessage.class);
when(message.topicSubscriptions()).thenReturn(List.of(requested));
return message;
@@ -2053,6 +2336,42 @@ class IotMqttBrokerServiceTest {
return client;
}
private static MqttEndpoint mqtt5Endpoint(String clientId, int sessionExpiry) {
MqttEndpoint endpoint = persistentEndpoint(clientId);
when(endpoint.protocolVersion()).thenReturn(5);
when(endpoint.connectProperties()).thenReturn(sessionExpiryProperties(sessionExpiry));
return endpoint;
}
private static MqttProperties sessionExpiryProperties(int sessionExpiry) {
MqttProperties properties = new MqttProperties();
properties.add(new MqttProperties.IntegerProperty(
MqttProperties.MqttPropertyType.SESSION_EXPIRY_INTERVAL.value(), sessionExpiry));
return properties;
}
private static void disconnectWithSessionExpiry(MqttEndpoint endpoint, int sessionExpiry) {
ArgumentCaptor<Handler<MqttDisconnectMessage>> disconnect = handlerCaptor();
verify(endpoint).disconnectMessageHandler(disconnect.capture());
disconnect.getValue().handle(MqttDisconnectMessage.create(
MqttDisconnectReasonCode.NORMAL, sessionExpiryProperties(sessionExpiry)));
}
private static void subscribeQos1(MqttEndpoint endpoint, String topicFilter) {
ArgumentCaptor<Handler<MqttSubscribeMessage>> subscribe = handlerCaptor();
verify(endpoint).subscribeHandler(subscribe.capture());
subscribe.getValue().handle(subscribeMessage(topicFilter, MqttQoS.AT_LEAST_ONCE));
}
private static MqttEndpoint persistentEndpoint(String clientId) {
MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.clientIdentifier()).thenReturn(clientId);
when(endpoint.protocolVersion()).thenReturn(4);
when(endpoint.isCleanSession()).thenReturn(false);
when(endpoint.isConnected()).thenReturn(true);
return endpoint;
}
private MqttClient connectPlain(String clientId) throws MqttException {
MqttClient client = new MqttClient("tcp://127.0.0.1:" + plainPort, clientId, new MemoryPersistence());
MqttConnectOptions options = new MqttConnectOptions();
@@ -47,6 +47,7 @@ import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
@@ -818,6 +819,136 @@ class IotMqttEnabledIntegrationTest {
}
}
@Test
void persistentSessionResumesItsSubscriptionsAndReceivesTheQos1MessagesQueuedWhileOffline() throws Exception {
String clientId = uniqueClientId("persistent");
String topic = "devices/" + clientId + "/commands";
try (MqttTestClient device = MqttTestClient.connect(clientId, false)) {
assertFalse(device.sessionPresent());
device.subscribe(topic, 1);
}
awaitSessionsEnded(clientId, 1);
try (MqttTestClient publisher = connectMqtt("persistent-pub")) {
publisher.publish(topic, json("{\"seq\":0}"), 0);
publisher.publish(topic, json("{\"seq\":1}"), 1);
}
try (MqttTestClient device = MqttTestClient.connect(clientId, false)) {
assertTrue(device.sessionPresent());
MqttPublish queued = device.takePublish();
assertEquals(topic, queued.topic());
assertArrayEquals(json("{\"seq\":1}"), queued.payload());
assertEquals(1, queued.qos());
try (MqttTestClient publisher = connectMqtt("persistent-live-pub")) {
publisher.publish(topic, json("{\"seq\":2}"), 1);
}
device.assertNextPublish(topic, json("{\"seq\":2}"));
}
}
@Test
void cleanSessionConnectDiscardsThePersistentSession() throws Exception {
String clientId = uniqueClientId("persistent-discarded");
String topic = "devices/" + clientId + "/commands";
try (MqttTestClient device = MqttTestClient.connect(clientId, false)) {
device.subscribe(topic, 1);
}
awaitSessionsEnded(clientId, 1);
try (MqttTestClient publisher = connectMqtt("persistent-discarded-pub")) {
publisher.publish(topic, json("{}"), 1);
}
byte[] marker = json("{\"marker\":true}");
try (MqttTestClient device = MqttTestClient.connect(clientId, true)) {
assertFalse(device.sessionPresent());
device.subscribe(topic, 1);
try (MqttTestClient publisher = connectMqtt("persistent-discarded-pub")) {
publisher.publish(topic, marker, 1);
}
device.assertNextPublish(topic, marker);
}
awaitSessionsEnded(clientId, 2);
String markerTopic = "devices/" + clientId + "/marker";
try (MqttTestClient device = MqttTestClient.connect(clientId, false)) {
assertFalse(device.sessionPresent());
device.subscribe(markerTopic, 1);
try (MqttTestClient publisher = connectMqtt("persistent-discarded-pub")) {
publisher.publish(topic, json("{}"), 1);
publisher.publish(markerTopic, marker, 1);
}
device.assertNextPublish(markerTopic, marker);
}
}
@Test
void listSubscriptionsReportsADisconnectedPersistentSession() throws Exception {
String clientId = uniqueClientId("persistent-listed");
String topic = "devices/" + clientId + "/commands";
try (MqttTestClient device = MqttTestClient.connect(clientId, false)) {
device.subscribe(topic, 1);
}
awaitSessionsEnded(clientId, 1);
given()
.when()
.get("/connections/{clientId}/subscriptions", clientId)
.then()
.statusCode(200)
.body("subscriptions[0].topicFilter", equalTo(topic));
MqttTestClient.connect(clientId, true).close();
awaitSessionsEnded(clientId, 2);
given()
.when()
.get("/connections/{clientId}/subscriptions", clientId)
.then()
.statusCode(404)
.body("__type", equalTo("ResourceNotFoundException"));
}
@Test
void mqtt5SessionWithAnExpiryIntervalResumesWithItsQueuedMessages() throws Exception {
String clientId = uniqueClientId("mqtt5-persistent");
String topic = "devices/" + clientId + "/commands";
try (Mqtt5TestClient device = Mqtt5TestClient.connect(clientId, false, 60L)) {
assertFalse(device.sessionPresent());
device.subscribe(topic, 1);
}
awaitSessionsEnded(clientId, 1);
try (MqttTestClient publisher = connectMqtt("mqtt5-persistent-pub")) {
publisher.publish(topic, json("{}"), 1);
}
try (Mqtt5TestClient device = Mqtt5TestClient.connect(clientId, false, 60L)) {
assertTrue(device.sessionPresent());
MqttPublish queued = device.takePublish();
assertEquals(topic, queued.topic());
assertEquals(1, queued.qos());
}
}
@Test
void mqtt5SessionWithoutAnExpiryIntervalEndsWithItsConnection() throws Exception {
String clientId = uniqueClientId("mqtt5-ephemeral");
try (Mqtt5TestClient device = Mqtt5TestClient.connect(clientId, false, null)) {
device.subscribe("devices/" + clientId + "/commands", 1);
}
awaitSessionsEnded(clientId, 1);
try (Mqtt5TestClient device = Mqtt5TestClient.connect(clientId, false, null)) {
assertFalse(device.sessionPresent());
}
}
private void awaitSessionsEnded(String clientId, int count) throws InterruptedException {
String topic = "$aws/events/presence/disconnected/" + clientId;
awaitPublishedEvents(event -> topic.equals(event.topic()), count, "MQTT session of " + clientId + " did not end");
}
private String createQueue(String queueName) {
return given()
.contentType("application/x-www-form-urlencoded")
@@ -951,16 +1082,20 @@ class IotMqttEnabledIntegrationTest {
}
private void awaitPublishedEvent(String topic, byte[] payload) throws InterruptedException {
awaitPublishedEvents(event -> topic.equals(event.topic()) && Arrays.equals(payload, event.payload()), 1,
"MQTT publish event was not recorded");
}
private void awaitPublishedEvents(Predicate<IotPublishEvent> matches, int count, String failure)
throws InterruptedException {
Instant deadline = Instant.now().plus(Duration.ofSeconds(2));
while (Instant.now().isBefore(deadline)) {
boolean found = eventRecorder.recentEvents().stream()
.anyMatch(event -> topic.equals(event.topic()) && Arrays.equals(payload, event.payload()));
if (found) {
if (eventRecorder.recentEvents().stream().filter(matches).count() >= count) {
return;
}
Thread.sleep(25);
}
throw new AssertionError("MQTT publish event was not recorded");
throw new AssertionError(failure);
}
/** An MQTT 3.1.1 CONNECT over a plain socket, so the test decides exactly which packets follow it. */
@@ -997,12 +1132,17 @@ class IotMqttEnabledIntegrationTest {
private static final class MqttTestClient implements AutoCloseable {
private final MqttClient client;
private final BlockingQueue<MqttPublish> publishes = new LinkedBlockingQueue<>();
private boolean sessionPresent;
private MqttTestClient(MqttClient client) {
this.client = client;
}
static MqttTestClient connect(String clientId) throws MqttException {
return connect(clientId, true);
}
static MqttTestClient connect(String clientId, boolean cleanSession) throws MqttException {
MqttClient client = new MqttClient(BROKER_URI, clientId, new MemoryPersistence());
client.setTimeToWait(10_000);
MqttTestClient testClient = new MqttTestClient(client);
@@ -1020,7 +1160,7 @@ class IotMqttEnabledIntegrationTest {
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
client.connect(connectOptions());
testClient.sessionPresent = client.connectWithResult(connectOptions(cleanSession)).getSessionPresent();
return testClient;
}
@@ -1028,6 +1168,10 @@ class IotMqttEnabledIntegrationTest {
return client.isConnected();
}
boolean sessionPresent() {
return sessionPresent;
}
void subscribe(String topic) throws MqttException {
subscribe(topic, 0);
}
@@ -1049,6 +1193,12 @@ class IotMqttEnabledIntegrationTest {
.orElseThrow(() -> new AssertionError("No MQTT publish received"));
}
void assertNextPublish(String topic, byte[] payload) throws InterruptedException {
MqttPublish next = takePublish();
assertEquals(topic, next.topic());
assertArrayEquals(payload, next.payload());
}
void awaitDisconnected() throws InterruptedException {
Instant deadline = Instant.now().plus(Duration.ofSeconds(2));
while (Instant.now().isBefore(deadline)) {
@@ -1074,9 +1224,9 @@ class IotMqttEnabledIntegrationTest {
client.close();
}
private static MqttConnectOptions connectOptions() {
private static MqttConnectOptions connectOptions(boolean cleanSession) {
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);
options.setCleanSession(cleanSession);
options.setConnectionTimeout(2);
options.setKeepAliveInterval(60);
options.setAutomaticReconnect(false);
@@ -1087,12 +1237,18 @@ class IotMqttEnabledIntegrationTest {
private static final class Mqtt5TestClient implements AutoCloseable {
private final org.eclipse.paho.mqttv5.client.MqttClient client;
private final BlockingQueue<MqttPublish> publishes = new LinkedBlockingQueue<>();
private boolean sessionPresent;
private Mqtt5TestClient(org.eclipse.paho.mqttv5.client.MqttClient client) {
this.client = client;
}
static Mqtt5TestClient connect(String clientId) throws org.eclipse.paho.mqttv5.common.MqttException {
return connect(clientId, true, null);
}
static Mqtt5TestClient connect(String clientId, boolean cleanStart, Long sessionExpiryInterval)
throws org.eclipse.paho.mqttv5.common.MqttException {
org.eclipse.paho.mqttv5.client.MqttClient client =
new org.eclipse.paho.mqttv5.client.MqttClient(BROKER_URI, clientId, null);
Mqtt5TestClient testClient = new Mqtt5TestClient(client);
@@ -1124,7 +1280,8 @@ class IotMqttEnabledIntegrationTest {
}
});
client.setTimeToWait(10_000);
client.connect(connectOptions());
testClient.sessionPresent = client.connectWithResult(connectOptions(cleanStart, sessionExpiryInterval))
.getSessionPresent();
return testClient;
}
@@ -1132,8 +1289,16 @@ class IotMqttEnabledIntegrationTest {
return client.isConnected();
}
boolean sessionPresent() {
return sessionPresent;
}
void subscribe(String topic) throws org.eclipse.paho.mqttv5.common.MqttException {
client.subscribe(topic, 0);
subscribe(topic, 0);
}
void subscribe(String topic, int qos) throws org.eclipse.paho.mqttv5.common.MqttException {
client.subscribe(topic, qos);
}
void publish(String topic, byte[] payload) throws org.eclipse.paho.mqttv5.common.MqttException {
@@ -1161,10 +1326,11 @@ class IotMqttEnabledIntegrationTest {
client.close();
}
private static MqttConnectionOptions connectOptions() {
private static MqttConnectionOptions connectOptions(boolean cleanStart, Long sessionExpiryInterval) {
MqttConnectionOptions options =
new MqttConnectionOptions();
options.setCleanStart(true);
options.setCleanStart(cleanStart);
options.setSessionExpiryInterval(sessionExpiryInterval);
options.setConnectionTimeout(2);
options.setKeepAliveInterval(60);
options.setAutomaticReconnect(false);