Aller au contenu
Français

MQTT

Ce contenu n’est pas encore disponible dans votre langue.

MqttActor integrates with MQTT brokers (Mosquitto, EMQ X, HiveMQ, AWS IoT Core). Supports both MQTT 3.1.1 and 5; topic wildcards (+, #); QoS 0/1/2; retained messages.

It is the MQTT counterpart to WebsocketClientActor: an abstract base class you extend. Declare subscriptions in the constructor, handle inbound traffic in onMessage, and publish with this.publish(...). It is still controllable from the outside via ref.tell(...).

import { ActorSystem, ActorSystemOptions } from 'actor-ts';
import { MqttActor, MqttOptions, type MqttOptionsBuilder, type MqttMessage } from 'actor-ts/io';
type Reading = { sensor: string; celsius: number };
const actorSystemOptions = ActorSystemOptions.create().withConfig({
'actor-ts': { io: { broker: { mqtt: { 'broker-url': 'mqtt://localhost:1883' } } } },
});
class TemperatureHub extends MqttActor<Reading> {
constructor(options: MqttOptionsBuilder) {
super(options.withQos(1).withClientId('temperature-hub'));
this.subscribe('sensors/+/temp');
this.subscribe('alerts/#', { qos: 2 });
}
override onMessage(message: MqttMessage<Reading>): void {
const { sensor, celsius } = message.payload.entity(); // decoded via the codec
this.log.info(`${sensor}: ${celsius}°C`);
this.publish(`ack/${sensor}`, 'ok'); // raw string
this.publish('rollup', { sensor, celsius }); // encoded entity
}
}
const system = ActorSystem.create('demo', actorSystemOptions);
system.spawn(() => new TemperatureHub(MqttOptions.create()), 'hub');

T (here Reading) types the inbound payload — message.payload.entity() returns a T. A second generic, TSelf, types application messages other actors may tell the ref (see External control below); it defaults to never.

Override these on your subclass. onReceive and onCommand are sealed — the base classes dispatch to the hooks below; do not override them.

HookWhen
onMessage(message)A message arrived on one of this actor’s own subscriptions. Required.
onConnected()The connection (re)opened; the subscription registry has been re-applied on the broker.
onDisconnected(cause?)The connection dropped; a reconnect cycle may follow (per settings).
onInvalidMessage(err, message)onMessage threw an MqttDecodeError (a lazy entity() on a malformed payload). Default: log + drop. Rethrow to escalate.
onSelfMessage(message)An application message (TSelf) was told to this ref — or anything else none of the actor’s own kinds matched, a remote node’s body included. Default: a warn naming the message’s class (never its payload), then this.unhandled(message) — a dead letter naming this actor, counted in actor_unhandled_total{class}.
onTerminated(signal)An actor you context.watched stopped. Inherited from BrokerActor; delivery targets this actor watches itself are already handled.

Inbound and lifecycle events are delivered through the mailbox, so onMessage and the hooks always run on the actor thread (single-threaded, per-connection order preserved: connected → messages → disconnected).

Settings resolve with the usual precedence: constructor / builder > HOCON (actor-ts.io.broker.mqtt) > built-in defaults. Use the fluent MqttOptions builder, or pass a plain Partial<MqttOptionsType>.

const options = MqttOptions.create()
.withBrokerUrl('mqtts://mqtt.example.com:8883')
.withClientId('my-app')
.withCredentials(process.env.MQTT_USER, process.env.MQTT_PASS)
.withQos(1) // default QoS for publish/subscribe
.withProtocolVersion(5) // opt in to MQTT 5.0
.withCleanSession(false)
.withKeepAlive(30);
interface MqttOptionsType extends BrokerCommonOptionsType {
brokerUrl?: string; // mqtt:// mqtts:// ws:// wss://
clientId?: string;
credentials?: { username?: string; password?: string };
qos?: 0 | 1 | 2; // default QoS for publish/subscribe
cleanSession?: boolean; // default true
keepAlive?: number; // seconds; default 60
protocolVersion?: 4 | 5; // default 4 (= MQTT 3.1.1)
codec?: MqttCodec<unknown>; // default mqttJsonCodec()
will?: { topic: string; payload: string | Uint8Array; qos?: 0 | 1 | 2; retain?: boolean };
tls?: TlsTransportOptionsType; // cert material for mqtts:// / wss://; code-only
}

Under actor-ts.io.broker.mqtt the multi-word fields are spelled in kebab-case — broker-url, client-id, clean-session, keep-alive, protocol-version — and the HOCON keep-alive is a duration in whole seconds, the unit MQTT carries it in: keep-alive = 30s is 30. A value that is not a whole number of seconds is refused at start, 1500ms and a bare 30 alike, since HOCON reads a bare number as milliseconds; 0 still switches keep-alive off.

Common patterns:

  • withCleanSession(false) — session persists; the broker delivers messages missed during disconnection (subject to broker config).
  • withWill({ ... }) — the broker publishes this when the client disconnects ungracefully. Useful for presence (“device-42-offline”).
  • withProtocolVersion(5) — enables MQTT 5 features (user properties, reason codes on MqttMessage). Requires a v5-capable broker.

The connection’s leaves sit under actor-ts.io.broker.mqtt too. This sample takes each of them from the environment: a leaf whose variable is not set stays unset, at the built-in default its comment names.

actor-ts.io.broker.mqtt {
broker-url = ${?ACTOR_TS_MQTT_BROKER_URL} # mqtt:// mqtts:// ws:// wss://; required, here or in code
client-id = ${?ACTOR_TS_MQTT_CLIENT_ID}
credentials {
username = ${?ACTOR_TS_MQTT_USERNAME}
password = ${?ACTOR_TS_MQTT_PASSWORD}
}
qos = ${?ACTOR_TS_MQTT_QOS} # 0, 1 or 2; unset = 0
clean-session = ${?ACTOR_TS_MQTT_CLEAN_SESSION} # unset = true
keep-alive = ${?ACTOR_TS_MQTT_KEEP_ALIVE} # whole seconds, such as 30s; unset = 60s
protocol-version = ${?ACTOR_TS_MQTT_PROTOCOL_VERSION} # 4 (MQTT 3.1.1) or 5; unset = 4
}

A value from the environment is read as JSON first wherever it parses as JSON. So ACTOR_TS_MQTT_KEEP_ALIVE=30 is the bare number 30, which keep-alive refuses as thirty milliseconds — write 30s — and a client id or password that reads as a number comes back in that number’s own spelling, 1e3 as 1000, 1.50 as 1.5, and a whole number past Number.MAX_SAFE_INTEGER possibly with other last digits (20261104123456789 as 20261104123456788); one that reads as null, a list or an object stops the start with a ConfigError. Quote such a value inside the variable (ACTOR_TS_MQTT_PASSWORD='"1e3"'), or set it in code.

The last will is what a fleet usually wants set per deployment rather than per build, so it has its own block under actor-ts.io.broker.mqtt:

actor-ts.io.broker.mqtt {
will {
topic = "devices/42/status"
payload = "offline"
qos = 1
retain = true
}
}

Two things to know about it.

payload is a string here. The field is string | Uint8Array, and a config file has no spelling for bytes, so a binary will stays code-only. Leaving payload out gives the empty one, which is legal MQTT and is how a retained will is cleared — but topic is required, and a will block without one is refused at start rather than sent to the broker to be rejected there.

The block is read whole. withWill({ … }) in code replaces the configured one entirely instead of merging leaf by leaf with it — which is the ordinary precedence (constructor > HOCON > defaults) applied at the field this object is.

Inbound MqttMessage<T> carries a lazily-decoding MqttPayload<T>:

override onMessage(message: MqttMessage<Reading>): void {
message.payload.bytes; // raw Uint8Array
message.payload.text(); // UTF-8 string (cached)
message.payload.entity(); // decoded T via the codec (cached)
message.payload.entity<Acknowledgment>(); // decode as a different type on a specific topic
}

Decoding is lazy — it only happens when you call text() / entity(). A malformed payload makes entity() throw an MqttDecodeError; because that happens inside onMessage, the base class catches it and routes it to onInvalidMessage (default: log + drop, no restart):

protected override onInvalidMessage(err: MqttDecodeError, message: MqttMessage<Reading>): void {
this.log.warn(`bad payload on ${err.topic}: ${err.message}`);
}

this.publish(topic, payload, options?) returns false if the message was dropped (encode failure or outbound-buffer overflow):

  • a string or Uint8Array payload is sent raw;
  • any other value is encoded via the codec (JSON by default).
this.publish('ack/1', 'ok'); // raw bytes: ok
this.publish('rollup', { sensor, celsius }); // JSON: {"sensor":...,"celsius":...}
this.publish('cfg', data, { qos: 1, retain: true });

To publish a bare string as a JSON entity (the wire bytes "pong" rather than pong), encode it explicitly:

this.publish('topic', this.codec().encode('pong'));

The codec turns entities into bytes and back. The default is mqttJsonCodec() (plain JSON over UTF-8). Supply your own via withCodec(...) — e.g. a JSON codec with runtime validation:

import { mqttJsonCodec, MqttOptions } from 'actor-ts/io';
const codec = mqttJsonCodec<Reading>({
validate: (v) => ReadingSchema.parse(v), // zod, etc.; throws → MqttDecodeError
});
MqttOptions.create().withBrokerUrl('mqtt://localhost:1883').withCodec(codec);

Beyond the subclass API, any actor can drive an MqttActor by telling it an MqttCommand:

ref.tell({ kind: 'publish', publish: { topic: 't', payload: 'hi', qos: 1 } });
// Subscribe and route to this actor's own onMessage (no target):
ref.tell({ kind: 'subscribe', topic: 'x/#', qos: 1 });
// Subscribe and fan out to another actor (external target):
ref.tell({ kind: 'subscribe', topic: 'y/#', target: someHandler });
ref.tell({ kind: 'unsubscribe', topic: 'y/#', target: someHandler });
  • A subscribe with no target delivers matching messages to the actor’s own onMessage; with a target, it fans out to that actor. Overlapping patterns deliver to each ref at most once.
  • An unsubscribe removes only what an external subscribe attached: the target it names, or — with no target — every externally attached target at once. It never removes the actor’s own onMessage delivery, and never a target the subclass declared itself with subscribe(topic, { target }), even when the command names that target outright. An external controller can’t silence the subclass’s constructor-declared subscription, in whichever of the two forms it was declared. From inside the subclass, unsubscribe(topic, { target }) detaches any target, whoever attached it.
  • The qos on a subscribe applies only to a pattern the command itself creates. Naming a pattern that already exists joins it at the QoS already registered; the command’s qos is ignored there. This is the additive mirror of the rule above: a controller that can’t silence the subclass’s subscription can’t quietly downgrade it either — a QoS-2 subscription re-issued at QoS 0 would leave the application believing delivery is exactly-once while the broker is free to drop. To change the QoS of your own pattern, call subscribe(topic, { qos }) from the subclass.
  • Fan-out targets are deathwatched: when a target actor stops, it is pruned automatically (and a broker UNSUBSCRIBE fires once a pattern has no consumers left).
  • An external subscribe that introduces a filter the actor did not already hold is logged at info, and so is one whose qos the rule above kept out of a filter the actor already holds — a refused request is worth as much to an operator as a new filter, and the sender sees only a successful re-SUBSCRIBE otherwise. A plain join stays silent: it introduces neither a filter nor a consumer that did not exist, and it asked for nothing it did not get. So does the subclass’s own subscribe(), in the constructor or at runtime. A join is not free at the broker, though — while connected it re-issues the SUBSCRIBE, and an MQTT re-SUBSCRIBE replays the filter’s retained messages to every consumer of that pattern.

The first record names the filter, the QoS the SUBSCRIBE actually carries, and whether matching messages go to the actor’s own onMessage or fan out to another actor; the second names the QoS that was asked for beside the one that was kept:

MqttActor: external subscribe introduced broker filter 'tele/#' at QoS 1, delivering to actor 'actor-ts://sensors/user/mirror'
MqttActor: external subscribe asked QoS 0 for filter 'own/#', which the actor already holds at QoS 2; kept QoS 2

That is the counterweight to the first rule rather than a restriction on it. Attaching a handler to any filter, # included, stays open because it is the actor’s contract and anyone holding the ref can already publish anywhere — which is defensible exactly as long as an operator can see it happen. Nothing from a message is logged: the record describes a subscription, not traffic, so one line per new filter never becomes one line per payload. The filter is escaped and length-capped before it goes in, because it is text the sender chose — a newline in it would otherwise forge a second log line that reads like a genuine one. If your topic scheme embeds a credential (some brokers put an API key in the path), note that it reaches the log here at info, the same way it already does in this actor’s subscribe-failure and undecodable-payload warnings.

Which makes possession of the ref the trust boundary — cluster members included. A valid member holding this actor’s ref can subscribe itself to anything the underlying client is entitled to read, exactly as a local actor can; there is no per-command trust hook, and one would not help, because the capability travels with the ref rather than with the command. Note that this is a read capability and the publish rule beside it is a write one: being able to publish to a topic tree is not the same as being able to read everything the broker serves that client, so “it can already publish” explains why the fan-out stays open, not why reading is harmless. A feed that must stay private therefore must not have its actor registered with the receptionist or its ref handed across nodes. Give that traffic its own MqttActor, keep the ref inside the subsystem that owns it, and let the externally controllable one carry the topics you are willing to have mirrored.

Since these commands are plain objects, keep any TSelf you define off the kind values publish / subscribe / unsubscribe — otherwise it would be dispatched as a command instead of reaching onSelfMessage.

QoSDeliveryCost
0At-most-once. Fire-and-forget.Cheapest; messages may be lost.
1At-least-once. Broker stores until acked.Default for most use cases. Duplicates possible.
2Exactly-once. Full handshake.Slowest; rarely needed.

For IoT telemetry, QoS 1 is the typical balance. Commands to devices: also QoS 1 (or QoS 2 if duplicates would be harmful). Status updates that are quickly superseded (sensor readings): QoS 0 is fine.

this.subscribe('sensors/+/temp'); // matches sensors/dev1/temp, sensors/dev2/temp, ...
this.subscribe('devices/#'); // matches devices/anything/anywhere/...
WildcardMatches
+Exactly one level.
#Multiple levels (must be the last segment).
this.publish('config/device-42', { mode: 'eco' }, { retain: true });

A retained message is stored by the broker and delivered immediately to any new subscriber. Use for configuration (devices reading the latest config on connect) or last-known-state. Keep retain unset for normal pub/sub — otherwise the broker keeps every old message visible forever.

An mqtts:// or wss:// URL starts the handshake, and mqtt.js verifies the broker against the system trust store by default. Behind a private CA, or for client-certificate auth, add withTls:

const mqttOptions = MqttOptions.create()
.withBrokerUrl('mqtts://mqtt.example.com:8883')
.withTls({
ca: fs.readFileSync('./tls/ca.crt', 'utf8'),
cert: fs.readFileSync('./tls/device.crt', 'utf8'),
key: fs.readFileSync('./tls/device.key', 'utf8'),
});

Every field carries the material itself, never a path to it, which is why the example reads the files. cert and key only mean anything together, and one without the other is rejected when the actor starts.

withTls configures the handshake rather than starting one, so keep the mqtts:// / wss:// scheme. It has no config key on purpose: a private key does not belong in application.conf.

Terminal window
npm install mqtt
# or: bun add mqtt
  1. IoT / telemetry — devices publishing sensor data, subscribing to commands.
  2. Bridging from existing MQTT infrastructure — when the broker is already there.
  3. Lightweight pub/sub — when Kafka is overkill (small payloads, no replay history needed).

For cluster-internal pub/sub, DistributedPubSub is simpler (no external broker).