@nestjs/microservices
Version:
Nest - modern, fast, powerful node.js web framework (@microservices)
158 lines (157 loc) • 6.34 kB
JavaScript
import * as net from 'net';
import { createServer as tlsCreateServer } from 'tls';
import { EADDRINUSE, ECONNREFUSED, NO_MESSAGE_HANDLER, TCP_DEFAULT_HOST, TCP_DEFAULT_PORT, } from '../constants.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 { isString, isUndefined } from '@nestjs/common/internal';
/**
* @publicApi
*/
export class ServerTCP extends Server {
options;
transportId = Transport.TCP;
server;
port;
host;
socketClass;
maxBufferSize;
isManuallyTerminated = false;
retryAttemptsCount = 0;
tlsOptions;
pendingEventListeners = [];
constructor(options) {
super();
this.options = options;
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.init();
this.initializeSerializer(options);
this.initializeDeserializer(options);
}
listen(callback) {
this.server.once("error" /* TcpEventsMap.ERROR */, (err) => {
if (err?.code === EADDRINUSE || err?.code === ECONNREFUSED) {
this._status$.next("disconnected" /* TcpStatus.DISCONNECTED */);
return callback(err);
}
});
this.server.listen(this.port, this.host, callback);
}
close() {
this.isManuallyTerminated = true;
this.server.close();
this.pendingEventListeners = [];
}
bindHandler(socket) {
const readSocket = this.getSocketInstance(socket);
readSocket.on('message', async (msg) => this.handleMessage(readSocket, msg));
readSocket.on("error" /* TcpEventsMap.ERROR */, err => {
const invalidError = new InvalidTcpDataReceptionException(err);
this.handleError(invalidError);
});
}
async handleMessage(socket, rawMessage) {
const packet = await this.deserializer.deserialize(rawMessage);
const pattern = !isString(packet.pattern)
? JSON.stringify(packet.pattern)
: packet.pattern;
const tcpContext = new TcpContext([socket, pattern]);
if (isUndefined(packet.id)) {
return this.handleEvent(pattern, packet, tcpContext);
}
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);
}
return this.onProcessingStartHook(this.transportId, tcpContext, async () => {
const response$ = this.transformToObservable(await handler(packet.data, tcpContext));
response$ &&
this.send(response$, data => {
Object.assign(data, { id: packet.id });
const outgoingResponse = this.serializer.serialize(data);
this.onProcessingEndHook?.(this.transportId, tcpContext);
socket.sendMessage(outgoingResponse);
});
});
}
handleClose() {
if (this.isManuallyTerminated ||
!this.getOptionsProp(this.options, 'retryAttempts') ||
this.retryAttemptsCount >=
this.getOptionsProp(this.options, 'retryAttempts', 0)) {
return undefined;
}
++this.retryAttemptsCount;
return setTimeout(() => this.server.listen(this.port, this.host), this.getOptionsProp(this.options, 'retryDelay', 0));
}
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));
}
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();
});
}
getSocketInstance(socket) {
// Pass maxBufferSize only if socketClass is JsonSocket
// For custom socket classes, users should handle maxBufferSize in their own implementation
if (this.maxBufferSize !== undefined && this.socketClass === JsonSocket) {
return new this.socketClass(socket, {
maxBufferSize: this.maxBufferSize,
});
}
return new this.socketClass(socket);
}
}