grafana e prometeus

This commit is contained in:
JurTI-BR
2025-04-03 16:43:30 -03:00
parent 8ba6f345c7
commit b7e5cb64aa
35 changed files with 962 additions and 942 deletions

View File

@@ -0,0 +1,258 @@
import { Injectable, Logger } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { firstValueFrom } from 'rxjs';
import { HealthCheckResult } from '@nestjs/terminus';
@Injectable()
export class HealthAlertService {
private readonly logger = new Logger(HealthAlertService.name);
private readonly webhookUrls: Record<string, string>;
private readonly alertThresholds: Record<string, any>;
private readonly alertCooldowns: Map<string, number> = new Map();
constructor(
private readonly httpService: HttpService,
private readonly configService: ConfigService,
) {
// Configurações de webhooks para diferentes canais de alerta
this.webhookUrls = {
slack: this.configService.get<string>('ALERT_WEBHOOK_SLACK'),
teams: this.configService.get<string>('ALERT_WEBHOOK_TEAMS'),
email: this.configService.get<string>('ALERT_WEBHOOK_EMAIL'),
};
// Thresholds para diferentes tipos de alerta
this.alertThresholds = {
disk: {
criticalPercent: this.configService.get<number>('ALERT_DISK_CRITICAL_PERCENT', 90),
warningPercent: this.configService.get<number>('ALERT_DISK_WARNING_PERCENT', 80),
},
memory: {
criticalPercent: this.configService.get<number>('ALERT_MEMORY_CRITICAL_PERCENT', 90),
warningPercent: this.configService.get<number>('ALERT_MEMORY_WARNING_PERCENT', 80),
},
db: {
cooldownMinutes: this.configService.get<number>('ALERT_DB_COOLDOWN_MINUTES', 15),
},
};
}
async processHealthCheckResult(result: HealthCheckResult): Promise<void> {
try {
const { status, info, error, details } = result;
// Se o status geral não for 'ok', envie um alerta
if (status !== 'ok') {
// Verificar quais componentes estão com problema
const failedComponents = Object.entries(error)
.map(([key, value]) => ({ key, value }));
if (failedComponents.length > 0) {
await this.sendAlert('critical', 'Health Check Falhou',
`Os seguintes componentes estão com problemas: ${failedComponents.map(c => c.key).join(', ')}`,
{ result, failedComponents }
);
}
}
// Verificar alertas específicos para cada tipo de componente
if (details.disk) {
await this.checkDiskAlerts(details.disk);
}
if (details.memory_heap) {
await this.checkMemoryAlerts(details.memory_heap);
}
// Verificar alertas de banco de dados
['oracle', 'postgres'].forEach(db => {
if (details[db] && details[db].status !== 'up') {
this.checkDatabaseAlerts(db, details[db]);
}
});
} catch (error) {
this.logger.error(`Erro ao processar health check result: ${error.message}`, error.stack);
}
}
private async checkDiskAlerts(diskDetails: any): Promise<void> {
try {
if (!diskDetails.freeBytes || !diskDetails.totalBytes) {
return;
}
const usedPercent = ((diskDetails.totalBytes - diskDetails.freeBytes) / diskDetails.totalBytes) * 100;
if (usedPercent >= this.alertThresholds.disk.criticalPercent) {
await this.sendAlert('critical', 'Espaço em Disco Crítico',
`O uso de disco está em ${usedPercent.toFixed(1)}%, acima do limite crítico de ${this.alertThresholds.disk.criticalPercent}%`,
{ diskDetails, usedPercent }
);
} else if (usedPercent >= this.alertThresholds.disk.warningPercent) {
await this.sendAlert('warning', 'Alerta de Espaço em Disco',
`O uso de disco está em ${usedPercent.toFixed(1)}%, acima do limite de alerta de ${this.alertThresholds.disk.warningPercent}%`,
{ diskDetails, usedPercent }
);
}
} catch (error) {
this.logger.error(`Erro ao verificar alertas de disco: ${error.message}`);
}
}
private async checkMemoryAlerts(memoryDetails: any): Promise<void> {
try {
if (!memoryDetails.usedBytes || !memoryDetails.thresholdBytes) {
return;
}
const usedPercent = (memoryDetails.usedBytes / memoryDetails.thresholdBytes) * 100;
if (usedPercent >= this.alertThresholds.memory.criticalPercent) {
await this.sendAlert('critical', 'Uso de Memória Crítico',
`O uso de memória heap está em ${usedPercent.toFixed(1)}%, acima do limite crítico de ${this.alertThresholds.memory.criticalPercent}%`,
{ memoryDetails, usedPercent }
);
} else if (usedPercent >= this.alertThresholds.memory.warningPercent) {
await this.sendAlert('warning', 'Alerta de Uso de Memória',
`O uso de memória heap está em ${usedPercent.toFixed(1)}%, acima do limite de alerta de ${this.alertThresholds.memory.warningPercent}%`,
{ memoryDetails, usedPercent }
);
}
} catch (error) {
this.logger.error(`Erro ao verificar alertas de memória: ${error.message}`);
}
}
private async checkDatabaseAlerts(dbName: string, dbDetails: any): Promise<void> {
try {
const now = Date.now();
const lastAlertTime = this.alertCooldowns.get(dbName) || 0;
const cooldownMs = this.alertThresholds.db.cooldownMinutes * 60 * 1000;
// Verifica se já passou o período de cooldown para este banco
if (now - lastAlertTime >= cooldownMs) {
await this.sendAlert('critical', `Problema de Conexão com Banco de Dados ${dbName}`,
`A conexão com o banco de dados ${dbName} está com problemas: ${dbDetails.message || 'Erro não especificado'}`,
{ dbName, dbDetails }
);
// Atualiza o timestamp do último alerta
this.alertCooldowns.set(dbName, now);
}
} catch (error) {
this.logger.error(`Erro ao verificar alertas de banco de dados: ${error.message}`);
}
}
private async sendAlert(
severity: 'critical' | 'warning' | 'info',
title: string,
message: string,
details?: any,
): Promise<void> {
try {
const environment = this.configService.get<string>('NODE_ENV', 'development');
const appName = this.configService.get<string>('APP_NAME', 'Portal Jurunense API');
this.logger.warn(`[${severity.toUpperCase()}] ${title}: ${message}`);
const payload = {
severity,
title: `[${environment.toUpperCase()}] [${appName}] ${title}`,
message,
timestamp: new Date().toISOString(),
details: details || {},
environment,
};
// Enviar para Slack, se configurado
if (this.webhookUrls.slack) {
await this.sendSlackAlert(payload);
}
// Enviar para Microsoft Teams, se configurado
if (this.webhookUrls.teams) {
await this.sendTeamsAlert(payload);
}
// Enviar para serviço de email, se configurado
if (this.webhookUrls.email) {
await this.sendEmailAlert(payload);
}
} catch (error) {
this.logger.error(`Erro ao enviar alerta: ${error.message}`, error.stack);
}
}
private async sendSlackAlert(payload: any): Promise<void> {
try {
const slackPayload = {
text: `${payload.title}`,
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: payload.title,
},
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `*Mensagem:* ${payload.message}\n*Severidade:* ${payload.severity}\n*Ambiente:* ${payload.environment}\n*Timestamp:* ${payload.timestamp}`,
},
},
],
};
await firstValueFrom(this.httpService.post(this.webhookUrls.slack, slackPayload));
} catch (error) {
this.logger.error(`Erro ao enviar alerta para Slack: ${error.message}`);
}
}
private async sendTeamsAlert(payload: any): Promise<void> {
try {
const teamsPayload = {
"@type": "MessageCard",
"@context": "http://schema.org/extensions",
"themeColor": payload.severity === 'critical' ? "FF0000" : (payload.severity === 'warning' ? "FFA500" : "0078D7"),
"summary": payload.title,
"sections": [
{
"activityTitle": payload.title,
"activitySubtitle": `Severidade: ${payload.severity} | Ambiente: ${payload.environment}`,
"text": payload.message,
"facts": [
{
"name": "Timestamp",
"value": payload.timestamp
}
]
}
]
};
await firstValueFrom(this.httpService.post(this.webhookUrls.teams, teamsPayload));
} catch (error) {
this.logger.error(`Erro ao enviar alerta para Microsoft Teams: ${error.message}`);
}
}
private async sendEmailAlert(payload: any): Promise<void> {
try {
const emailPayload = {
subject: payload.title,
text: `${payload.message}\n\nSeveridade: ${payload.severity}\nAmbiente: ${payload.environment}\nTimestamp: ${payload.timestamp}`,
html: `<h2>${payload.title}</h2><p>${payload.message}</p><p><strong>Severidade:</strong> ${payload.severity}<br><strong>Ambiente:</strong> ${payload.environment}<br><strong>Timestamp:</strong> ${payload.timestamp}</p>`,
};
await firstValueFrom(this.httpService.post(this.webhookUrls.email, emailPayload));
} catch (error) {
this.logger.error(`Erro ao enviar alerta por email: ${error.message}`);
}
}
}

