nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.76k stars 7.64k forks source link

Provide a callback handle config for NatsServer. Currently if NatsServer disconnects a hybrid application has no way of getting notified. #10581

Open arkh-consensys opened 1 year ago

arkh-consensys commented 1 year ago

Is there an existing issue that is already proposing this?

Is your feature request related to a problem? Please describe it

When NATS client (js) reaches to a ProtocolError it will close the connection without reconnecting: ref, but the NatsServer used underneath by nestJS framework only logs this event as an error and doesn't provide any handle, callback to recover or exit from it. NestJS ref

This is ok for single server microservices because either they are configured for reconnect or upon a disconnect event the process is killed. However, for a hybrid micorservice which has a NatsServer and an HTTP Server, the process continues serving http request whereas the NatsServer is down.

Describe the solution you'd like

Getting a callback handle errorCallback from Nats config (NatsOptions) and call it upon detecting an error from nats.


  public async handleStatusUpdates(client: Client) {
    for await (const status of client.status()) {
      ....
      if (status.type === 'disconnect' || status.type === 'error') {
        this.logger.error(
          `NatsError: type: "${status.type}", data: "${data}".`,
        );

        if(status.type === 'error') {
        this.errorCallback()
        }

      } else {
        ....
    }
  }`

### Teachability, documentation, adoption, migration strategy

It is not a breaking change as the default `errorCallback` could be an empty function doing nothing.

### What is the motivation / use case for changing the behavior?

To be able to react upon the nats server closes connection upon NatsProtocolError or other uncaptured nats errors for a hybrid application.
arkus7 commented 1 year ago

The same issue is with the RabbitMQ server. While you can set how many times the server can try to connect to the broker by using maxConnectionAttempts option, if the connection is lost after the initial connection (after a channel is created), the app is trying to retry connection indefinitely (ref).

I would like to react to such an event, or at least have the option to specify that the app should try up to X times.

kamilmysliwiec commented 1 year ago

Would you like to create a PR for this issue?

Muhamed23 commented 1 year ago

Hey @kamilmysliwiec what is the status for this ?

kamilmysliwiec commented 1 year ago

Would you like to create a PR for this issue?