UNPKG

@nestjs/microservices

Version:

Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.

467 lines (466 loc) • 20.7 kB
import * as net from 'net'; import { isObservable, of, ReplaySubject } from 'rxjs'; import { switchMap, takeUntil } from 'rxjs/operators'; import { createServer as tlsCreateServer } from 'tls'; import { ECONNREFUSED, MAX_TIMEOUT, NO_MESSAGE_HANDLER, TCP_DEFAULT_HOST, TCP_DEFAULT_PORT, } from '../constants.js'; import { getHandlerObservableNotifier } from '../context/rpc-context-creator.js'; import { TcpContext } from '../ctx-host/tcp.context.js'; import { Transport } from '../enums/index.js'; import { JsonSocket } from '../helpers/index.js'; import { InvalidTcpDataReceptionException } from '../errors/invalid-tcp-data-reception.exception.js'; import { Server } from './server.js'; import { isUndefined } from '@nestjs/common/internal'; const DEFAULT_MAX_CONCURRENT_MESSAGES = 1000; /** * @publicApi */ export class ServerTCP extends Server { options; transportId = Transport.TCP; server; port; host; socketClass; maxBufferSize; incompleteMessageTimeout; messageReceiveTimeout; maxSendBufferSize; drainTimeout; maxConcurrentMessages; isManuallyTerminated = false; retryAttemptsCount = 0; retryTimer; tlsOptions; pendingEventListeners = []; /** * Sockets accepted by this server that are still open. "net.Server#close" * only stops the server from accepting new connections, so these are tracked * separately and torn down on "close" - otherwise the process outlives the * shutdown and handlers keep running on already established connections. */ openSockets = new Set(); /** * Sockets bound by "bindHandler" that are still open, which are the ones * requests and events arrive on. */ boundSockets = new Set(); /** * Notifiers that emit once a socket bound by "bindHandler" can no longer be * written to. They replay, so that a response stream that only starts after * the peer has gone ends right away as well. */ disconnectNotifiers = new WeakMap(); /** * How many messages of each socket are being handled. */ pendingMessages = new WeakMap(); /** * What settles the message of a context, until a processing end hook * runner takes it over (see "createProcessingEndHookRunner"). */ pendingMessageSettlers = new WeakMap(); constructor(options) { super(); this.options = options; // Present but empty, e.g. "host: process.env.HOST" with the variable // unset, means the default as well. Listening with no host would accept // connections on every interface rather than on localhost. this.port = this.getOptionsProp(options, 'port') ?? TCP_DEFAULT_PORT; this.host = this.getOptionsProp(options, 'host') || TCP_DEFAULT_HOST; this.socketClass = this.getOptionsProp(options, 'socketClass') ?? JsonSocket; this.tlsOptions = this.getOptionsProp(options, 'tlsOptions'); this.maxBufferSize = this.getOptionsProp(options, 'maxBufferSize'); this.incompleteMessageTimeout = this.getOptionsProp(options, 'incompleteMessageTimeout'); this.messageReceiveTimeout = this.getOptionsProp(options, 'messageReceiveTimeout'); this.maxSendBufferSize = this.getOptionsProp(options, 'maxSendBufferSize'); this.drainTimeout = this.getOptionsProp(options, 'drainTimeout'); // Not a number gets the default as well, and 0 lifts the limit const maxConcurrentMessages = this.getOptionsProp(options, 'maxConcurrentMessages'); this.maxConcurrentMessages = maxConcurrentMessages == null || isNaN(maxConcurrentMessages) ? DEFAULT_MAX_CONCURRENT_MESSAGES : maxConcurrentMessages || Infinity; this.init(); this.initializeSerializer(options); this.initializeDeserializer(options); } listen(callback) { // Each listen() counts its own attempts towards "retryAttempts". Without // this, a listen() after one that exhausted its attempts starts above the // limit and never retries again. this.retryAttemptsCount = 0; // A close() before this listen() must not keep retries off for good this.isManuallyTerminated = false; // A retry armed before this listen() would otherwise still fire, calling // "listen" on a server that is already listening (ERR_SERVER_ALREADY_LISTEN // thrown from a timer), and "handleClose" would keep returning it instead // of arming a retry for this listen(). if (this.retryTimer) { clearTimeout(this.retryTimer); this.retryTimer = undefined; } // The once('error') listener outlives a successful listen, so a later // error must find the callback already settled. let listenCallback = callback; const settleListenCallback = (err) => { const cb = listenCallback; listenCallback = undefined; isUndefined(err) ? cb?.() : cb?.(err); }; this.server.once("error" /* TcpEventsMap.ERROR */, err => { if (!listenCallback) { return; } this._status$.next("disconnected" /* TcpStatus.DISCONNECTED */); settleListenCallback(err); }); this.server.listen(this.port, this.host, () => settleListenCallback()); } close() { this.isManuallyTerminated = true; if (this.retryTimer) { clearTimeout(this.retryTimer); this.retryTimer = undefined; } this.server.close(); this.pendingEventListeners = []; if (this.getOptionsProp(this.options, 'gracefulShutdown')) { return this.closeOpenSocketsGracefully(); } this.closeOpenSockets(); } bindHandler(socket) { this.trackOpenSocket(socket); if (this.isManuallyTerminated) { // A TLS handshake that was under way when the server was closed socket.destroy(); return; } const readSocket = this.getSocketInstance(socket); this.boundSockets.add(readSocket); readSocket.on("close" /* TcpEventsMap.CLOSE */, () => this.boundSockets.delete(readSocket)); this.trackDisconnect(readSocket); readSocket.on('message', (msg) => this.handleMessage(readSocket, msg).catch(err => this.handleError(err))); readSocket.on("error" /* TcpEventsMap.ERROR */, err => { const invalidError = new InvalidTcpDataReceptionException(err); this.handleError(invalidError); }); } async handleMessage(socket, rawMessage) { if (this.isManuallyTerminated) { // A connection kept open for the replies it is owed takes no more work return; } // Up to its first "await" this runs within the "message" event, so a // socket paused here emits no further message of the same read const settle = this.trackPendingMessage(socket); let tcpContext; try { const packet = await this.deserializer.deserialize(rawMessage); const pattern = this.getPatternAsString(packet.pattern); tcpContext = new TcpContext([socket, pattern, packet.metadata]); this.pendingMessageSettlers.set(tcpContext, settle); return await this.dispatchMessage(socket, packet, pattern, tcpContext); } finally { // A message a handler was started for is settled by its processing end // hook runner (see "createProcessingEndHookRunner"), once the handler // and the stream it returned are done. Any other is done with now. if (!tcpContext || this.pendingMessageSettlers.delete(tcpContext)) { settle(); } } } dispatchMessage(socket, packet, pattern, tcpContext) { if (isUndefined(packet.id)) { const handler = this.getHandlerByPattern(pattern); if (!handler || handler.isEventHandler) { return this.handleEvent(pattern, packet, tcpContext, handler); } // A message handler is called without an id as well (ClientProxy#emit). // Nobody waits for its reply, but the stream it returns belongs to the // connection it was called over, as for a request. Event handlers stay // detached from the connection the event came from. return this.handleRequest(tcpContext, async () => this.endOnDisconnect(await handler(packet.data, tcpContext), tcpContext, socket), () => undefined); } this.assertValidPacketId(packet.id); const handler = this.getHandlerByPattern(pattern); if (!handler) { const status = 'error'; const noHandlerPacket = this.serializer.serialize({ id: packet.id, status, err: NO_MESSAGE_HANDLER, }); return socket.sendMessage(noHandlerPacket); } this.warnIfEventHandlerReplies(handler, pattern); return this.handleRequest(tcpContext, async () => this.endOnDisconnect(await handler(packet.data, tcpContext), tcpContext, socket), data => { Object.assign(data, { id: packet.id }); const outgoingResponse = this.serializer.serialize(data); socket.sendMessage(outgoingResponse); }); } /** * Counts a message of "socket" as pending, and asks the socket for no * further messages while "maxConcurrentMessages" of them are. How many a * peer sends before any of them is done is up to the peer, and each takes * up memory for as long as its handler, and the stream it returned, run. * Returns what to call, once, when the message is no longer pending. */ trackPendingMessage(socket) { const pending = (this.pendingMessages.get(socket) ?? 0) + 1; this.pendingMessages.set(socket, pending); if (pending >= this.maxConcurrentMessages) { // A socket class written for an older version may lack it socket.pauseMessages?.(); } let isPending = true; return () => { if (!isPending) { return; } isPending = false; const stillPending = this.pendingMessages.get(socket) - 1; this.pendingMessages.set(socket, stillPending); // Nothing more is dispatched once the server is closed, including what // a socket has read but not emitted yet if (stillPending < this.maxConcurrentMessages && !this.isManuallyTerminated) { socket.resumeMessages?.(); } // A graceful close ends each connection once its own messages are done if (stillPending === 0 && this.isManuallyTerminated && this.getOptionsProp(this.options, 'gracefulShutdown')) { // The replies of a stream that has just settled are written over the // next ticks (see "Server#send") setImmediate(() => this.endSocketIfIdle(socket)); } }; } /** * Keeps a message pending from the moment its handler is about to run until * the handler, and the stream it returned, have settled, which is also when * the processing end hook runs. */ createProcessingEndHookRunner(context) { const runEndHook = super.createProcessingEndHookRunner(context); const settle = this.pendingMessageSettlers.get(context); if (!settle) { return runEndHook; } this.pendingMessageSettlers.delete(context); return () => { try { runEndHook(); } finally { settle(); } }; } handleClose() { if (this.retryTimer) { return this.retryTimer; } if (this.isManuallyTerminated || // The "close" event of a close() that a listen() already followed (it // fires once the open connections end): there is nothing to retry this.server.listening || !this.getOptionsProp(this.options, 'retryAttempts') || this.retryAttemptsCount >= this.getOptionsProp(this.options, 'retryAttempts', 0)) { return undefined; } ++this.retryAttemptsCount; this.retryTimer = setTimeout(() => { this.retryTimer = undefined; // Listening again throws ERR_SERVER_ALREADY_LISTEN from this timer if (!this.isManuallyTerminated && !this.server.listening) { this.server.listen(this.port, this.host); } }, this.getOptionsProp(this.options, 'retryDelay', 0)); return this.retryTimer; } unwrap() { if (!this.server) { throw new Error('Not initialized. Please call the "listen"/"startAllMicroservices" method before accessing the server.'); } return this.server; } on(event, callback) { if (this.server) { this.server.on(event, callback); } else { this.pendingEventListeners.push({ event, callback }); } } init() { if (this.tlsOptions) { // TLS enabled, use tls server this.server = tlsCreateServer(this.tlsOptions, this.bindHandler.bind(this)); // "bindHandler" only runs once the TLS handshake is over. The raw socket // is tracked from the moment it is accepted, so that "close" also tears // down connections that are still in the middle of their handshake. this.server.on('connection', socket => this.trackOpenSocket(socket)); } else { // TLS disabled, use net server this.server = net.createServer(this.bindHandler.bind(this)); } this.registerListeningListener(this.server); this.registerErrorListener(this.server); this.registerCloseListener(this.server); this.pendingEventListeners.forEach(({ event, callback }) => this.server.on(event, callback)); this.pendingEventListeners = []; } registerListeningListener(socket) { socket.on("listening" /* TcpEventsMap.LISTENING */, () => { this._status$.next("connected" /* TcpStatus.CONNECTED */); }); } registerErrorListener(socket) { socket.on("error" /* TcpEventsMap.ERROR */, err => { if ('code' in err && err.code === ECONNREFUSED) { this._status$.next("disconnected" /* TcpStatus.DISCONNECTED */); } this.handleError(err); }); } registerCloseListener(socket) { socket.on("close" /* TcpEventsMap.CLOSE */, () => { this._status$.next("disconnected" /* TcpStatus.DISCONNECTED */); this.handleClose(); }); } /** * Keeps a reference to an accepted socket so that it can be destroyed when * the server is closed, and drops it again once it closes on its own. */ trackOpenSocket(socket) { if (!socket) { return; } this.openSockets.add(socket); socket.on("close" /* TcpEventsMap.CLOSE */, () => this.openSockets.delete(socket)); } /** * Destroys every socket still open. Called on shutdown so that "close" does * not leave the process alive, and so that no further messages are dispatched * to handlers over connections established before the shutdown. */ closeOpenSockets() { this.openSockets.forEach(socket => socket.destroy()); this.openSockets.clear(); } /** * Closes the connections that have nothing in flight right away, as * "closeOpenSockets" does, and the others once their requests and events * have been handled. Everything is closed "gracePeriod" after the call at * the latest. */ async closeOpenSocketsGracefully() { const gracePeriod = this.getGracePeriod(); const closeBy = Date.now() + gracePeriod; const idleSockets = [...this.boundSockets].filter(socket => !this.pendingMessages.get(socket)); // The replies of a stream that has just settled are written over the next // ticks (see "Server#send") await new Promise(resolve => setImmediate(resolve)); idleSockets.forEach(socket => this.endSocketIfIdle(socket)); // The others are ended as their own messages are done (see // "trackPendingMessage") await this.waitForHandlersInFlight(gracePeriod); // Every handler is done, or the period is over this.boundSockets.forEach(socket => this.endSocket(socket)); await this.waitForBoundSocketsToClose(closeBy - Date.now()); // What is left is a TLS handshake under way, or a peer that does not read this.closeOpenSockets(); } /** * Closes the socket once what was written to it has been sent, so that the * last replies reach the peer. */ endSocket(socket) { socket.netSocket.destroySoon(); } /** * Ends the socket unless it has closed already or a message of it is being * handled. */ endSocketIfIdle(socket) { if (this.boundSockets.has(socket) && !this.pendingMessages.get(socket)) { this.endSocket(socket); } } /** * "gracePeriod" as every transport reads it (see "normalizeGracePeriod"). */ getGracePeriod() { return this.normalizeGracePeriod(this.getOptionsProp(this.options, 'gracePeriod')); } waitForBoundSocketsToClose(timeout) { const sockets = [...this.boundSockets]; if (sockets.length === 0 || timeout <= 0) { return Promise.resolve(); } return new Promise(resolve => { let open = sockets.length; // "gracePeriod" can be longer than a timer supports (e.g. Infinity) const timer = setTimeout(resolve, Math.min(timeout, MAX_TIMEOUT)); sockets.forEach(socket => socket.once("close" /* TcpEventsMap.CLOSE */, () => { if (--open === 0) { clearTimeout(timer); resolve(); } })); }); } /** * Notes when the socket can no longer be written to: "TcpSocket" drops every * message once the socket has closed or errored. */ trackDisconnect(socket) { const disconnect$ = new ReplaySubject(1); socket.on("close" /* TcpEventsMap.CLOSE */, () => disconnect$.next()); socket.on("error" /* TcpEventsMap.ERROR */, () => disconnect$.next()); this.disconnectNotifiers.set(socket, disconnect$); } /** * Turns a handler result into the response stream. As for HTTP, the stream * ends once the peer disconnects only if the handler itself returned (or * resolved to) an Observable: any other handler, and the interceptors * around it, run to completion. */ endOnDisconnect(result, context, socket) { const response$ = this.transformToObservable(result); const disconnect$ = this.disconnectNotifiers.get(socket); if (!isObservable(result) || !disconnect$) { return response$; } // Without interceptors, "result" is what the handler returned const handlerObservable$ = getHandlerObservableNotifier(context) ?? of(null); return response$.pipe(takeUntil(handlerObservable$.pipe(switchMap(() => disconnect$)))); } getSocketInstance(socket) { // Pass the framing options only if socketClass is JsonSocket // For custom socket classes, users should handle them in their own implementation const hasJsonSocketOptions = this.maxBufferSize !== undefined || this.incompleteMessageTimeout !== undefined || this.messageReceiveTimeout !== undefined || this.maxSendBufferSize !== undefined || this.drainTimeout !== undefined; if (hasJsonSocketOptions && this.socketClass === JsonSocket) { return new this.socketClass(socket, { maxBufferSize: this.maxBufferSize, incompleteMessageTimeout: this.incompleteMessageTimeout, messageReceiveTimeout: this.messageReceiveTimeout, maxSendBufferSize: this.maxSendBufferSize, drainTimeout: this.drainTimeout, }); } return new this.socketClass(socket); } }