import { Global, Injectable, Module, ServiceUnavailableException, } from '@nestjs/common'; import { DatabaseClient } from '../database/database.client.js'; import { RedisClient } from '../redis/redis.client.js'; @Injectable() export class HealthService { private ready = true; constructor( private readonly database: DatabaseClient, private readonly redis: RedisClient, ) {} getLiveness() { return { status: 'ok' as const }; } // Load-balancer probe, deliberately independent of PostgreSQL and Redis: a // shared dependency outage cannot be fixed by removing replicas from // rotation, and draining every backend would answer clients with the LB's // own HTML error page instead of the bounded API 503. /health/ready stays // the operator-facing readiness signal. getLbCheck() { if (!this.ready) throw new ServiceUnavailableException('Draining'); return { status: 'ok' as const }; } async getReadiness() { if (!this.ready) throw new ServiceUnavailableException('Service is shutting down'); try { await Promise.all([this.database.health(), this.redis.health()]); } catch { throw new ServiceUnavailableException('Dependencies unavailable'); } return { status: 'ok' as const }; } // Called on SIGTERM before the drain delay: the replica turns not-ready for // both the LB probe and the operator probe while it finishes in-flight // requests. The delay itself lives in main.ts, because Nest destroys // providers (closing the pools) before this class could serve anyone. setDraining() { this.ready = false; } } @Global() @Module({ providers: [HealthService], exports: [HealthService] }) export class HealthServiceModule {}