import { Controller, Get } from '@nestjs/common'; import { HealthCheck, HealthCheckService, HttpHealthIndicator, DiskHealthIndicator, MemoryHealthIndicator, } from '@nestjs/terminus'; import { TypeOrmHealthIndicator } from './indicators/typeorm.health'; import { DbPoolStatsIndicator } from './indicators/db-pool-stats.health'; import { ConfigService } from '@nestjs/config'; import { ApiTags, ApiOperation } from '@nestjs/swagger'; import * as os from 'os'; @ApiTags('Health Check') @Controller('health') export class HealthController { private readonly diskPath: string; constructor( private health: HealthCheckService, private http: HttpHealthIndicator, private disk: DiskHealthIndicator, private memory: MemoryHealthIndicator, private typeOrmHealth: TypeOrmHealthIndicator, private dbPoolStats: DbPoolStatsIndicator, private configService: ConfigService, ) { // Define o caminho correto para o disco, baseado no sistema operacional this.diskPath = os.platform() === 'win32' ? 'C:\\' : '/'; } @Get() @HealthCheck() @ApiOperation({ summary: 'Verificar saúde geral da aplicação' }) check() { return this.health.check([ // Verifica o status da própria aplicação () => this.http.pingCheck('api', 'http://localhost:8066/docs'), // Verifica espaço em disco (espaço livre < 80%) () => this.disk.checkStorage('disk_percent', { path: this.diskPath, thresholdPercent: 0.8, // 80% }), // Verifica espaço em disco (pelo menos 500MB livres) () => this.disk.checkStorage('disk_space', { path: this.diskPath, threshold: 500 * 1024 * 1024, // 500MB em bytes }), // Verifica uso de memória (heap <150MB) () => this.memory.checkHeap('memory_heap', 150 * 1024 * 1024), // 150MB // Verifica as conexões de banco de dados () => this.typeOrmHealth.checkOracle(), () => this.typeOrmHealth.checkPostgres(), ]); } @Get('db') @HealthCheck() @ApiOperation({ summary: 'Verificar saúde das conexões de banco de dados' }) checkDatabase() { return this.health.check([ () => this.typeOrmHealth.checkOracle(), () => this.typeOrmHealth.checkPostgres(), ]); } @Get('memory') @HealthCheck() @ApiOperation({ summary: 'Verificar uso de memória' }) checkMemory() { return this.health.check([ () => this.memory.checkHeap('memory_heap', 150 * 1024 * 1024), () => this.memory.checkRSS('memory_rss', 300 * 1024 * 1024), ]); } @Get('disk') @HealthCheck() @ApiOperation({ summary: 'Verificar espaço em disco' }) checkDisk() { return this.health.check([ // Verificar espaço em disco usando porcentagem () => this.disk.checkStorage('disk_percent', { path: this.diskPath, thresholdPercent: 0.8, }), // Verificar espaço em disco usando valor absoluto () => this.disk.checkStorage('disk_space', { path: this.diskPath, threshold: 500 * 1024 * 1024, }), ]); } @Get('pool') @HealthCheck() @ApiOperation({ summary: 'Verificar estatísticas do pool de conexões' }) checkPoolStats() { return this.health.check([ () => this.dbPoolStats.checkOraclePoolStats(), () => this.dbPoolStats.checkPostgresPoolStats(), ]); } }