Rust

MQTT

Building blocks for MQTT 5.0 and 3.1.1 brokers: the packet codec, a subscription trie, per-connection delivery state, a broker over adapters (Tokio on TCP, TLS and WebSocket; in-memory) with keep-alive timers, and a client.
Rust 5,330 lines (3,118 code)split
PartCodeCommentsBlankTotalFiles
Rust source3,1181,7944185,33021

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-mqtt = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with MQTT, each a complete program you can copy and run.

An MQTT broker keeps many clients connected, authenticates them, remembers what each subscribed to, and delivers every message published on a topic to the clients whose filters match it. This library gives you the pieces to build one that speaks MQTT 5.0 and 3.1.1: a packet codec, a subscription store, per-connection delivery state, and a Server that runs your decisions (a Handler) on an adapter: Tokio on TCP, TLS and WebSocket listeners, or Memory in process for tests. A Client connects to any broker. This guide covers the common tasks.

Decode what a client sends

On a TCP connection each read is one packet; on WebSocket a message can hold several packets, or part of one, so split the stream with frames and keep the remainder. Packet::parse reads the fixed header; the packet types decode the rest. A Publish decodes differently for each protocol version, so pass the level the client's CONNECT gave.

Rust
use utopia_mqtt::packet::{frames, Connect, Kind, Packet, Publish};
use utopia_mqtt::spec::{v3, v5};

let mut stream = v3::connect(b"sensor-7", 30, true, b"", b"");
stream.extend(v3::publish(b"sensors/7/temp", b"21.5", 0, 0, false));
stream.extend(&v5::puback(b"\x00\x01")[..2]); // the start of the next packet

let (packets, rest) = frames(&stream);
assert_eq!((packets.len(), rest.len()), (2, 2));

let connect = Connect::decode(Packet::parse(packets[0])?.body)?;
assert_eq!((connect.client_id.as_slice(), connect.keep_alive), (&b"sensor-7"[..], 30));

let packet = Packet::parse(packets[1])?;
assert_eq!(packet.kind, Kind::Publish);
let publish = Publish::decode(&packet, connect.protocol_level)?;
assert_eq!(publish.payload, b"21.5");

Answer in the client's protocol version

spec::v3 and spec::v5 encode every packet. 5.0 acknowledgements carry a reason code and a property block; 3.1.1 ones have neither. Properties are typed by their identifier, and a User Property carries one key and value.

Rust
use utopia_mqtt::spec::{v3, v5};
use utopia_mqtt::{Properties, Property};

let welcome = Properties::new()
    .with(Property::bytes(Property::REASON_STRING, "welcome"))
    .with(Property::user("region", "eu"));
let connack = v5::connack(v5::REASON_SUCCESS, Some(&welcome))?;
assert_eq!(&connack[..4], b"\x20\x1a\x00\x00");

assert_eq!(v3::connack(v3::RETURN_NOT_AUTHORIZED), b"\x20\x02\x00\x05");
assert_eq!(v5::suback(b"\x00\x01", &[1, 0x80], None)?, b"\x90\x05\x00\x01\x00\x01\x80");

Route publishes with the store

The store indexes subscriptions by a prefix (whatever isolates one set of clients from another: a tenant, a project) and by topic level. + matches one level, # the rest, and a wildcard never matches a $-prefixed system topic. A connection matched by several filters gets the highest QoS granted.

Rust
use utopia_mqtt::Store;

let mut store = Store::new();
store.subscribe(b"project-1", b"user-a", b"orders/+/created", 1, 1);
store.subscribe(b"project-1", b"user-b", b"orders/#", 2, 0);
store.subscribe(b"project-2", b"user-c", b"orders/#", 3, 1);
store.subscribe(b"project-1", b"user-b", b"orders/eu/created", 2, 1);

let found: Vec<_> = store.subscribers(b"project-1", b"orders/eu/created").into_iter().collect();
assert_eq!(found, [(2, 1), (1, 1)]);
assert!(store.subscribers(b"project-1", b"$SYS/uptime").is_empty());

store.close(2);
assert_eq!(store.subscribers(b"project-1", b"orders/eu/created").len(), 1);

Track QoS 1 deliveries

A connection draws packet ids for QoS 1 deliveries and, given each message's sequence, matches every PUBACK back to it. The topic's cursor moves only across acknowledged sequences without a gap, so it is always safe to persist and replay from.

Rust
use utopia_mqtt::Connection;

let connection = Connection::new(1, None);
connection.resume(b"orders", 41); // replay starts after 41
connection.track(1, b"orders", 42);
connection.track(2, b"orders", 43);

