in src/sinks/connections/TcpClient.ts [87:124]
private async establishConnection(): Promise<void> {
await new Promise((resolve, reject) => {
const onError = (e: Error): void => {
// socket is already open, no need to connect
if (e.message.includes('EISCONN')) {
resolve();
return;
}
LOG('TCP Client received error', e);
this.disconnect(e.message);
reject(e);
};
const onConnect = (): void => {
this.socket.removeListener('error', onError);
LOG('TcpClient connected.', this.endpoint);
resolve();
};
// TODO: convert this to a proper state machine
switch (this.socket.readyState) {
case 'open':
resolve();
break;
case 'opening':
// the socket is currently opening, we will resolve
// or fail the current promise on the connect or
// error events
this.socket.once('connect', onConnect);
this.socket.once('error', onError);
break;
default:
LOG('opening connection with socket in state: ', this.socket.readyState);
this.socket.connect(this.endpoint.port, this.endpoint.host, onConnect).once('error', onError);
break;
}
});
}