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:
Mario Toffia authored and GitHub committed 2026-10-26 11:43:50 -04:00
1 parent f184cce726
commit c81cf8a630
8 files changed
+284 -41

No files matched your search

@@ -2,6 +2,8 @@ package io.github.hectorvent.floci.services.iot;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.List;
@@ -177,6 +179,29 @@ class IotDataIntegrationTest {
.body("__type", equalTo("ResourceNotFoundException"));
}
/** Measured on AWS IoT: a QoS other than 0 or 1 is refused before the message is retained. */
@ParameterizedTest
@CsvSource({"2,QoS 2 is currently not supported", "-1,Invalid QoS value: -1", "7,Invalid QoS value: 7"})
void publishRefusesAQosOtherThanZeroOrOne(int qos, String message) {
given()
.contentType("text/plain")
.queryParam("retain", true)
.queryParam("qos", qos)
.body("refused")
.when()
.post("/topics/devices/qos/refused")
.then()
.statusCode(400)
.body("__type", equalTo("InvalidRequestException"))
.body("message", equalTo(message));
given()
.when()
.get("/retainedMessage/devices/qos/refused")
.then()
.statusCode(404);
}
@Test
void shadowNullDeletesPropertiesAndVersionConflicts() {
given()
@@ -69,6 +69,7 @@ import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedKeyManager;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.net.InetSocketAddress;
@@ -83,6 +84,7 @@ import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -493,7 +495,7 @@ class IotMqttBrokerServiceTest {
subscribeHandler.set(invocation.getArgument(0));
return closing;
});
when(closing.publish(anyString(), any(), any(), anyBoolean(), anyBoolean()))
when(closing.publish(anyString(), any(), any(), anyBoolean(), anyBoolean(), anyInt()))
.thenThrow(new IllegalStateException("the connection closed"));
MqttTopicSubscription requested = mock(MqttTopicSubscription.class);
when(requested.topicName()).thenReturn("devices/+/metrics");
@@ -511,7 +513,7 @@ class IotMqttBrokerServiceTest {
broker.publish("devices/d1/metrics", "{\"t\":1}".getBytes(StandardCharsets.UTF_8));
verify(closing).publish(eq("devices/d1/metrics"), any(), any(), anyBoolean(), anyBoolean());
verify(closing).publish(eq("devices/d1/metrics"), any(), any(), anyBoolean(), anyBoolean(), anyInt());
assertEquals("{\"t\":1}", fannedOut.poll(10, TimeUnit.SECONDS), "the other subscriber got its copy");
} finally {
disconnect(subscriber);
@@ -892,6 +894,74 @@ class IotMqttBrokerServiceTest {
assertFalse(disconnected.get(0).get("clientInitiatedDisconnect").asBoolean());
}
/**
* A retained message whose stored QoS is negative, which Publish kept as sent before it refused
* a qos outside 0 and 1, is still sent on subscribe, at QoS 0.
*/
@Test
void aRetainedMessageStoredWithANegativeQosIsStillSentOnSubscribe() throws Exception {
startBrokerRecordingPublishes();
iotService.get().publish("legacy/status", "{}".getBytes(StandardCharsets.UTF_8), true, -1, null, null, Runnable::run);
BlockingQueue<String> topics = new LinkedBlockingQueue<>();
MqttClient subscriber = subscribedPlain("legacy", "legacy/status", topics);
try {
assertEquals("legacy/status", topics.poll(10, TimeUnit.SECONDS));
} finally {
disconnect(subscriber);
}
}
/**
* QoS 1 copies fanned out to one client from several threads, none acknowledged yet, each carry
* their own packet identifier, as MQTT requires.
*/
@Test
void concurrentQos1CopiesToOneClientCarryDistinctPacketIdentifiers() throws Exception {
startBrokerRecordingPublishes();
int threads = 8;
int perThread = 2000;
ExecutorService publishers = Executors.newFixedThreadPool(threads);
try (Socket socket = rawConnect("packet-ids")) {
DataInputStream in = rawSubscribeQos1(socket, "ids/#");
for (int thread = 0; thread < threads; thread++) {
publishers.execute(() -> {
for (int i = 0; i < perThread; i++) {
broker.publish("ids/x", new byte[] {1}, 1);
}
});
}
Set<Integer> packetIds = new HashSet<>();
for (int i = 0; i < threads * perThread; i++) {
packetIds.add(readQos1PublishPacketId(in));
}
assertEquals(threads * perThread, packetIds.size(), "no two unacknowledged copies share a packet identifier");
} finally {
publishers.shutdownNow();
}
}
/** QoS 1 copies sent to other clients do not use up the packet identifiers of a client whose QoS 1 copy is unacknowledged. */
@Test
void anotherClientsTrafficDoesNotRecycleAPacketIdentifierStillInFlight() throws Exception {
startBrokerRecordingPublishes();
try (Socket busy = rawConnect("busy"); Socket socket = rawConnect("slow")) {
rawSubscribeQos1(busy, "busy/#");
DataInputStream in = rawSubscribeQos1(socket, "slow/#");
broker.publish("slow/first", new byte[] {1}, 1);
int first = readQos1PublishPacketId(in);
for (int i = 0; i < 65_534; i++) {
broker.publish("busy/x", new byte[] {1}, 1);
}
broker.publish("slow/second", new byte[] {2}, 1);
assertNotEquals(first, readQos1PublishPacketId(in), "the first copy was never acknowledged");
}
}
@Test
void aQos2PublishEndsTheSessionWithAClientError() throws Exception {
startBrokerRecordingPublishes();
@@ -1052,7 +1122,7 @@ class IotMqttBrokerServiceTest {
});
broker.handleEndpoint(departing, false);
verify(subscriber, timeout(10_000))
.publish(eq("$aws/events/presence/connected/departing"), any(), any(), anyBoolean(), anyBoolean());
.publish(eq("$aws/events/presence/connected/departing"), any(), any(), anyBoolean(), anyBoolean(), anyInt());
ExecutorService departingEventLoop = Executors.newSingleThreadExecutor();
subscriberMonitor.lock();
@@ -1066,7 +1136,7 @@ class IotMqttBrokerServiceTest {
departingEventLoop.shutdown();
}
verify(subscriber, timeout(10_000))
.publish(eq("$aws/events/presence/disconnected/departing"), any(), any(), anyBoolean(), anyBoolean());
.publish(eq("$aws/events/presence/disconnected/departing"), any(), any(), anyBoolean(), anyBoolean(), anyInt());
}
/** A PUBLISH, SUBSCRIBE, UNSUBSCRIBE or PUBACK counts as traffic for the keep-alive, as a PINGREQ does. */
@@ -1190,8 +1260,8 @@ class IotMqttBrokerServiceTest {
broker.publish("stale/topic", "{}".getBytes(StandardCharsets.UTF_8));
broker.publish("kept/topic", "{}".getBytes(StandardCharsets.UTF_8));
verify(current, timeout(10_000)).publish(eq("kept/topic"), any(), any(), anyBoolean(), anyBoolean());
verify(current, never()).publish(eq("stale/topic"), any(), any(), anyBoolean(), anyBoolean());
verify(current, timeout(10_000)).publish(eq("kept/topic"), any(), any(), anyBoolean(), anyBoolean(), anyInt());
verify(current, never()).publish(eq("stale/topic"), any(), any(), anyBoolean(), anyBoolean(), anyInt());
}
/**
@@ -1893,6 +1963,37 @@ class IotMqttBrokerServiceTest {
socket.getOutputStream().write(packet(0x30 | (qos << 1), body.toByteArray()));
}
/** Subscribes a raw client to one filter at QoS 1 and returns its stream once the broker granted it. */
private static DataInputStream rawSubscribeQos1(Socket socket, String topicFilter) throws IOException {
ByteArrayOutputStream subscribe = new ByteArrayOutputStream();
subscribe.write(0x00);
subscribe.write(0x01);
writeUtf8(subscribe, topicFilter);
subscribe.write(0x01);
socket.getOutputStream().write(packet(0x82, subscribe.toByteArray()));
DataInputStream in = new DataInputStream(socket.getInputStream());
assertArrayEquals(new byte[] {(byte) 0x90, 0x03, 0x00, 0x01, 0x01}, in.readNBytes(5), "SUBACK granting QoS 1");
return in;
}
/** Reads one QoS 1 PUBLISH and returns its packet identifier. */
private static int readQos1PublishPacketId(DataInputStream in) throws IOException {
assertEquals(0x32, in.readUnsignedByte(), "a QoS 1 PUBLISH without DUP or RETAIN");
int remaining = 0;
int multiplier = 1;
int encoded;
do {
encoded = in.readUnsignedByte();
remaining += (encoded & 127) * multiplier;
multiplier *= 128;
} while ((encoded & 128) != 0);
int topicLength = in.readUnsignedShort();
in.skipNBytes(topicLength);
int packetId = in.readUnsignedShort();
in.skipNBytes(remaining - topicLength - 4);
return packetId;
}
private static byte[] packet(int type, byte[] body) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(type);
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.iot;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.testing.IotDataRequests;
import io.github.hectorvent.floci.testing.IotMqttTlsProfile;
import io.github.hectorvent.floci.testing.PartitionCleanup;
import io.quarkus.test.junit.QuarkusTest;
@@ -19,6 +20,8 @@ import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -194,11 +197,71 @@ class IotMqttEnabledIntegrationTest {
MqttPublish received = subscriber.takePublish();
assertEquals(topic, received.topic());
assertArrayEquals(payload, received.payload());
assertEquals(1, received.qos(), "measured on AWS IoT: the lower of the publish and subscription QoS");
}
awaitPublishedEvent(topic, payload);
}
/** Measured on AWS IoT: a data plane Publish reaches every matching subscriber and runs the matching rule once. */
@Test
void dataPlanePublishReachesAWildcardSubscriberAndFiresItsRuleOnce() throws Exception {
String prefix = "dataplane/" + System.nanoTime();
String queueUrl = createQueue("dataplane-rule-" + System.nanoTime());
String rule = "dataPlaneRule" + System.nanoTime();
createSqsRule(rule, "SELECT * FROM '" + prefix + "/b'", queueUrl);
try (MqttTestClient subscriber = connectMqtt("dataplane-sub");
IotDataPlaneClient iotData = IotDataRequests.iotDataClient("test")) {
subscriber.subscribe(prefix + "/#", 1);
iotData.publish(request -> request.topic(prefix + "/b").qos(1).payload(SdkBytes.fromUtf8String("{\"cmd\":\"on\"}")));
MqttPublish received = subscriber.takePublish();
assertEquals(prefix + "/b", received.topic());
assertEquals("{\"cmd\":\"on\"}", new String(received.payload(), StandardCharsets.UTF_8));
assertEquals(1, received.qos());
assertFalse(received.retained(), "a live copy carries RETAIN 0");
List<JsonNode> fired = awaitMessages(queueUrl, 1);
assertEquals(1, fired.size(), "the rule fired once: " + fired);
assertEquals("on", fired.get(0).path("cmd").asText());
} finally {
deleteRule(rule);
}
}
/**
* Measured on AWS IoT: a retained data plane Publish reaches a current subscriber as a live copy, and a later
* subscriber of its exact topic as the retained message, each at the lower of the publish and subscription QoS.
*/
@Test
void retainedDataPlanePublishReachesACurrentAndALaterSubscriber() throws Exception {
String prefix = "dataplane/" + System.nanoTime();
String topic = prefix + "/config";
try (MqttTestClient current = connectMqtt("dataplane-current");
IotDataPlaneClient iotData = IotDataRequests.iotDataClient("test")) {
current.subscribe(prefix + "/#", 0);
iotData.publish(request -> request.topic(topic).qos(1).retain(true).payload(SdkBytes.fromUtf8String("config-v1")));
cleanup.register(() -> given().contentType("application/octet-stream").queryParam("retain", true)
.body(new byte[0]).when().post("/topics/" + topic).then().statusCode(200));
MqttPublish live = current.takePublish();
assertEquals("config-v1", new String(live.payload(), StandardCharsets.UTF_8));
assertEquals(0, live.qos());
assertFalse(live.retained(), "a live copy carries RETAIN 0");
try (MqttTestClient later = connectMqtt("dataplane-later")) {
later.subscribe(topic, 1);
MqttPublish retained = later.takePublish();
assertEquals(topic, retained.topic());
assertEquals("config-v1", new String(retained.payload(), StandardCharsets.UTF_8));
assertEquals(1, retained.qos());
assertTrue(retained.retained());
}
}
}
@Test
void publishOfTheAwsMaximumPayloadIsDelivered() throws Exception {
String topic = "phase6/limit/" + System.nanoTime();
@@ -891,7 +954,7 @@ class IotMqttEnabledIntegrationTest {
out.writeBytes(bytes);
}
private record MqttPublish(String topic, byte[] payload) {
private record MqttPublish(String topic, byte[] payload, int qos, boolean retained) {
}
private static final class MqttTestClient implements AutoCloseable {
@@ -913,7 +976,7 @@ class IotMqttEnabledIntegrationTest {
@Override
public void messageArrived(String topic, MqttMessage message) {
testClient.publishes.add(new MqttPublish(topic, message.getPayload()));
testClient.publishes.add(new MqttPublish(topic, message.getPayload(), message.getQos(), message.isRetained()));
}
@Override
@@ -1007,7 +1070,7 @@ class IotMqttEnabledIntegrationTest {
@Override
public void messageArrived(String topic, org.eclipse.paho.mqttv5.common.MqttMessage message) {
testClient.publishes.add(new MqttPublish(topic, message.getPayload()));
testClient.publishes.add(new MqttPublish(topic, message.getPayload(), message.getQos(), message.isRetained()));
}
@Override
@@ -4,20 +4,15 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.services.iot.model.IotRetainedMessage;
import io.github.hectorvent.floci.testing.IotDataRequests;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import jakarta.ws.rs.core.Response;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.core.SdkBytes;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient;
import java.net.URI;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
@@ -71,11 +66,7 @@ class IotRetainedTimestampIntegrationTest {
String authorization = "AWS4-HMAC-SHA256 Credential=" + account
+ "/20261023/us-east-1/iotdata/aws4_request, SignedHeaders=host, Signature=test";
ObjectMapper mapper = new ObjectMapper();
try (IotDataPlaneClient client = IotDataPlaneClient.builder()
.endpointOverride(URI.create("http://localhost:" + RestAssured.port))
.httpClientBuilder(UrlConnectionHttpClient.builder()).region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(account, "test")))
.build()) {
try (IotDataPlaneClient client = IotDataRequests.iotDataClient(account)) {
long before = System.currentTimeMillis();
client.publish(request -> request.topic(topic).qos(qos).retain(true).payload(SdkBytes.fromUtf8String("online")));
long after = System.currentTimeMillis();
@@ -0,0 +1,24 @@
package io.github.hectorvent.floci.testing;
import io.restassured.RestAssured;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iotdataplane.IotDataPlaneClient;
import java.net.URI;
public final class IotDataRequests {
private IotDataRequests() {}
/** An IoT Data client on the test instance in us-east-1, signing with {@code accessKey}, which Floci reads as the account when it is one. */
public static IotDataPlaneClient iotDataClient(String accessKey) {
return IotDataPlaneClient.builder()
.endpointOverride(URI.create("http://localhost:" + RestAssured.port))
.httpClientBuilder(UrlConnectionHttpClient.builder())
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey, "test")))
.build();
}
}