assert_eq!(connection.acknowledge(2).unwrap().cursor, 41); // 42 is still out
assert_eq!(connection.acknowledge(1).unwrap().cursor, 43);
assert!(connection.acknowledge(1).is_none());

Run a broker

Implement Handler with your decisions and give it to a Server on the Tokio adapter. The server decodes every packet for the client's protocol version, keeps the store, answers PINGREQ and closes clients that stay silent past their keep-alive. Here a broker accepts everyone, grants every filter at QoS 0 and fans publishes out; a Client subscribes and receives its own message.

Rust
use utopia_mqtt::client::{Client, Options};
use utopia_mqtt::packet::{Auth, Connack, Connect, Disconnect, Packet, Puback, Publish, Suback, Subscribe, Unsuback, Unsubscribe};
use utopia_mqtt::server::{AuthReply, ConnectReply, Subscriber};
use utopia_mqtt::spec::v3;
use utopia_mqtt::{Connection, Error, Handler, Server, Tokio, Transport};

struct Open;

impl Handler for Open {
    fn on_connect(&self, _: &Connect, _: &Connection) -> Result<ConnectReply, Error> {
        Ok(ConnectReply::Connack(Connack::accept(false, None)))
    }
    fn on_authenticate(&self, auth: &Auth, _: &Connection) -> Result<AuthReply, Error> {
        Ok(AuthReply::Auth(Auth::success(&auth.method)))
    }
    fn on_subscribe(&self, subscribe: &Subscribe, _: &Connection) -> Result<Suback, Error> {
        let mut suback = Suback::new();
        for _ in &subscribe.filters {
            suback.grant(0);
        }
        Ok(suback)
    }
    fn on_unsubscribe(&self, _: &Unsubscribe, _: &Connection) -> Result<Unsuback, Error> {
        Ok(Unsuback::new())
    }
    fn on_publish(&self, publish: &Publish, _: &Connection, subscribers: &[Subscriber]) -> Result<(), Error> {
        for (subscriber, _) in subscribers {
            subscriber.publish(&publish.topic, &publish.payload, 0, false, None)?;
        }
        Ok(())
    }
    fn on_puback(&self, _: &Puback, _: &Connection) -> Result<(), Error> {
        Ok(())
    }
    fn on_disconnect(&self, _: Option<&Disconnect>, _: &Connection) -> Result<(), Error> {
        Ok(())
    }
}

tokio::runtime::Runtime::new()?.block_on(async {
    let adapter = Tokio::new(vec![Transport::tcp("127.0.0.1", 0)], 1, None)?;
    let server = Server::new(adapter.clone(), Open);
    let running = server.clone();
    let task = tokio::spawn(async move { running.start().await });
    let addr = adapter.listening().await[0];

    let mut client = Client::new(&format!("mqtt://{addr}"), Options { timeout: 5.0 })?;
    client.connect().await?;
    client.send(&v3::connect(b"me", 60, true, b"", b"")).await?;
    client.receive().await?; // CONNACK
    client.send(&v3::subscribe(1, &[b"chat/#"], 0)).await?;
    client.receive().await?; // SUBACK
    client.send(&v3::publish(b"chat/general", b"hi", 0, 0, false)).await?;

    let delivery = client.receive().await?.unwrap();
    assert_eq!(Packet::parse(&delivery)?.body, b"\x00\x0cchat/generalhi");

    client.close().await;
    server.stop();
    task.await.ok();
    Ok::<_, Box<dyn std::error::Error>>(())
})?;

Test a broker in process

The Memory adapter has no network: open connections, deliver packets and read back what the broker sent and closed. Hooks run on your thread, so a test is a straight line.

Rust
use utopia_mqtt::packet::{Auth, Connack, Connect, Disconnect, Puback, Publish, Suback, Subscribe, Unsuback, Unsubscribe};
use utopia_mqtt::server::{AuthReply, ConnectReply, Subscriber};
use utopia_mqtt::spec::v5;
use utopia_mqtt::{Connection, Error, Handler, Memory, Server};

struct Strict;

