🚨 Sistema de Alertas
Sistema automático de monitorização e alertas para detectar falhas críticas nos serviços Audissey.
📋 Visão Geral
Monitora continuamente a disponibilidade de:
- API (port 3000)
- Worker (port 3001)
- ML Service (se configurado)
Envia alertas por email quando:
- Serviço fica indisponível (down)
- Serviço volta online (recovered)
⚙️ Configuração
Variáveis de Ambiente
# Destinatários de alertas (opcional - padrão: tiago.costa@audissey.io, ptiago07@gmail.com)
ALERT_RECIPIENTS=admin@example.com,ops@example.com
# URLs customizadas (opcional - detecta automaticamente por NODE_ENV)
API_URL=https://audissey-api-staging.azurewebsites.net
WORKER_URL=https://audissey-worker-staging.azurewebsites.net
ML_SERVICE_URL=https://audissey-ml-staging.azurewebsites.net
Ambiente (NODE_ENV) - URLs Padrão
Development
API: http://localhost:3000
Worker: http://localhost:3001
ML: (se ML_SERVICE_URL definida)
Staging
API: https://audissey-api-staging.azurewebsites.net
Worker: https://audissey-worker-staging.azurewebsites.net
ML: (se ML_SERVICE_URL definida)
Production
API: https://audissey-api.azurewebsites.net
Worker: https://audissey-worker.azurewebsites.net
ML: (se ML_SERVICE_URL definida)
Destinatários Padrão
Se ALERT_RECIPIENTS não for definida, os alertas serão enviados para:
tiago.costa@audissey.ioptiago07@gmail.com
🔍 Endpoints
GET /api/alerts/status
Retorna o status atual de todos os serviços monitorados.
Response (200 OK):
{
"services": [
{
"name": "API",
"url": "http://localhost:3000/health",
"status": "up",
"lastCheck": "2025-12-31T14:30:00.000Z"
},
{
"name": "Worker",
"url": "http://localhost:3001/health",
"status": "up",
"lastCheck": "2025-12-31T14:30:00.000Z"
}
],
"allHealthy": true,
"timestamp": "2025-12-31T14:30:00.000Z"
}
GET /api/alerts/check/:service
Verifica a saúde de um serviço específico.
Parâmetros:
:service- api, worker
Response (200 OK):
{
"name": "API",
"url": "http://localhost:3000/health",
"status": "up",
"lastCheck": "2025-12-31T14:30:00.000Z"
}
📊 Fluxo de Monitoramento
┌─────────────────────────────────────┐
│ AlertsScheduler (CRON: a cada 5min) │
└────────────┬────────────────────────┘
│
├──> checkAllServices()
│
├──> checkService(API)
├──> checkService(Worker)
└──> checkService(ML)
│
├──> Compare com status anterior
│
├──> Status mudou?
│ ├──> SIM: onStatusChanged()
│ │ ├──> sendAlert()
│ │ ├──> sendEmailAlert()
│ │ └──> trackEvent(App Insights)
│ │
│ └──> NÃO: continue
│
└──> getServiceStatuses() (cache)
🔔 Exemplos de Alertas
Serviço Down
Subject: 🚨 ALERT: API is DOWN
Body:
Service: API
Status: DOWN
Time: 2025-12-31T14:30:00.000Z
Error: ECONNREFUSED: Connection refused
Please check the service immediately.
Serviço Recovered
Subject: ✅ RECOVERED: API is back UP
Body:
Service: API
Status: UP
Time: 2025-12-31T14:35:00.000Z
Please check the service immediately.
📧 Integração com Email
Sender (implementado)
O envio está implementado em alerts.service.ts (sendViaSender) através do cliente partilhado sendTransactionalEmail (worker-shared/src/services/sender-email.client.ts). Configuração e verificação: Email com Sender.
Alternativas
- Mailgun:
npm install mailgun.js - AWS SES:
npm install @aws-sdk/client-ses - Azure Communication Services:
npm install @azure/communication-email
🔐 Segurança
- ✅ URLs de serviços não expostas em logs públicos
- ✅ Timeout de 5 segundos para evitar travamento
- ✅ Erros são redactados em logs de produção
- ✅ Alertas são rastreados em Application Insights
- ✅ Destinatários de alerta validados
📈 Métricas e Observabilidade
Todos os eventos de alerta são enviados para Application Insights:
ServiceDown- evento quando serviço fica indisponívelServiceRecovered- evento quando serviço volta online
Query KQL:
customEvents
| where name in ("ServiceDown", "ServiceRecovered")
| order by timestamp desc
| project timestamp, name, service=tostring(customDimensions.service), error=tostring(customDimensions.error)
🧪 Testes
# Testar endpoint de status
curl http://localhost:3000/api/alerts/status
# Testar verificação de serviço específico
curl http://localhost:3000/api/alerts/check/api
curl http://localhost:3000/api/alerts/check/worker
📧 Email Configuration (Sender)
The alerts system uses Sender (https://www.sender.net) for sending email notifications.
Setup
- Create an API token in the Sender dashboard (the
audissey.iodomain must be verified there). - Set environment variables:
SENDER_API_TOKEN=<token from the Sender dashboard>
ALERT_FROM_EMAIL=alerts@audissey.io
ALERT_RECIPIENTS=tiago.costa@audissey.io,ptiago07@gmail.com
For Azure Deployment
SENDER_API_TOKEN is a secret in the Azure DevOps Variable Groups (audissey-dev, audissey-staging, audissey-prod); ALERT_FROM_EMAIL and ALERT_RECIPIENTS are non-secret VG variables. The release pipelines apply them to the Container Apps via deploy/config/appsettings/{api,worker}/<env>.json. See Email com Sender.
Email Format
Service Down - Red theme with 🚨 emoji
Subject: 🚨 ALERT: Worker is DOWN
Body: HTML formatted with error details
Service Recovered - Green theme with ✅ emoji
Subject: ✅ RECOVERED: Worker is back UP
Body: HTML formatted confirmation
Configuration Reference
| Variable | Required | Default |
|---|---|---|
SENDER_API_TOKEN |
Yes | None |
ALERT_FROM_EMAIL |
No | alerts@audissey.io |
ALERT_RECIPIENTS |
No | tiago.costa@audissey.io,ptiago07@gmail.com |
Implementation Details
- ✅ Non-blocking async email sending
- ✅ Per-recipient error logging (status + message, never the token); no automatic retries
- ✅ Sender
emailIdlogged per recipient - ✅ HTML email formatting with color coding
- ✅ Graceful degradation if
SENDER_API_TOKENis not configured - ✅ Support for multiple recipients (Sender takes one
toper request, so one request per recipient)
Full setup guide: Email com Sender
📋 TODO
- Implementar integração Sender (substitui SendGrid)
- Dashboard de alertas no portal de docs
- Notificações via Slack
- Histórico de alertas em MongoDB
- Escalation policy (reenviar após X minutos se ainda down)
- Testes de carga
- Webhooks customizados
🚀 Próximos Passos
- Configurar Sender: Setup Guide
- Testar localmente:
npm run start:api+ trigger alerts - Deploy em staging e testar
- Monitorar em Application Insights