mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(iot): MQTT over WebSocket at /mqtt (#3150)
* test(iot): MQTT over WebSocket at /mqtt, failing * feat(http): echo MQTT WebSocket subprotocols * feat(iot): MQTT over WebSocket at /mqtt Bridges a WebSocket upgrade on /mqtt (HTTP and HTTPS) onto the broker's plaintext listener, so wss://host:443/mqtt works on the 443:4566 mapping with the same certificate as HTTPS and no extra listener or config. * docs(iot): MQTT over WebSocket at /mqtt * feat(iot): do not queue the /mqtt handshake behind ordered blocking tasks * fix(iot): forward only binary WebSocket frames to the broker One frame handler decides per frame: text closes with 1003, binary and continuation frames are written to the broker socket, control frames are left to Vert.x. Nothing else reads the frames, so a text payload can never reach the MQTT stream. * test(iot): AWS contract and framing tests for MQTT over WebSocket Handshake: only GET upgrades (405), unsupported version is 426, each MQTT subprotocol name is echoed and the first supported offer wins, ping gets pong, non-upgrade requests fall through. Framing (MQTT 3.1.1 section 6): a CONNECT split across two frames, two packets in one frame, garbage bytes and a frame over the transport limit. Session semantics as on AWS: MQTT 5 over wss, client id takeover across transports, retained messages, QoS 2 disconnects, shadow topics, topic rules, keep-alive pings and the IoT Data connection APIs on a WebSocket session. * test(iot): log the tolerated exceptions in the WebSocket contract tests * test(iot): pin the MQTT TLS port and the unrelated-subprotocol handshake The profile pins floci.services.iot.mqtt.tls-port now that #3142 opens 8883 whenever TLS is on. A client offering only graphql-ws on an API Gateway WebSocket path still connects, with no subprotocol echoed: the server-wide MQTT list does not affect other WebSocket routes. * test(iot): pin the deployment claims of MQTT over WebSocket Every claim the docs and comments make now has a test that fails without the behaviour: ws and wss share one port through TlsProxyServer (the 443:4566 path), a hostname learned by ensureHost serves /mqtt to a client verifying that name, the first upgrade starts a lazy broker (also eight at once, and again after a stop), a text frame or an abrupt TCP drop after a live CONNECT frees the broker session, 30 connect and disconnect cycles leave nothing behind, and the burst is 1000 messages. * test(iot): force-close the Paho client the broker stop left behind * test(iot): wait for the dropped session before closing the Paho client
This commit is contained in:
1 parent
006f3c77c9
commit
c4027bbf54
9 files changed
+1808
-3
No files matched your search
@@ -4,6 +4,8 @@ import io.quarkus.vertx.http.HttpServerOptionsCustomizer;
|
||||
import io.vertx.core.http.HttpServerOptions;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Customizes Vert.x HTTP server options for Floci's requirements.
|
||||
*
|
||||
@@ -19,6 +21,8 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
* defaults to 64 KB per frame, which causes Netty to silently reject larger
|
||||
* frames before the application-level size check in
|
||||
* {@code WebSocketHandler} can fire.</li>
|
||||
* <li>Echoes the MQTT WebSocket subprotocol names, so MQTT over WebSocket clients
|
||||
* complete their handshake on {@code /mqtt}.</li>
|
||||
* </ul>
|
||||
*
|
||||
* The overall request body size is still bounded by
|
||||
@@ -41,17 +45,29 @@ public class HttpOptionsCustomizer implements HttpServerOptionsCustomizer {
|
||||
*/
|
||||
private static final int MAX_WS_MESSAGE_SIZE = 256 * 1024;
|
||||
|
||||
/**
|
||||
* Subprotocol names an MQTT over WebSocket client offers in {@code Sec-WebSocket-Protocol}
|
||||
* (AWS IoT documents {@code mqtt}; the others are the names Vert.x MQTT accepts). Vert.x only
|
||||
* echoes a name from this list, and Paho and the AWS Device SDKs refuse a handshake whose
|
||||
* response does not echo one. Netty completes a handshake that asks for any other name without
|
||||
* the header, so API Gateway WebSocket clients are unaffected.
|
||||
*/
|
||||
static final List<String> MQTT_WEBSOCKET_SUBPROTOCOLS = List.of("mqtt", "mqttv3.1", "mqttv3.1.1");
|
||||
|
||||
@Override
|
||||
public void customizeHttpServer(HttpServerOptions options) {
|
||||
options.setMaxFormAttributeSize(-1);
|
||||
options.setMaxWebSocketFrameSize(MAX_WS_FRAME_SIZE);
|
||||
options.setMaxWebSocketMessageSize(MAX_WS_MESSAGE_SIZE);
|
||||
customize(options);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void customizeHttpsServer(HttpServerOptions options) {
|
||||
customize(options);
|
||||
}
|
||||
|
||||
private static void customize(HttpServerOptions options) {
|
||||
options.setMaxFormAttributeSize(-1);
|
||||
options.setMaxWebSocketFrameSize(MAX_WS_FRAME_SIZE);
|
||||
options.setMaxWebSocketMessageSize(MAX_WS_MESSAGE_SIZE);
|
||||
options.setWebSocketSubProtocols(MQTT_WEBSOCKET_SUBPROTOCOLS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package io.github.hectorvent.floci.services.iot;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.ServerWebSocket;
|
||||
import io.vertx.core.net.NetClient;
|
||||
import io.vertx.core.net.NetSocket;
|
||||
import io.vertx.ext.web.Router;
|
||||
import io.vertx.ext.web.RoutingContext;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.enterprise.event.Observes;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
/**
|
||||
* Serves MQTT over WebSocket at {@code /mqtt} on the HTTP and HTTPS ports, the path and port AWS
|
||||
* IoT uses for browser clients, the Device SDK's WebSocket transport and secure tunnelling. Frames
|
||||
* are piped byte for byte to the broker's plaintext listener, so every broker feature and every
|
||||
* authorization rule applies without a second code path. No client certificate is involved: on
|
||||
* AWS this path authenticates by SigV4 or a custom authorizer, and the broker stays permissive
|
||||
* for it.
|
||||
*
|
||||
* <p>Everything for one session runs on the event loop of the WebSocket's connection, the
|
||||
* broker socket included, so the handlers below never race each other.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class IotMqttWebSocketBridge {
|
||||
|
||||
static final String PATH = "/mqtt";
|
||||
private static final Logger LOG = Logger.getLogger(IotMqttWebSocketBridge.class);
|
||||
private static final short CLOSE_UNSUPPORTED_DATA = 1003;
|
||||
private static final short CLOSE_INTERNAL_ERROR = 1011;
|
||||
|
||||
private final EmulatorConfig config;
|
||||
private final Vertx vertx;
|
||||
private final NetClient client;
|
||||
private final IotMqttBrokerService broker;
|
||||
|
||||
@Inject
|
||||
public IotMqttWebSocketBridge(EmulatorConfig config, Vertx vertx, IotMqttBrokerService broker) {
|
||||
this.config = config;
|
||||
this.vertx = vertx;
|
||||
this.client = vertx.createNetClient();
|
||||
this.broker = broker;
|
||||
}
|
||||
|
||||
void init(@Observes Router router) {
|
||||
router.route(PATH).handler(this::upgrade);
|
||||
}
|
||||
|
||||
private void upgrade(RoutingContext ctx) {
|
||||
if (!"websocket".equalsIgnoreCase(ctx.request().getHeader("Upgrade"))) {
|
||||
ctx.next();
|
||||
return;
|
||||
}
|
||||
// startIfEnabled blocks on the listen, and ordered blocking tasks queue behind every other
|
||||
// blocking task of this event loop (a Lambda invocation, say); the start is idempotent and
|
||||
// synchronized, so the handshake need not wait its turn.
|
||||
vertx.executeBlocking(() -> {
|
||||
broker.startIfEnabled();
|
||||
return broker.isRunning();
|
||||
}, false).onSuccess(running -> {
|
||||
if (!running) {
|
||||
ctx.response().setStatusCode(503).end();
|
||||
return;
|
||||
}
|
||||
ctx.request().toWebSocket()
|
||||
.onSuccess(this::pipeToBroker)
|
||||
.onFailure(error -> rejectUpgrade(ctx, error));
|
||||
}).onFailure(error -> {
|
||||
LOG.warnv("MQTT WebSocket upgrade refused, the broker did not start: {0}", error.getMessage());
|
||||
ctx.response().setStatusCode(503).end();
|
||||
});
|
||||
}
|
||||
|
||||
private static void rejectUpgrade(RoutingContext ctx, Throwable error) {
|
||||
LOG.debugv("MQTT WebSocket upgrade failed: {0}", error.getMessage());
|
||||
if (!ctx.response().ended()) {
|
||||
ctx.response().setStatusCode(400).end();
|
||||
}
|
||||
}
|
||||
|
||||
private void pipeToBroker(ServerWebSocket ws) {
|
||||
ws.pause();
|
||||
int port = config.services().iot().mqtt().port();
|
||||
String host = brokerHost();
|
||||
client.connect(port, host)
|
||||
.onSuccess(socket -> {
|
||||
if (ws.isClosed()) {
|
||||
socket.close();
|
||||
return;
|
||||
}
|
||||
wire(ws, socket);
|
||||
ws.resume();
|
||||
})
|
||||
.onFailure(error -> {
|
||||
LOG.warnv("MQTT WebSocket bridge could not reach the broker on {0}:{1}: {2}",
|
||||
host, port, error.getMessage());
|
||||
ws.close(CLOSE_INTERNAL_ERROR, "MQTT broker unavailable");
|
||||
});
|
||||
}
|
||||
|
||||
private static void wire(ServerWebSocket ws, NetSocket socket) {
|
||||
ws.frameHandler(frame -> {
|
||||
if (ws.isClosed()) {
|
||||
return;
|
||||
}
|
||||
if (frame.isText()) {
|
||||
ws.close(CLOSE_UNSUPPORTED_DATA, "MQTT over WebSocket is binary");
|
||||
return;
|
||||
}
|
||||
if (!frame.isBinary() && !frame.isContinuation()) {
|
||||
return;
|
||||
}
|
||||
socket.write(frame.binaryData());
|
||||
if (socket.writeQueueFull()) {
|
||||
ws.pause();
|
||||
socket.drainHandler(ignored -> ws.resume());
|
||||
}
|
||||
});
|
||||
ws.closeHandler(ignored -> socket.close());
|
||||
ws.exceptionHandler(error -> socket.close());
|
||||
|
||||
socket.handler(bytes -> {
|
||||
if (ws.isClosed()) {
|
||||
return;
|
||||
}
|
||||
ws.writeBinaryMessage(bytes);
|
||||
if (ws.writeQueueFull()) {
|
||||
socket.pause();
|
||||
ws.drainHandler(ignored -> socket.resume());
|
||||
}
|
||||
});
|
||||
socket.closeHandler(ignored -> ws.close());
|
||||
socket.exceptionHandler(error -> ws.close(CLOSE_INTERNAL_ERROR, "MQTT broker connection failed"));
|
||||
}
|
||||
|
||||
/** The broker binds {@code 0.0.0.0} by default, which is not a connect target; loopback is. */
|
||||
private String brokerHost() {
|
||||
String host = config.services().iot().mqtt().host();
|
||||
return "0.0.0.0".equals(host) ? "127.0.0.1" : host;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user