mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(iot): deliver data-plane publishes to MQTT subscribers (#6630)
* fix(iot): deliver data-plane publishes to MQTT subscribers A message sent with the IoT Data Publish API stored its retained copy and ran the topic rules, but never reached a connected MQTT client. The data-plane publish now goes through the broker fan-out after the rules, as an MQTT publish does. The fan-out delivers at the lower of the message and subscription QoS, with RETAIN 0, and a retained message sent on subscribe carries RETAIN 1 at the lower of its stored and the subscription QoS, as measured on AWS IoT Core. Publish refuses a qos other than 0 or 1 with AWS's InvalidRequestException messages. Closes floci-io/floci#6627 * fix(iot): allocate packet identifiers for broker publishes Vert.x draws the packet identifier of an outbound publish from an unsynchronized per-endpoint counter. With QoS 1 delivery, two threads fanning out to one client could send two unacknowledged copies under the same identifier. The broker now allocates them from one atomic counter. A retained message stored with a negative qos, which Publish accepted before it validated qos, is sent on subscribe at QoS 0 instead of aborting the replay. * fix(iot): keep MQTT packet identifiers per session One broker-wide counter let copies sent to other clients, QoS 0 included, wrap a client's identifiers while its QoS 1 copy was unacknowledged. Each session now draws QoS 1 identifiers from its own counter, and a QoS 0 copy carries none. * test(iot): share the IoT Data client builder Both IoT Data integration tests now build their IotDataPlaneClient through IotDataRequests.iotDataClient(accessKey), as review asked. The IoT limitations also list that a QoS 1 copy is never retried and has no in-flight limit, where AWS holds further copies at 100 unacknowledged. * test(iot): drive the packet identifier isolation test at QoS 1 QoS 0 copies carry no packet identifier, so the other client's 65,534 copies must be QoS 1 for the test to catch a counter shared by every client. The IoT limitations also say that a data-plane Publish reaches subscribers in every account and region, as the broker has none.
This commit is contained in:
1 parent
f184cce726
commit
c81cf8a630
8 files changed
+284
-41
No files matched your search
@@ -50,6 +50,7 @@ import java.security.cert.CertificateException;
|
||||
import java.security.cert.X509Certificate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -374,7 +375,11 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
void publish(String topic, byte[] payload) {
|
||||
fanOut(topic, payload, false);
|
||||
publish(topic, payload, 0);
|
||||
}
|
||||
|
||||
void publish(String topic, byte[] payload, int qos) {
|
||||
fanOut(topic, payload, qos);
|
||||
}
|
||||
|
||||
boolean disconnectClient(String clientId, boolean cleanSession) {
|
||||
@@ -544,7 +549,8 @@ public class IotMqttBrokerService implements Resettable {
|
||||
device == null ? config.defaultAccountId() : device.accountId(),
|
||||
device == null ? config.defaultRegion() : device.region(),
|
||||
System.currentTimeMillis(),
|
||||
endpoint.keepAliveTimeSeconds());
|
||||
endpoint.keepAliveTimeSeconds(),
|
||||
new AtomicInteger());
|
||||
ClientSession previous = sessionsByClient.put(clientId, session);
|
||||
if (previous != null && previous.endpoint() != endpoint) {
|
||||
endSession(previous, DUPLICATE_CLIENTID);
|
||||
@@ -729,7 +735,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
|
||||
iotService.get().publish(topic, payload, message.isRetain(), message.qosLevel().value(), null,
|
||||
session.clientId(), rules -> evaluateRulesOnWorker(topic, rules));
|
||||
fanOut(topic, payload, false);
|
||||
fanOut(topic, payload, message.qosLevel().value());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -787,26 +793,34 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
}
|
||||
|
||||
private void fanOut(String topic, byte[] payload, boolean retained) {
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private void fanOut(String topic, byte[] payload, int qos) {
|
||||
byte[] safePayload = payload == null ? new byte[0] : payload.clone();
|
||||
for (ClientSession session : sessionsByClient.values()) {
|
||||
if (!session.endpoint().isConnected() || !hasMatchingSubscription(session.clientId(), topic)) {
|
||||
Map<String, Subscription> subscriptions = subscriptionsByClient.get(session.clientId());
|
||||
int granted = subscriptions == null ? -1 : grantedQos(subscriptions.values(), topic);
|
||||
if (!session.endpoint().isConnected() || granted < 0) {
|
||||
continue;
|
||||
}
|
||||
MqttQoS delivered = MqttQoS.valueOf(Math.min(qos, granted));
|
||||
try {
|
||||
session.endpoint().publish(topic, Buffer.buffer(safePayload), MqttQoS.AT_MOST_ONCE, false, retained);
|
||||
session.endpoint().publish(topic, Buffer.buffer(safePayload), delivered, false, false, session.packetId(delivered));
|
||||
} catch (IllegalStateException e) {
|
||||
LOG.debugv("IoT MQTT client {0} closed before the publish on {1} reached it", session.clientId(), topic);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean hasMatchingSubscription(String clientId, String topic) {
|
||||
Map<String, Subscription> subscriptions = subscriptionsByClient.get(clientId);
|
||||
if (subscriptions == null) {
|
||||
return false;
|
||||
}
|
||||
return subscriptions.values().stream().anyMatch(subscription -> topicMatches(subscription.topicFilter(), topic));
|
||||
/** The highest QoS among the subscriptions matching {@code topic}, or -1 when none does. */
|
||||
private int grantedQos(Collection<Subscription> subscriptions, String topic) {
|
||||
return subscriptions.stream()
|
||||
.filter(subscription -> topicMatches(subscription.topicFilter(), topic))
|
||||
.mapToInt(Subscription::qos)
|
||||
.max()
|
||||
.orElse(-1);
|
||||
}
|
||||
|
||||
private void deliverRetained(ClientSession session, List<Subscription> subscriptions) {
|
||||
@@ -818,13 +832,14 @@ public class IotMqttBrokerService implements Resettable {
|
||||
if (!deliveredTopics.add(retained.getTopic())) {
|
||||
continue;
|
||||
}
|
||||
boolean matches = subscriptions.stream()
|
||||
.anyMatch(subscription -> topicMatches(subscription.topicFilter(), retained.getTopic()));
|
||||
if (!matches) {
|
||||
int granted = grantedQos(subscriptions, retained.getTopic());
|
||||
if (granted < 0) {
|
||||
continue;
|
||||
}
|
||||
byte[] payload = Base64.getDecoder().decode(retained.getPayload());
|
||||
session.endpoint().publish(retained.getTopic(), Buffer.buffer(payload), MqttQoS.AT_MOST_ONCE, false, true);
|
||||
// Publish kept a qos outside 0 and 1 as sent before it refused one, so a stored message may carry one.
|
||||
MqttQoS delivered = MqttQoS.valueOf(Math.clamp(retained.getQos(), 0, granted));
|
||||
session.endpoint().publish(retained.getTopic(), Buffer.buffer(payload), delivered, false, true, session.packetId(delivered));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -886,7 +901,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
vertx.runOnContext(ignored -> {
|
||||
iotService.get().publish(topic, payload, false, 0, null, session.clientId(),
|
||||
rules -> evaluateRulesOnWorker(topic, rules, admitted));
|
||||
fanOut(topic, payload, false);
|
||||
fanOut(topic, payload, 0);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -958,7 +973,18 @@ public class IotMqttBrokerService implements Resettable {
|
||||
String accountId,
|
||||
String region,
|
||||
long connectedAt,
|
||||
int keepAliveDuration) {
|
||||
int keepAliveDuration,
|
||||
AtomicInteger packetIds) {
|
||||
|
||||
/**
|
||||
* The packet identifier of a copy sent at {@code qos}: none at QoS 0, otherwise the session's
|
||||
* next, from 1 to 65535. Vert.x draws its own from an unsynchronized counter, which two threads
|
||||
* fanning out to the same client race on.
|
||||
*/
|
||||
int packetId(MqttQoS qos) {
|
||||
// ponytail: no in-flight tracking, so an identifier repeats after 65535 QoS 1 copies to one client; track until PUBACK if Floci ever redelivers.
|
||||
return qos == MqttQoS.AT_MOST_ONCE ? 0 : packetIds.updateAndGet(id -> id % 65535 + 1);
|
||||
}
|
||||
|
||||
HistoryKey historyKey() {
|
||||
return new HistoryKey(accountId, region, clientId);
|
||||
|
||||
@@ -1135,9 +1135,20 @@ public class IotService {
|
||||
publish(topic, payload, false, 0, null, null);
|
||||
}
|
||||
|
||||
/** {@code clientId} is the MQTT client that published, or null for a message that did not come over MQTT. */
|
||||
/**
|
||||
* A publish from outside the broker, such as the data plane Publish API: retained, recorded and
|
||||
* run through the topic rules before it returns, then delivered to the broker's matching
|
||||
* subscribers. {@code clientId} is what a rule's clientid() reports, null for the data plane.
|
||||
*/
|
||||
public void publish(String topic, byte[] payload, boolean retain, int qos, String region, String clientId) {
|
||||
if (qos == 2) {
|
||||
throw new AwsException("InvalidRequestException", "QoS 2 is currently not supported", 400);
|
||||
}
|
||||
if (qos != 0 && qos != 1) {
|
||||
throw new AwsException("InvalidRequestException", "Invalid QoS value: " + qos, 400);
|
||||
}
|
||||
publish(topic, payload, retain, qos, region, clientId, Runnable::run);
|
||||
mqttBrokerService.publish(topic, payload, qos);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user