impl Handler for Strict {
    fn on_connect(&self, connect: &Connect, _: &Connection) -> Result<ConnectReply, Error> {
        let known = connect.auth_data.as_deref() == Some(b"secret");
        Ok(ConnectReply::Connack(if known { Connack::accept(false, None) } else { Connack::refuse(Connack::NOT_AUTHORIZED, None) }))
    }
    fn on_authenticate(&self, auth: &Auth, _: &Connection) -> Result<AuthReply, Error> {
        Ok(AuthReply::Auth(Auth::success(&auth.method)))
    }
    fn on_subscribe(&self, _: &Subscribe, _: &Connection) -> Result<Suback, Error> {
        Ok(Suback::new())
    }
    fn on_unsubscribe(&self, _: &Unsubscribe, _: &Connection) -> Result<Unsuback, Error> {
        Ok(Unsuback::new())
    }
    fn on_publish(&self, _: &Publish, _: &Connection, _: &[Subscriber]) -> Result<(), Error> {
        Ok(())
    }
    fn on_puback(&self, _: &Puback, _: &Connection) -> Result<(), Error> {
        Ok(())
    }
    fn on_disconnect(&self, _: Option<&Disconnect>, _: &Connection) -> Result<(), Error> {
        Ok(())
    }
}

let adapter = Memory::new();
let server = Server::new(adapter.clone(), Strict);
tokio::runtime::Builder::new_current_thread().build()?.block_on(server.start());

adapter.open(1)?;
adapter.receive(1, &v5::connect(b"anonymous", 60, true, None)?)?;

assert_eq!(adapter.sent()[0].data, v5::connack(Connack::NOT_AUTHORIZED, None)?);
assert_eq!(adapter.closed(), [1]);

Reap silent clients

A client promises to send something at least every keep-alive interval. The server schedules each connection on the adapter's timer at CONNECT and again on every packet; the TimingWheel drains one-second buckets on a heartbeat and closes the connections whose time ran out (1.5 keep-alive intervals by default). NoTimer never reaps.

Rust
use std::sync::{Arc, Mutex};

use utopia_mqtt::{Timer, TimingWheel};

let now = php_std::datetime::time();
let wheel = TimingWheel::new(20, 1.5, Some(now));
let reaped = Arc::new(Mutex::new(Vec::new()));
let seen = reaped.clone();
wheel.on_tick(Arc::new(move |connection| seen.lock().unwrap().push(connection)));

wheel.schedule(1, 60); // silent for 90 seconds
wheel.schedule(2, 10); // silent for 15 seconds
wheel.schedule(2, 60); // it sent a packet: 90 seconds again
wheel.drain(now + 30);
assert!(reaped.lock().unwrap().is_empty());
wheel.drain(now + 100);
assert_eq!(*reaped.lock().unwrap(), [1, 2]);

Reference#

Building blocks for MQTT brokers that speak MQTT 5.0 and 3.1.1.