View File

@@ -1,115 +0,0 @@
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.HealthController = void 0;
var common_1 = require("@nestjs/common");
var terminus_1 = require("@nestjs/terminus");
var swagger_1 = require("@nestjs/swagger");
var os = require("os");
var HealthController = /** @class */ (function () {
function HealthController(health, http, disk, memory, typeOrmHealth, dbPoolStats, configService) {
this.health = health;
this.http = http;
this.disk = disk;
this.memory = memory;
this.typeOrmHealth = typeOrmHealth;
this.dbPoolStats = dbPoolStats;
this.configService = configService;
// Define o caminho correto para o disco, baseado no sistema operacional
this.diskPath = os.platform() === 'win32' ? 'C:\\' : '/';
}
HealthController.prototype.check = function () {
var _this = this;
return this.health.check([
// Verifica o status da própria aplicação
function () { return _this.http.pingCheck('api', 'http://localhost:8066/docs'); },
// Verifica espaço em disco (espaço livre < 80%)
function () { return _this.disk.checkStorage('disk_percent', {
path: _this.diskPath,
thresholdPercent: 0.8
}); },
// Verifica espaço em disco (pelo menos 500MB livres)
function () { return _this.disk.checkStorage('disk_space', {
path: _this.diskPath,
threshold: 500 * 1024 * 1024
}); },
// Verifica uso de memória (heap <150MB)
function () { return _this.memory.checkHeap('memory_heap', 150 * 1024 * 1024); },
// Verifica as conexões de banco de dados
function () { return _this.typeOrmHealth.checkOracle(); },
function () { return _this.typeOrmHealth.checkPostgres(); },
]);
};
HealthController.prototype.checkDatabase = function () {
var _this = this;
return this.health.check([
function () { return _this.typeOrmHealth.checkOracle(); },
function () { return _this.typeOrmHealth.checkPostgres(); },
]);
};
HealthController.prototype.checkMemory = function () {
var _this = this;
return this.health.check([
function () { return _this.memory.checkHeap('memory_heap', 150 * 1024 * 1024); },
function () { return _this.memory.checkRSS('memory_rss', 300 * 1024 * 1024); },
]);
};
HealthController.prototype.checkDisk = function () {
var _this = this;
return this.health.check([
// Verificar espaço em disco usando porcentagem
function () { return _this.disk.checkStorage('disk_percent', {
path: _this.diskPath,
thresholdPercent: 0.8
}); },
// Verificar espaço em disco usando valor absoluto
function () { return _this.disk.checkStorage('disk_space', {
path: _this.diskPath,
threshold: 500 * 1024 * 1024
}); },
]);
};
HealthController.prototype.checkPoolStats = function () {
var _this = this;
return this.health.check([
function () { return _this.dbPoolStats.checkOraclePoolStats(); },
function () { return _this.dbPoolStats.checkPostgresPoolStats(); },
]);
};
__decorate([
common_1.Get(),
terminus_1.HealthCheck(),
swagger_1.ApiOperation({ summary: 'Verificar saúde geral da aplicação' })
], HealthController.prototype, "check");
__decorate([
common_1.Get('db'),
terminus_1.HealthCheck(),
swagger_1.ApiOperation({ summary: 'Verificar saúde das conexões de banco de dados' })
], HealthController.prototype, "checkDatabase");
__decorate([
common_1.Get('memory'),
terminus_1.HealthCheck(),
swagger_1.ApiOperation({ summary: 'Verificar uso de memória' })
], HealthController.prototype, "checkMemory");
__decorate([
common_1.Get('disk'),
terminus_1.HealthCheck(),
swagger_1.ApiOperation({ summary: 'Verificar espaço em disco' })
], HealthController.prototype, "checkDisk");
__decorate([
common_1.Get('pool'),
terminus_1.HealthCheck(),
swagger_1.ApiOperation({ summary: 'Verificar estatísticas do pool de conexões' })
], HealthController.prototype, "checkPoolStats");
HealthController = __decorate([
swagger_1.ApiTags('Health Check'),
common_1.Controller('health')
], HealthController);
return HealthController;
}());
exports.HealthController = HealthController;

