fastify / fastify-redis

Plugin to share a common Redis connection across Fastify.
MIT License
203 stars 32 forks source link

fastify.ready fulfills before the Redis connection is established #197

Open 2ico opened 4 months ago

2ico commented 4 months ago

Prerequisites

Fastify version

4.10.2

Plugin version

6.1.1

Node.js version

18.18

Operating system

Linux

Operating system version (i.e. 20.04, 11.3, 10)

5.10

Description

How am I supposed to have the server quit in case the Redis server is offline?

Ideally, I'd expect redis.register to block server.ready untl the connection is ready.

server.ts

await fastify.register(redis, { url: fastify.config.REDIS_URL, namespace: "main" /* other redis options */ }).after(err => {
  const { redis } = fastify;
  if (err) {
    fastify.log.error(`Redis connection error: Coult not connect to ${fastify.config.REDIS_URL}`)
    process.exit(1)
  }

})

await fastify.ready();
export default fastify;

index.ts

import server from './server.js'

process.on('unhandledRejection', (err) => {
  console.error(err);
  process.exit(1);
});

const port = +server.config.API_PORT;
const host = server.config.API_HOST;
await server.listen({ host, port }, (err, address) => {

  if(err){
    server.log.error(err)
    process.exit(2)
  }

  server.log.trace(`Server start: [${port}:] ${address}:${port}-${process.pid}/start`);

  // for pm2
  if (process.send != null) {
    process.send('ready');
  }
})

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.on(signal, () =>
    server.close().then((err) => {
      console.log(`close application on ${signal}`);
      process.exit(err ? 1 : 0);
    }),
  );
}

Link to code that reproduces the bug

No response

Expected Behavior

No response

mcollina commented 4 months ago

Thanks for reporting!

Can you provide steps to reproduce? We often need a reproducible example, e.g. some code that allows someone else to recreate your problem by just copying and pasting it. If it involves more than a couple of different file, create a new repository on GitHub and add a link to that.