| 15 | (process.env.NODE_ENV === 'production' ? '0.0.0.0' : 'localhost'); |
| 16 | |
| 17 | const startServer = async () => { |
| 18 | logger.info('Starting server'); |
| 19 | try { |
| 20 | const fastify = await buildApp(); |
| 21 | |
| 22 | if (process.env.NODE_ENV === 'production') { |
| 23 | logger.info('Registering graceful shutdown handlers'); |
| 24 | process.on('SIGTERM', async () => await shutdown(fastify, 'SIGTERM', 0)); |
| 25 | process.on('SIGINT', async () => await shutdown(fastify, 'SIGINT', 0)); |
| 26 | |
| 27 | // After an uncaughtException / unhandledRejection the process state |
| 28 | // is corrupt — don't try to gracefully drain queues/DBs. Log and |
| 29 | // exit immediately so Docker can respawn the container. Anything |
| 30 | // slower than this lets bad requests keep hitting a poisoned process |
| 31 | // and risks blocking past Docker's stop_grace_period (→ SIGKILL). |
| 32 | process.on('uncaughtException', (error) => { |
| 33 | logger.fatal({ err: error }, 'Uncaught exception — exiting'); |
| 34 | // Flush pino, then hard-exit. unref() so the safety net doesn't |
| 35 | // keep the loop alive on its own. |
| 36 | setTimeout(() => process.exit(1), 1000).unref(); |
| 37 | }); |
| 38 | process.on('unhandledRejection', (reason, promise) => { |
| 39 | logger.fatal({ reason, promise }, 'Unhandled rejection — exiting'); |
| 40 | setTimeout(() => process.exit(1), 1000).unref(); |
| 41 | }); |
| 42 | } |
| 43 | |
| 44 | await fastify.listen({ host, port }); |
| 45 | |
| 46 | try { |
| 47 | await getRedisPub().config('SET', 'notify-keyspace-events', 'Ex'); |
| 48 | } catch (error) { |
| 49 | logger.warn({ err: error }, 'Failed to set redis notify-keyspace-events'); |
| 50 | logger.warn( |
| 51 | 'If you use a managed Redis service, you may need to set this manually.', |
| 52 | ); |
| 53 | logger.warn('Otherwise some functions may not work as expected.'); |
| 54 | } |
| 55 | } catch (error) { |
| 56 | logger.error({ err: error }, 'Failed to start server'); |
| 57 | } |
| 58 | }; |
| 59 | |
| 60 | startServer(); |