@nestjs/microservices
Version:
Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.
291 lines (290 loc) • 12.6 kB
JavaScript
import { isObject, isUndefined } from '@nestjs/common/internal';
import { EventEmitter } from 'events';
import { NATS_DEFAULT_URL, NO_MESSAGE_HANDLER } from '../constants.js';
import { NatsContext } from '../ctx-host/nats.context.js';
import { NatsRequestJSONDeserializer } from '../deserializers/nats-request-json.deserializer.js';
import { Transport } from '../enums/index.js';
import { NatsRecordSerializer } from '../serializers/nats-record.serializer.js';
import { Server } from './server.js';
/**
* @publicApi
*/
export class ServerNats extends Server {
options;
transportId = Transport.NATS;
natsClient;
closeCount = 0;
statusEventEmitter = new EventEmitter();
subscriptions = [];
constructor(options) {
super();
this.options = options;
this.initializeSerializer(options);
this.initializeDeserializer(options);
}
async listen(callback) {
const closeCount = this.closeCount;
try {
const natsClient = await this.createNatsClient();
if (this.closeCount !== closeCount) {
await natsClient.close().catch(() => { });
callback(new Error('Connection closed'));
return;
}
this.natsClient = natsClient;
this._status$.next("connected" /* NatsStatus.CONNECTED */);
this.handleStatusUpdates(this.natsClient).catch(err => this.logger.error(err));
this.start(callback);
}
catch (err) {
callback(err);
}
}
start(callback) {
this.bindEvents(this.natsClient);
callback();
}
bindEvents(client) {
const subscribe = (channel, queue) => client.subscribe(channel, {
queue,
callback: this.getMessageHandler(channel).bind(this),
});
const defaultQueue = this.getOptionsProp(this.options, 'queue');
const registeredPatterns = [...this.messageHandlers.keys()];
for (const channel of registeredPatterns) {
const handlerRef = this.messageHandlers.get(channel);
const queue = handlerRef.extras?.queue ?? defaultQueue;
const sub = subscribe(channel, queue);
this.subscriptions.push(sub);
}
}
async close() {
this.closeCount++;
if (!this.natsClient) {
this.statusEventEmitter.removeAllListeners();
return;
}
const graceful = this.getOptionsProp(this.options, 'gracefulShutdown');
if (graceful) {
this.subscriptions.forEach(sub => sub.unsubscribe());
this.subscriptions = [];
await this.waitForHandlersInFlight(this.getOptionsProp(this.options, 'gracePeriod'));
}
// Reset first, so that the status updates do not take this close for a
// connection that gave up
const natsClient = this.natsClient;
this.natsClient = null;
this.subscriptions = [];
try {
await natsClient?.close();
}
finally {
this.statusEventEmitter.removeAllListeners();
}
}
async createNatsClient() {
const natsPackage = await this.loadPackage('@nats-io/transport-node', ServerNats.name, () => import('@nats-io/transport-node'));
const options = this.options || {};
return natsPackage.connect({
servers: NATS_DEFAULT_URL,
...options,
});
}
getMessageHandler(channel) {
return async (error, message) => {
if (error) {
return this.logger.error(error);
}
return this.handleMessage(channel, message).catch(err => this.handleError(err));
};
}
async handleMessage(channel, natsMsg) {
const callerSubject = natsMsg.subject;
const rawMessage = natsMsg.data;
const replyTo = natsMsg.reply;
const natsCtx = new NatsContext([callerSubject, natsMsg.headers]);
const message = await this.deserializer.deserialize(natsMsg, {
channel,
replyTo,
});
if (this.isReply(message)) {
// The requester names the subject its reply is published on, so a
// reply of a Nest server, this one included, can arrive on the subject
// of a handler. It is not a message for that handler.
this.logger.debug?.(`Skipped a reply of a Nest server that was published on "${callerSubject}"`);
return;
}
if (isUndefined(message.id)) {
return this.handleEvent(channel, message, natsCtx);
}
this.assertValidPacketId(message.id);
const publish = this.getPublisher(natsMsg, message.id, natsCtx);
const handler = this.getHandlerByPattern(channel);
if (!handler) {
const status = 'error';
const noHandlerPacket = {
id: message.id,
status,
err: NO_MESSAGE_HANDLER,
};
return publish(noHandlerPacket);
}
if (handler.isEventHandler &&
this.isAnsweredByMessageHandler(callerSubject, handler)) {
// NATS delivers the request to every subscription whose subject matches
// it, so a message handler subscribed to such a subject answers it.
return this.handleEvent(channel, message, natsCtx);
}
if (channel !== callerSubject &&
this.isAnsweredByOwnMessageHandler(callerSubject, handler)) {
// The message handler subscribed to the subject itself answers it alone
return;
}
this.warnIfEventHandlerReplies(handler, channel);
return this.handleRequest(natsCtx, async () => this.transformToObservable(await handler(message.data, natsCtx)), publish);
}
/**
* Whether the packet is a reply of a Nest server, which the default
* deserializer leaves as it is: a packet with an id that carries a
* response, an error or the end of the response stream instead of a
* pattern and data.
*/
isReply(packet) {
return (isObject(packet) &&
!isUndefined(packet.id) &&
isUndefined(packet.pattern) &&
isUndefined(packet.data) &&
(!isUndefined(packet.response) ||
!isUndefined(packet.err) ||
!isUndefined(packet.isDisposed)));
}
/**
* Whether a message handler receives a request published to the subject as
* well. NATS delivers a message to every subscription whose subject matches
* it, but to a single member of a queue group.
*/
isAnsweredByMessageHandler(subject, eventHandler) {
const defaultQueue = this.getOptionsProp(this.options, 'queue');
const eventQueue = eventHandler.extras?.queue ?? defaultQueue;
return [...this.messageHandlers].some(([pattern, handler]) => !handler.isEventHandler &&
(isUndefined(eventQueue) ||
(handler.extras?.queue ?? defaultQueue) !== eventQueue) &&
this.matchNatsSubject(pattern, subject));
}
/**
* Whether a message handler subscribed to the subject itself receives a
* request published to it as well, as it does unless it shares a queue
* group with the given handler.
*/
isAnsweredByOwnMessageHandler(subject, wildcardHandler) {
const defaultQueue = this.getOptionsProp(this.options, 'queue');
const queue = wildcardHandler.extras?.queue ?? defaultQueue;
const handler = this.messageHandlers.get(subject);
return (!!handler &&
!handler.isEventHandler &&
(isUndefined(queue) || (handler.extras?.queue ?? defaultQueue) !== queue));
}
/**
* Whether a subject matches a subscription subject, in which "*" stands for
* any single token and a final ">" for one or more tokens.
*/
matchNatsSubject(pattern, subject) {
const patternTokens = pattern.split('.');
const subjectTokens = subject.split('.');
for (let i = 0; i < patternTokens.length; i++) {
if (patternTokens[i] === '>') {
return subjectTokens.length > i;
}
if (patternTokens[i] !== '*' && patternTokens[i] !== subjectTokens[i]) {
return false;
}
}
return patternTokens.length === subjectTokens.length;
}
getPublisher(natsMsg, id, ctx) {
if (natsMsg.reply) {
return (response) => {
Object.assign(response, { id });
const outgoingResponse = this.serializer.serialize(response);
return natsMsg.respond(outgoingResponse.data, {
headers: outgoingResponse.headers,
});
};
}
// In case the "reply" topic is not provided, there's no need for a reply.
// Method returns a noop function instead
return () => { };
}
async handleStatusUpdates(client) {
for await (const status of client.status()) {
try {
switch (status.type) {
case 'error':
this.logger.error(`NatsError: type: "${status.type}", error: "${status.error}".`);
break;
case 'disconnect':
this.logger.error(`NatsError: type: "${status.type}".`);
this._status$.next("disconnected" /* NatsStatus.DISCONNECTED */);
this.statusEventEmitter.emit("disconnect" /* NatsEventsMap.DISCONNECT */, status.server);
break;
case 'ping':
if (this.options.debug) {
this.logger.debug(`NatsStatus: type: "${status.type}", pending pings: "${status.pendingPings}".`);
}
break;
case 'reconnecting':
this._status$.next("reconnecting" /* NatsStatus.RECONNECTING */);
break;
case 'reconnect':
this.logger.log(`NatsStatus: type: "${status.type}".`);
this._status$.next("connected" /* NatsStatus.CONNECTED */);
this.statusEventEmitter.emit("reconnect" /* NatsEventsMap.RECONNECT */, status.server);
break;
case 'update':
this.logger.log(`NatsStatus: type: "${status.type}", added: "${status.added}", deleted: "${status.deleted}".`);
this.statusEventEmitter.emit("update" /* NatsEventsMap.UPDATE */, {
added: status.added,
deleted: status.deleted,
});
break;
default: {
const data = 'data' in status && isObject(status.data)
? JSON.stringify(status.data)
: 'data' in status
? status.data
: '';
this.logger.log(`NatsStatus: type: "${status.type}", data: "${data}".`);
break;
}
}
}
catch (err) {
// A throwing listener must neither end the status updates nor
// escape as an unhandled rejection
this.logger.error(err);
}
}
// The status iterator only completes once the client is closed for good.
// Unless close() closed it, the server no longer receives any message.
if (this.natsClient === client) {
this._status$.next("disconnected" /* NatsStatus.DISCONNECTED */);
this.logger.error('The connection to the NATS server is closed and will not be reopened (see the "maxReconnectAttempts" option). The microservice no longer receives messages.');
}
}
unwrap() {
if (!this.natsClient) {
throw new Error('Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing the server.');
}
return this.natsClient;
}
on(event, callback) {
this.statusEventEmitter.on(event, callback);
}
initializeSerializer(options) {
this.serializer = options?.serializer ?? new NatsRecordSerializer();
}
initializeDeserializer(options) {
this.deserializer =
options?.deserializer ?? new NatsRequestJSONDeserializer();
}
}