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

@@ -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) {