View File

@@ -1,33 +0,0 @@
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
exports.__esModule = true;
exports.HealthModule = void 0;
var common_1 = require("@nestjs/common");
var terminus_1 = require("@nestjs/terminus");
var axios_1 = require("@nestjs/axios");
var health_controller_1 = require("./health.controller");
var typeorm_health_1 = require("./indicators/typeorm.health");
var db_pool_stats_health_1 = require("./indicators/db-pool-stats.health");
var config_1 = require("@nestjs/config");
var HealthModule = /** @class */ (function () {
function HealthModule() {
}
HealthModule = __decorate([
common_1.Module({
imports: [
terminus_1.TerminusModule,
axios_1.HttpModule,
config_1.ConfigModule,
],
controllers: [health_controller_1.HealthController],
providers: [typeorm_health_1.TypeOrmHealthIndicator, db_pool_stats_health_1.DbPoolStatsIndicator]
})
], HealthModule);
return HealthModule;
}());
exports.HealthModule = HealthModule;

View File

@@ -5,14 +5,40 @@ import { HealthController } from './health.controller';
import { TypeOrmHealthIndicator } from './indicators/typeorm.health';
import { DbPoolStatsIndicator } from './indicators/db-pool-stats.health';
import { ConfigModule } from '@nestjs/config';
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
import { metricProviders } from './metrics/metrics.config';
import { CustomMetricsService } from './metrics/custom.metrics';
import { MetricsInterceptor } from './metrics/metrics.interceptor';
import { HealthAlertService } from './alert/health-alert.service';
import { APP_INTERCEPTOR } from '@nestjs/core';
@Module({
imports: [
TerminusModule,
HttpModule,
ConfigModule,
PrometheusModule.register({
path: '/metrics',
defaultMetrics: {
enabled: true,
},
}),
],
controllers: [HealthController],
providers: [TypeOrmHealthIndicator, DbPoolStatsIndicator],
providers: [
TypeOrmHealthIndicator,
DbPoolStatsIndicator,
CustomMetricsService,
HealthAlertService,
{
provide: APP_INTERCEPTOR,
useClass: MetricsInterceptor,
},
...metricProviders,
],
exports: [
CustomMetricsService,
HealthAlertService,
],
})
export class HealthModule {}

