@nestjs/microservices
Version:
Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.
323 lines (322 loc) • 14.5 kB
JavaScript
import { CONNECTION_FAILED_MESSAGE, MQTT_DEFAULT_URL, MQTT_MAX_TOPIC_LENGTH, MQTT_SEPARATOR, MQTT_WILDCARD_ALL, MQTT_WILDCARD_SINGLE, NO_MESSAGE_HANDLER, } from '../constants.js';
import { MqttContext } from '../ctx-host/mqtt.context.js';
import { Transport } from '../enums/index.js';
import { MaxMqttTopicLengthExceededException } from '../errors/max-mqtt-topic-length-exceeded.exception.js';
import { MqttRecord } from '../record-builders/mqtt.record-builder.js';
import { MqttRecordSerializer } from '../serializers/mqtt-record.serializer.js';
import { Server } from './server.js';
import { isUndefined } from '@nestjs/common/internal';
const INFINITE_CONNECTION_ATTEMPTS = -1;
/**
* @publicApi
*/
export class ServerMqtt extends Server {
options;
transportId = Transport.MQTT;
url;
mqttClient;
closeCount = 0;
connectionAttempts = 0;
hasConnected = false;
pendingEventListeners = [];
constructor(options) {
super();
this.options = options;
this.url = this.getOptionsProp(options, 'url', MQTT_DEFAULT_URL);
this.initializeSerializer(options);
this.initializeDeserializer(options);
}
async listen(callback) {
const closeCount = this.closeCount;
try {
// Re-arm the attempts limit so that a restarted server gets a fresh
// startup window.
this.connectionAttempts = 0;
this.hasConnected = false;
const mqttClient = await this.createMqttClient();
if (this.closeCount !== closeCount) {
await mqttClient.endAsync().catch(() => { });
callback(new Error('Connection closed'));
return;
}
this.mqttClient = mqttClient;
this.start(callback);
}
catch (err) {
callback(err);
}
}
start(callback) {
// The bootstrap callback must settle exactly once, no matter whether the
// connection succeeds or the attempts limit is exhausted first.
let listenCallback = callback;
const settleListenCallback = (err) => {
const cb = listenCallback;
listenCallback = undefined;
isUndefined(err) ? cb?.() : cb?.(err);
};
this.registerErrorListener(this.mqttClient, settleListenCallback);
this.registerReconnectListener(this.mqttClient);
this.registerDisconnectListener(this.mqttClient);
this.registerCloseListener(this.mqttClient);
this.registerConnectListener(this.mqttClient);
this.pendingEventListeners.forEach(({ event, callback }) => this.mqttClient.on(event, callback));
this.pendingEventListeners = [];
this.bindEvents(this.mqttClient);
this.mqttClient.once("connect" /* MqttEventsMap.CONNECT */, () => settleListenCallback());
}
bindEvents(mqttClient) {
mqttClient.on('message', this.getMessageHandler(mqttClient).bind(this));
const registeredPatterns = [...this.messageHandlers.keys()];
registeredPatterns.forEach(pattern => {
const handler = this.messageHandlers.get(pattern);
const { extras } = handler;
const globalSubscribeOptions = this.getOptionsProp(this.options, 'subscribeOptions');
const subscribeOptions = extras?.qos !== undefined
? { ...globalSubscribeOptions, qos: extras.qos }
: globalSubscribeOptions;
mqttClient.subscribe(this.getSubscriptionTopic(pattern, handler), subscribeOptions);
});
}
async close() {
this.closeCount++;
// Reset first, so that the status update of the client being closed is not
// taken for the connection that gave up, and a listener registered right
// after close() waits for the next listen() instead of attaching to it
const mqttClient = this.mqttClient;
this.mqttClient = null;
this.pendingEventListeners = [];
if (mqttClient && this.getOptionsProp(this.options, 'gracefulShutdown')) {
await this.stopReceivingMessages(mqttClient);
await this.waitForHandlersInFlight(this.getOptionsProp(this.options, 'gracePeriod'));
}
// Awaited, so that a close() the caller awaits really has the connection
// closed, as with the other transports: mqtt closes it on a later tick and
// the broker still delivers to it until then
await mqttClient?.endAsync();
}
async stopReceivingMessages(mqttClient) {
// On a reconnect, mqtt subscribes again to every topic it has not
// unsubscribed from. Turned off, as the client is discarded after close().
mqttClient.options.resubscribe = false;
const topics = [...this.messageHandlers].map(([pattern, handler]) => this.getSubscriptionTopic(pattern, handler));
// While disconnected, mqtt would keep the packet for the next connection,
// which end() would then wait for. That connection does not resubscribe.
if (topics.length === 0 || !mqttClient.connected) {
return;
}
try {
await mqttClient.unsubscribeAsync(topics);
}
catch {
// The connection was lost before the broker answered. The next one does
// not resubscribe either.
}
}
getSubscriptionTopic(pattern, handler) {
return handler.isEventHandler ? pattern : this.getRequestPattern(pattern);
}
async createMqttClient() {
const mqttPackage = await this.loadPackage('mqtt', ServerMqtt.name, () => import('mqtt'));
// mqtt stops reconnecting for good once the broker refuses a connection
// (CONNACK error), which would leave the server disconnected. Retry as
// after any other failed attempt, unless told otherwise.
return mqttPackage.connect(this.url, {
reconnectOnConnackError: true,
...this.options,
});
}
getMessageHandler(pub) {
return async (channel, buffer, originalPacket) => this.handleMessage(channel, buffer, pub, originalPacket).catch(err => this.handleError(err));
}
async handleMessage(channel, buffer, pub, originalPacket) {
const rawPacket = this.parseMessage(buffer.toString());
if (this.isOwnReply(channel, rawPacket)) {
return;
}
const packet = await this.deserializer.deserialize(rawPacket, { channel });
const mqttContext = new MqttContext([channel, originalPacket]);
if (isUndefined(packet.id)) {
return this.handleEvent(channel, packet, mqttContext);
}
this.assertValidPacketId(packet.id);
const publish = this.getPublisher(pub, mqttContext, packet.id);
const handler = this.getHandlerByPattern(channel);
if (!handler) {
const status = 'error';
const noHandlerPacket = {
id: packet.id,
status,
err: NO_MESSAGE_HANDLER,
};
return publish(noHandlerPacket);
}
this.warnIfEventHandlerReplies(handler, channel);
return this.handleRequest(mqttContext, async () => this.transformToObservable(await handler(packet.data, mqttContext)), publish);
}
/**
* A filter that ends in "#" also matches the topic this server replies on
* ("orders/1/reply"), so the broker hands the server its own replies. Those
* are skipped unless a handler's filter targets reply topics.
*/
isOwnReply(topic, packet) {
const replySuffix = this.getReplyPattern('');
return (topic.endsWith(replySuffix) &&
!isUndefined(packet?.id) &&
isUndefined(packet?.pattern) &&
![...this.messageHandlers.keys()].some(key => {
const filter = this.removeHandlerKeySharedPrefix(key);
return (filter.endsWith(replySuffix) && this.matchMqttPattern(filter, topic));
}));
}
getPublisher(client, context, id) {
// Checked before the handler runs, as none of its replies could be sent
this.assertTopicLength(this.getReplyPattern(context.getTopic()));
return (response) => {
Object.assign(response, { id });
const options = response.response instanceof MqttRecord
? response.response.options
: {};
const outgoingResponse = this.serializer.serialize(response);
return client.publish(this.getReplyPattern(context.getTopic()), outgoingResponse, options);
};
}
parseMessage(content) {
try {
return JSON.parse(content);
}
catch (e) {
return content;
}
}
matchMqttPattern(pattern, topic) {
// MQTT 3.1.1 section 4.7.2 excludes $ topics from leading wildcards.
if (topic.startsWith('$') &&
(pattern[0] === MQTT_WILDCARD_ALL || pattern[0] === MQTT_WILDCARD_SINGLE)) {
return false;
}
const patternSegments = pattern.split(MQTT_SEPARATOR);
const topicSegments = topic.split(MQTT_SEPARATOR);
const patternSegmentsLength = patternSegments.length;
const topicSegmentsLength = topicSegments.length;
const lastIndex = patternSegmentsLength - 1;
for (let i = 0; i < patternSegmentsLength; i++) {
const currentPattern = patternSegments[i];
const patternChar = currentPattern[0];
const currentTopic = topicSegments[i];
if (isUndefined(currentTopic) && currentPattern !== MQTT_WILDCARD_ALL) {
return false;
}
if (patternChar === MQTT_WILDCARD_ALL) {
return i === lastIndex;
}
if (patternChar !== MQTT_WILDCARD_SINGLE &&
currentPattern !== currentTopic) {
return false;
}
}
return patternSegmentsLength === topicSegmentsLength;
}
getHandlerByPattern(pattern) {
// The topic is matched as the broker delivered it, which is what its ACLs
// checked: decoded as JSON, '"admin/reset"' would reach the handler of
// "admin/reset". Only the topic of an object pattern is decoded, so that
// its keys are sorted as the handler's are.
const route = pattern.startsWith('{')
? this.getRouteFromPattern(pattern)
: pattern;
if (this.messageHandlers.has(route)) {
return this.messageHandlers.get(route) || null;
}
// Wildcard filters are matched against the topic itself: decoding moves
// its levels around ('/' inside a JSON string is a level separator), so
// the decoded topic can match a filter that the topic does not.
for (const [key, value] of this.messageHandlers) {
const keyWithoutSharedPrefix = this.removeHandlerKeySharedPrefix(key);
if (this.matchMqttPattern(keyWithoutSharedPrefix, pattern)) {
return value;
}
}
return null;
}
removeHandlerKeySharedPrefix(handlerKey) {
return handlerKey && handlerKey.startsWith('$share/')
? handlerKey.split('/').slice(2).join('/')
: handlerKey;
}
getRequestPattern(pattern) {
return pattern;
}
getReplyPattern(pattern) {
return `${pattern}/reply`;
}
/**
* A topic's length is encoded in two bytes, and "/reply" can take a topic
* the broker delivered past it. mqtt.js only fails on a longer topic once it
* has written the start of the packet, so the broker would read the packets
* sent after it as the rest of that packet.
*/
assertTopicLength(topic) {
const length = Buffer.byteLength(topic);
if (length > MQTT_MAX_TOPIC_LENGTH) {
throw new MaxMqttTopicLengthExceededException(length, MQTT_MAX_TOPIC_LENGTH);
}
}
registerErrorListener(client, callback) {
client.on("error" /* MqttEventsMap.ERROR */, (err) => {
this.logger.error(err);
const maxConnectionAttempts = this.getOptionsProp(this.options, 'maxConnectionAttempts', INFINITE_CONNECTION_ATTEMPTS);
// The limit bounds the initial connection only. Once the server has
// connected, mqtt.js reconnects indefinitely and errors are just logged,
// so a running microservice is never torn down by this option.
if (maxConnectionAttempts === INFINITE_CONNECTION_ATTEMPTS ||
this.hasConnected) {
return;
}
if (++this.connectionAttempts === maxConnectionAttempts) {
// The failure that is reported is the connection one, not a close one
this.close().catch(closeErr => this.logger.error(closeErr));
callback?.(err ?? new Error(CONNECTION_FAILED_MESSAGE));
}
});
}
registerReconnectListener(client) {
client.on("reconnect" /* MqttEventsMap.RECONNECT */, () => {
this._status$.next("reconnecting" /* MqttStatus.RECONNECTING */);
this.logger.log('MQTT connection lost. Trying to reconnect...');
});
}
registerDisconnectListener(client) {
client.on("disconnect" /* MqttEventsMap.DISCONNECT */, () => {
this._status$.next("disconnected" /* MqttStatus.DISCONNECTED */);
});
}
registerCloseListener(client) {
client.on("close" /* MqttEventsMap.CLOSE */, () => {
this._status$.next("closed" /* MqttStatus.CLOSED */);
});
}
registerConnectListener(client) {
client.on("connect" /* MqttEventsMap.CONNECT */, () => {
this.hasConnected = true;
this._status$.next("connected" /* MqttStatus.CONNECTED */);
});
}
unwrap() {
if (!this.mqttClient) {
throw new Error('Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing the server.');
}
return this.mqttClient;
}
on(event, callback) {
if (this.mqttClient) {
this.mqttClient.on(event, callback);
}
else {
this.pendingEventListeners.push({ event, callback });
}
}
initializeSerializer(options) {
this.serializer = options?.serializer ?? new MqttRecordSerializer();
}
}