The crate has four layers, each usable on its own:

  • The codec. packet splits a byte stream into control packets (packet::frames, Packet::parse) and decodes the ones a broker reads (packet::Connect, packet::Publish, packet::Subscribe, ...); spec::v3 and spec::v5 encode every packet for each protocol version; Properties is a 5.0 property block; wire holds the primitive encodings.
  • Subscriptions. Store is a topic-filter trie scoped by a prefix (a tenant, a project): one walk finds every connection whose filters (+, #) match a topic, with its granted QoS.
  • Connections. Connection holds what CONNECT negotiated and the delivery state of QoS 1 messages: packet ids, messages in flight, and a per-topic cursor of the sequences acknowledged without a gap.
  • The broker. Server runs on an Adapter (Tokio on TCP, TLS and WebSocket listeners; Memory in process, for tests) and asks a Handler what to do with each CONNECT, AUTH, SUBSCRIBE, UNSUBSCRIBE, PUBLISH, PUBACK and DISCONNECT, keeps the store, answers PINGREQ and reaps silent clients with the adapter's Timer (TimingWheel). Client connects to any broker over TCP or TLS.
Rust
use utopia_mqtt::packet::{Connect, Packet, Publish};
use utopia_mqtt::spec::v5;
use utopia_mqtt::{Properties, Property, Store};

// A client's CONNECT and PUBLISH, as they arrive.
let properties = Properties::new().with(Property::user("projectId", "p1"));
let connect = v5::connect(b"device-1", 60, true, Some(&properties))?;
let publish = v5::publish(b"sensors/room1/temp", b"21.5", 1, 7, None, false)?;

let connect = Connect::decode(Packet::parse(&connect)?.body)?;
assert_eq!(connect.user_properties(), [(b"projectId".to_vec(), b"p1".to_vec())]);

// Who receives the PUBLISH, under the client's project.
let mut store = Store::new();
store.subscribe(b"p1", b"user-1", b"sensors/+/temp", 11, 1);
store.subscribe(b"p2", b"user-2", b"sensors/#", 12, 1);
let publish = Publish::decode(&Packet::parse(&publish)?, connect.protocol_level)?;
let subscribers = store.subscribers(b"p1", &publish.topic);
assert_eq!(subscribers.into_iter().collect::<Vec<_>>(), [(11, 1)]);

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

adapter8 items
The interfaces a broker runs on: an `Adapter` serves connections and calls the server's hooks, and its `Timer` reaps connections that go silent.
client3 items
An MQTT client connection: sends encoded packets and receives whole ones.
connectioninternal
Per-connection state: the session CONNECT negotiated, and the delivery state of QoS 1 messages in flight.
errorinternal
The error type of the codec, the broker, its adapters and the client.
memory3 items
An in-process adapter: connections and packets are driven by calls, and what the broker sends and closes is recorded.
net4 items
The network adapter: MQTT over TCP, TLS and WebSocket listeners on tokio.
packet::authinternal
Undocumented.
packet::connackinternal
Undocumented.
packet::connectinternal
Undocumented.
packet::disconnectinternal
Undocumented.
packet::publishinternal
Undocumented.
packet::subscribeinternal
Undocumented.
packet::unsubscribeinternal
Undocumented.
packet5 items
MQTT control packets: the fixed header (`Packet`, `Kind`), splitting a byte stream into packets (`frames`), and the decoded form of each packet a broker reads or answers with.
propertyinternal
MQTT 5.0 properties: identifier/value pairs carried in a block (a variable byte length, then each property) by every 5.0 packet that has one. MQTT 3.1.1 packets have none.
server5 items
The broker: decodes each packet an adapter receives, asks the `Handler` what to do, keeps the subscription store and answers clients.
spec0 items
Control packet encoders for each protocol version: `v3` (MQTT 3.1.1) and `v5` (MQTT 5.0).
spec::v317 items
MQTT 3.1.1 encoders. There are no property blocks and no reason codes: CONNACK carries a return code, SUBACK a granted QoS (or failure) byte per filter, and there is no AUTH.
spec::v516 items
MQTT 5.0 encoders. Every acknowledgement carries a reason code and a property block (empty when `None`); PUBLISH carries the block before its payload. Encoding fails only for a property with an unknown identifier.
storeinternal
The subscription store: a topic-filter trie that resolves a publish to its subscribers in one walk.
timerinternal
Keep-alive timers: `TimingWheel` (one-second buckets drained by a heartbeat) and `NoTimer` (never reaps).
wire7 items
The primitive encodings MQTT packets are built from: variable byte integers, length-prefixed strings, two-byte integers and single bytes.
wire::atinternal
Undocumented.

API#

What utopia_mqtt exports at its root.

Structs

AckA delivery a PUBACK acknowledged.ClientA connection to an MQTT broker over TCP (`mqtt://`) or TLS (`mqtts://`), sending packets the caller encodes (see `crate::spec`) and receiving whole packets, framed by their fixed header.ConnectionOne client connection, by the transport's connection id: its session `State`, and its outbound deliveries. A broker shares it (cheap to clone behind an `Arc`); every method takes `&self`.MemoryAn adapter without a network, for tests: the caller opens connections, delivers packets and disconnects clients, and reads back what the broker sent and which connections it closed. Hooks run on the caller's thread.NoTimerA timer that never reaps: scheduling and clearing do nothing.PacketA framed control packet: its type and flags (the fixed header) and the rest of it, borrowed from the bytes it was parsed from.PropertiesAn ordered list of `Property`: an MQTT 5.0 property block. It encodes to its length as a variable byte integer followed by each property, and parses the same shape back.PropertyOne MQTT 5.0 property: an identifier and a value whose wire encoding the identifier fixes (see `Property::wire_type`).RecordWhat the store knows of one connection: the isolation key and user it subscribed under, and its subscriptions.ServerAn MQTT broker over an `Adapter`, with a `Handler` making its decisions. It speaks MQTT 3.1.1 and 5.0, keeps the subscriptions in a `Store`, answers PINGREQ, schedules each connection's keep-alive on the adapter's timer (30 seconds to CONNECT, then the negotiated keep-alive, refreshed by every packet), and counts packets, connections and subscriptions on a telemetry backend.StateWhat the broker knows about a connection's session. Read and change it through `Connection::state`.StoreA topic-filter trie for MQTT subscriptions, indexed by a prefix (an isolation key: a tenant, a project) and then by topic level, so a publish finds every matching filter (`+` one level, `#` the rest) in one walk.TimingWheelKeep-alive deadlines in one-second buckets. Scheduling an id puts it in the bucket of the second its keep-alive (times the multiplier) runs out; a heartbeat every `interval` seconds drains the buckets that are due and calls the tick hook with each id in them. Rescheduling (every packet a client sends) moves the id to a later bucket, so only silent clients are reaped, at most `interval` seconds late.TokioAn MQTT adapter on the network, on tokio: one listener per `Transport`, all feeding the same hooks.