View File

@@ -16,7 +16,6 @@ export class DbPoolStatsIndicator extends HealthIndicator {
const key = 'oracle_pool';
try {
// Obter estatísticas do pool Oracle (usando query específica do Oracle)
const queryResult = await this.oracleConnection.query(`
SELECT
'ORACLEDB_POOL' as source,

View File

@@ -1,150 +0,0 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.DbPoolStatsIndicator = void 0;
var common_1 = require("@nestjs/common");
var terminus_1 = require("@nestjs/terminus");
var typeorm_1 = require("@nestjs/typeorm");
var DbPoolStatsIndicator = /** @class */ (function (_super) {
__extends(DbPoolStatsIndicator, _super);
function DbPoolStatsIndicator(oracleConnection, postgresConnection) {
var _this = _super.call(this) || this;
_this.oracleConnection = oracleConnection;
_this.postgresConnection = postgresConnection;
return _this;
}
DbPoolStatsIndicator.prototype.checkOraclePoolStats = function () {
var _a;
return __awaiter(this, void 0, Promise, function () {
var key, queryResult, status, error_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
key = 'oracle_pool';
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.oracleConnection.query("\n SELECT \n 'ORACLEDB_POOL' as source,\n COUNT(*) as total_connections\n FROM \n V$SESSION \n WHERE \n TYPE = 'USER' \n AND PROGRAM LIKE 'nodejs%'\n ")];
case 2:
queryResult = _b.sent();
status = {
isHealthy: true,
totalConnections: ((_a = queryResult === null || queryResult === void 0 ? void 0 : queryResult[0]) === null || _a === void 0 ? void 0 : _a.total_connections) || 0,
connectionClass: 'PORTALJURU'
};
return [2 /*return*/, this.getStatus(key, status.isHealthy, {
totalConnections: status.totalConnections,
connectionClass: status.connectionClass
})];
case 3:
error_1 = _b.sent();
// Em caso de erro, ainda retornar um status (não saudável)
return [2 /*return*/, this.getStatus(key, false, {
message: "Erro ao obter estat\u00EDsticas do pool Oracle: " + error_1.message
})];
case 4: return [2 /*return*/];
}
});
});
};
DbPoolStatsIndicator.prototype.checkPostgresPoolStats = function () {
var _a, _b, _c;
return __awaiter(this, void 0, Promise, function () {
var key, queryResult, status, error_2;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
key = 'postgres_pool';
_d.label = 1;
case 1:
_d.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.postgresConnection.query("\n SELECT \n count(*) as total_connections,\n sum(CASE WHEN state = 'active' THEN 1 ELSE 0 END) as active_connections,\n sum(CASE WHEN state = 'idle' THEN 1 ELSE 0 END) as idle_connections\n FROM \n pg_stat_activity \n WHERE \n datname = current_database()\n AND application_name LIKE 'nodejs%'\n ")];
case 2:
queryResult = _d.sent();
status = {
isHealthy: true,
totalConnections: parseInt((_a = queryResult === null || queryResult === void 0 ? void 0 : queryResult[0]) === null || _a === void 0 ? void 0 : _a.total_connections) || 0,
activeConnections: parseInt((_b = queryResult === null || queryResult === void 0 ? void 0 : queryResult[0]) === null || _b === void 0 ? void 0 : _b.active_connections) || 0,
idleConnections: parseInt((_c = queryResult === null || queryResult === void 0 ? void 0 : queryResult[0]) === null || _c === void 0 ? void 0 : _c.idle_connections) || 0
};
return [2 /*return*/, this.getStatus(key, status.isHealthy, {
totalConnections: status.totalConnections,
activeConnections: status.activeConnections,
idleConnections: status.idleConnections
})];
case 3:
error_2 = _d.sent();
// Em caso de erro, ainda retornar um status (não saudável)
return [2 /*return*/, this.getStatus(key, false, {
message: "Erro ao obter estat\u00EDsticas do pool PostgreSQL: " + error_2.message
})];
case 4: return [2 /*return*/];
}
});
});
};
DbPoolStatsIndicator = __decorate([
common_1.Injectable(),
__param(0, typeorm_1.InjectConnection('oracle')),
__param(1, typeorm_1.InjectConnection('postgres'))
], DbPoolStatsIndicator);
return DbPoolStatsIndicator;
}(terminus_1.HealthIndicator));
exports.DbPoolStatsIndicator = DbPoolStatsIndicator;

View File

@@ -1,122 +0,0 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
exports.__esModule = true;
exports.TypeOrmHealthIndicator = void 0;
var common_1 = require("@nestjs/common");
var terminus_1 = require("@nestjs/terminus");
var typeorm_1 = require("@nestjs/typeorm");
var TypeOrmHealthIndicator = /** @class */ (function (_super) {
__extends(TypeOrmHealthIndicator, _super);
function TypeOrmHealthIndicator(oracleConnection, postgresConnection) {
var _this = _super.call(this) || this;
_this.oracleConnection = oracleConnection;
_this.postgresConnection = postgresConnection;
return _this;
}
TypeOrmHealthIndicator.prototype.checkOracle = function () {
return __awaiter(this, void 0, Promise, function () {
var key, isHealthy, result, result;
return __generator(this, function (_a) {
key = 'oracle';
try {
isHealthy = this.oracleConnection.isInitialized;
result = this.getStatus(key, isHealthy);
if (isHealthy) {
return [2 /*return*/, result];
}
throw new terminus_1.HealthCheckError('Oracle healthcheck failed', result);
}
catch (error) {
result = this.getStatus(key, false, { message: error.message });
throw new terminus_1.HealthCheckError('Oracle healthcheck failed', result);
}
return [2 /*return*/];
});
});
};
TypeOrmHealthIndicator.prototype.checkPostgres = function () {
return __awaiter(this, void 0, Promise, function () {
var key, isHealthy, result, result;
return __generator(this, function (_a) {
key = 'postgres';
try {
isHealthy = this.postgresConnection.isInitialized;
result = this.getStatus(key, isHealthy);
if (isHealthy) {
return [2 /*return*/, result];
}
throw new terminus_1.HealthCheckError('Postgres healthcheck failed', result);
}
catch (error) {
result = this.getStatus(key, false, { message: error.message });
throw new terminus_1.HealthCheckError('Postgres healthcheck failed', result);
}
return [2 /*return*/];
});
});
};
TypeOrmHealthIndicator = __decorate([
common_1.Injectable(),
__param(0, typeorm_1.InjectConnection('oracle')),
__param(1, typeorm_1.InjectConnection('postgres'))
], TypeOrmHealthIndicator);
return TypeOrmHealthIndicator;
}(terminus_1.HealthIndicator));
exports.TypeOrmHealthIndicator = TypeOrmHealthIndicator;

View File

@@ -0,0 +1,93 @@
import { Injectable } from '@nestjs/common';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import { Counter, Gauge, Histogram } from 'prom-client';
import { InjectConnection } from '@nestjs/typeorm';
import { DataSource } from 'typeorm';
@Injectable()
export class CustomMetricsService {
constructor(
@InjectMetric('http_request_total')
private readonly requestCounter: Counter<string>,
@InjectMetric('http_request_duration_seconds')
private readonly requestDuration: Histogram<string>,
@InjectMetric('api_memory_usage_bytes')
private readonly memoryGauge: Gauge<string>,
@InjectMetric('api_db_connection_pool_used')
private readonly dbPoolUsedGauge: Gauge<string>,
@InjectMetric('api_db_connection_pool_total')
private readonly dbPoolTotalGauge: Gauge<string>,
@InjectMetric('api_db_query_duration_seconds')
private readonly dbQueryDuration: Histogram<string>,
@InjectConnection('oracle')
private oracleConnection: DataSource,
@InjectConnection('postgres')
private postgresConnection: DataSource,
) {
// Iniciar coleta de métricas de memória
this.startMemoryMetrics();
// Iniciar coleta de métricas do pool de conexões
this.startDbPoolMetrics();
}
recordHttpRequest(method: string, route: string, statusCode: number): void {
this.requestCounter.inc({ method, route, statusCode: statusCode.toString() });
}
startTimingRequest(): (labels?: Record<string, string>) => void {
const end = this.requestDuration.startTimer();
return (labels?: Record<string, string>) => end(labels);
}
recordDbQueryDuration(db: 'oracle' | 'postgres', operation: string, durationMs: number): void {
this.dbQueryDuration.observe({ db, operation }, durationMs / 1000);
}
private startMemoryMetrics(): void {
// Coletar métricas de memória a cada 15 segundos
setInterval(() => {
const memoryUsage = process.memoryUsage();
this.memoryGauge.set({ type: 'rss' }, memoryUsage.rss);
this.memoryGauge.set({ type: 'heapTotal' }, memoryUsage.heapTotal);
this.memoryGauge.set({ type: 'heapUsed' }, memoryUsage.heapUsed);
this.memoryGauge.set({ type: 'external' }, memoryUsage.external);
}, 15000);
}
private startDbPoolMetrics(): void {
// Coletar métricas do pool de conexões a cada 15 segundos
setInterval(async () => {
try {
// Tente obter estatísticas do pool do Oracle
// Nota: depende da implementação específica do OracleDB
if (this.oracleConnection && this.oracleConnection.driver) {
const oraclePoolStats = (this.oracleConnection.driver as any).pool?.getStatistics?.();
if (oraclePoolStats) {
this.dbPoolUsedGauge.set({ db: 'oracle' }, oraclePoolStats.busy || 0);
this.dbPoolTotalGauge.set({ db: 'oracle' }, oraclePoolStats.poolMax || 0);
}
}
// Tente obter estatísticas do pool do Postgres
// Nota: depende da implementação específica do TypeORM
if (this.postgresConnection && this.postgresConnection.driver) {
const pgPoolStats = (this.postgresConnection.driver as any).pool;
if (pgPoolStats) {
this.dbPoolUsedGauge.set({ db: 'postgres' }, pgPoolStats.totalCount - pgPoolStats.idleCount || 0);
this.dbPoolTotalGauge.set({ db: 'postgres' }, pgPoolStats.totalCount || 0);
}
}
} catch (error) {
console.error('Erro ao coletar métricas do pool de conexões:', error);
}
}, 15000);
}
}

View File

@@ -0,0 +1,51 @@
import {
makeCounterProvider,
makeGaugeProvider,
makeHistogramProvider
} from '@willsoto/nestjs-prometheus';
export const metricProviders = [
// Contador de requisições HTTP
makeCounterProvider({
name: 'http_request_total',
help: 'Total de requisições HTTP',
labelNames: ['method', 'route', 'statusCode'],
}),
// Histograma de duração de requisições HTTP
makeHistogramProvider({
name: 'http_request_duration_seconds',
help: 'Duração das requisições HTTP em segundos',
labelNames: ['method', 'route', 'error'], // 👈 adicionado "error"
buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10],
}),
// Gauge para uso de memória
makeGaugeProvider({
name: 'api_memory_usage_bytes',
help: 'Uso de memória da aplicação em bytes',
labelNames: ['type'],
}),
// Gauge para conexões de banco de dados usadas
makeGaugeProvider({
name: 'api_db_connection_pool_used',
help: 'Número de conexões de banco de dados em uso',
labelNames: ['db'],
}),
// Gauge para total de conexões no pool de banco de dados
makeGaugeProvider({
name: 'api_db_connection_pool_total',
help: 'Número total de conexões no pool de banco de dados',
labelNames: ['db'],
}),
// Histograma para duração de consultas de banco de dados
makeHistogramProvider({
name: 'api_db_query_duration_seconds',
help: 'Duração das consultas de banco de dados em segundos',
labelNames: ['db', 'operation'],
buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2],
}),
];

View File

@@ -0,0 +1,64 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CustomMetricsService } from './custom.metrics';
@Injectable()
export class MetricsInterceptor implements NestInterceptor {
constructor(private metricsService: CustomMetricsService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
if (context.getType() !== 'http') {
return next.handle();
}
const request = context.switchToHttp().getRequest();
const { method, url } = request;
// Simplificar a rota para evitar cardinalidade alta no Prometheus
// Ex: /users/123 -> /users/:id
const route = this.normalizeRoute(url);
// Inicia o timer para medir a duração da requisição
const endTimer = this.metricsService.startTimingRequest();
return next.handle().pipe(
tap({
next: (data) => {
const response = context.switchToHttp().getResponse();
const statusCode = response.statusCode;
// Registra a requisição concluída
this.metricsService.recordHttpRequest(method, route, statusCode);
// Finaliza o timer com labels adicionais
endTimer({ method, route });
},
error: (error) => {
// Determina o código de status do erro
const statusCode = error.status || 500;
// Registra a requisição com erro
this.metricsService.recordHttpRequest(method, route, statusCode);
// Finaliza o timer com labels adicionais
endTimer({ method, route, error: 'true' });
}
})
);
}
private normalizeRoute(url: string): string {
// Remove query parameters
const path = url.split('?')[0];
// Normaliza rotas com IDs e outros parâmetros dinâmicos
// Por exemplo, /users/123 -> /users/:id
return path.replace(/\/[0-9a-f]{8,}|\/[0-9]+/g, '/:id');
}
}