import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; import { emitLatency, emitRequestCount, emitError } from '@shieldai/monitoring'; const SERVICE_NAME = process.env.DD_SERVICE || 'shieldai-api'; export async function monitoringMiddleware(fastify: FastifyInstance) { fastify.addHook('onResponse', async (request: FastifyRequest, reply: FastifyReply) => { const statusCode = reply.statusCode; const responseTime = reply.elapsedTime; const method = request.method; const url = request.url; // Emit request count await emitRequestCount(SERVICE_NAME, statusCode); // Emit latency metrics await emitLatency(SERVICE_NAME, responseTime, 'p50'); await emitLatency(SERVICE_NAME, responseTime, 'p95'); await emitLatency(SERVICE_NAME, responseTime, 'p99'); // Emit error metric for 5xx if (statusCode >= 500) { await emitError(SERVICE_NAME, 'server_error'); fastify.log.warn({ event: 'high_latency_or_error', method, url, statusCode, responseTime, service: SERVICE_NAME, }); } // Log high latency requests (>2s) if (responseTime > 2000) { fastify.log.warn({ event: 'high_latency', method, url, statusCode, responseTime, service: SERVICE_NAME, }); } }); }