mirror of
https://github.com/nestjs/nest.git
synced 2026-02-21 23:11:44 +00:00
feat(microservice): add tcp over tls support
Signed-off-by: nomaxg <noahgolub2@gmail.com>
This commit is contained in:
@@ -2,6 +2,7 @@ import { Logger, Type } from '@nestjs/common';
|
||||
import * as net from 'net';
|
||||
import { EmptyError, lastValueFrom } from 'rxjs';
|
||||
import { share, tap } from 'rxjs/operators';
|
||||
import { ConnectionOptions } from 'tls';
|
||||
import {
|
||||
CLOSE_EVENT,
|
||||
ECONNREFUSED,
|
||||
@@ -11,6 +12,7 @@ import {
|
||||
TCP_DEFAULT_PORT,
|
||||
} from '../constants';
|
||||
import { JsonSocket, TcpSocket } from '../helpers';
|
||||
import { connect as tlsConnect, TLSSocket } from 'tls';
|
||||
import { PacketId, ReadPacket, WritePacket } from '../interfaces';
|
||||
import { TcpClientOptions } from '../interfaces/client-metadata.interface';
|
||||
import { ClientProxy } from './client-proxy';
|
||||
@@ -23,6 +25,7 @@ export class ClientTCP extends ClientProxy {
|
||||
private readonly socketClass: Type<TcpSocket>;
|
||||
private isConnected = false;
|
||||
private socket: TcpSocket;
|
||||
public tlsOptions?: ConnectionOptions;
|
||||
|
||||
constructor(options: TcpClientOptions['options']) {
|
||||
super();
|
||||
@@ -30,6 +33,7 @@ export class ClientTCP extends ClientProxy {
|
||||
this.host = this.getOptionsProp(options, 'host') || TCP_DEFAULT_HOST;
|
||||
this.socketClass =
|
||||
this.getOptionsProp(options, 'socketClass') || JsonSocket;
|
||||
this.tlsOptions = this.getOptionsProp(options, 'tlsOptions');
|
||||
|
||||
this.initializeSerializer(options);
|
||||
this.initializeDeserializer(options);
|
||||
@@ -42,6 +46,10 @@ export class ClientTCP extends ClientProxy {
|
||||
this.socket = this.createSocket();
|
||||
this.bindEvents(this.socket);
|
||||
|
||||
if (!this.tlsOptions) {
|
||||
this.socket.connect(this.port, this.host);
|
||||
}
|
||||
|
||||
const source$ = this.connect$(this.socket.netSocket).pipe(
|
||||
tap(() => {
|
||||
this.isConnected = true;
|
||||
@@ -52,7 +60,6 @@ export class ClientTCP extends ClientProxy {
|
||||
share(),
|
||||
);
|
||||
|
||||
this.socket.connect(this.port, this.host);
|
||||
this.connection = lastValueFrom(source$).catch(err => {
|
||||
if (err instanceof EmptyError) {
|
||||
return;
|
||||
@@ -84,7 +91,21 @@ export class ClientTCP extends ClientProxy {
|
||||
}
|
||||
|
||||
public createSocket(): TcpSocket {
|
||||
return new this.socketClass(new net.Socket());
|
||||
let socket: net.Socket | TLSSocket;
|
||||
/**
|
||||
* TLS enabled, "upgrade" the TCP Socket to TLS
|
||||
*/
|
||||
if (this.tlsOptions) {
|
||||
socket = tlsConnect({
|
||||
...this.tlsOptions,
|
||||
port: this.port,
|
||||
host: this.host,
|
||||
socket,
|
||||
});
|
||||
} else {
|
||||
socket = new net.Socket();
|
||||
}
|
||||
return new this.socketClass(socket);
|
||||
}
|
||||
|
||||
public close() {
|
||||
|
||||
Reference in New Issue
Block a user