cache-manager icon indicating copy to clipboard operation
cache-manager copied to clipboard

Implement cache client event listeners

Open aaroncraigongithub opened this issue 2 years ago • 3 comments

Is there an existing issue that is already proposing this?

  • [X] I have searched the existing issues

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

I often use console commands for long running jobs such as data migrations. I also have some workers that run in a headless Nest application.

In both instances, I occasionally have issues where the Redis cache client throws an ETIMEDOUT error. This has the effect of crashing the entire program, and no amount of try/catching seems to catch the error.

I believe the correct way to deal with this is to set up an event listener on the redis client itself, however I have not been able to find a way to get the client once it's been instantiated.

Unless I'm missing something, there is no opportunity to set up an error listener in the following example code:

    CacheModule.registerAsync<RedisClientOptions>({
      useFactory: async () => {
        const config = await getRedisConfig();

        return {
          ...config,
          store: redisStore,
        };
      },
    }),

Describe the solution you'd like

Being able to grab the client and set up listeners somewhere before it is used seems to be important. Ideally one could set up listeners at various touchpoints:

  • in the configuration itself
  • by exposing the client (or an .on() method) at runtime

Event listeners may be specific to the Redis client, in which case this would be a better request for that library.

Teachability, documentation, adoption, migration strategy

A possible API

Setting up listeners at config time:

    CacheModule.registerAsync<RedisClientOptions>({
      useFactory: async () => {
        const config = await getRedisConfig();

        return {
          ...config,
          store: redisStore,
          on: {
            error: globalCacheErrorHandler,
            // other event listeners
          }
        };
      },
    }),

Setting up listeners at run time

 @Injectable()
export class CacheService {
  constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {
    this.cacheManager.on('error', this.handleCacheError);
  }

  private handleCacheError(err: Error) {
    // ....
  }
}

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

As it stands, it's impossible to react to events emitted by the underlying client.

aaroncraigongithub avatar Feb 16 '23 05:02 aaroncraigongithub