UNPKG

@nestjs/microservices

Version:

Nest - modern, fast, powerful node.js web framework (@microservices)

193 lines (192 loc) 7.76 kB
import { isObject, isUndefined } from '@nestjs/common/internal'; import { EventEmitter } from 'events'; import { NATS_DEFAULT_GRACE_PERIOD, 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; statusEventEmitter = new EventEmitter(); subscriptions = []; constructor(options) { super(); this.options = options; this.initializeSerializer(options); this.initializeDeserializer(options); } async listen(callback) { try { this.natsClient = await this.createNatsClient(); this._status$.next("connected" /* NatsStatus.CONNECTED */); void this.handleStatusUpdates(this.natsClient); 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 waitForGracePeriod() { const gracePeriod = this.getOptionsProp(this.options, 'gracePeriod', NATS_DEFAULT_GRACE_PERIOD); await new Promise(res => { setTimeout(() => { res(); }, gracePeriod); }); } async close() { if (!this.natsClient) { return; } const graceful = this.getOptionsProp(this.options, 'gracefulShutdown'); if (graceful) { this.subscriptions.forEach(sub => sub.unsubscribe()); await this.waitForGracePeriod(); } await this.natsClient?.close(); this.statusEventEmitter.removeAllListeners(); this.natsClient = null; } 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); }; } 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 (isUndefined(message.id)) { return this.handleEvent(channel, message, natsCtx); } 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); } return this.onProcessingStartHook(this.transportId, natsCtx, async () => { const response$ = this.transformToObservable(await handler(message.data, natsCtx)); response$ && this.send(response$, publish); }); } getPublisher(natsMsg, id, ctx) { if (natsMsg.reply) { return (response) => { Object.assign(response, { id }); const outgoingResponse = this.serializer.serialize(response); this.onProcessingEndHook?.(this.transportId, ctx); 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()) { 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; } } } } 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(); } }