🚨

Sistema de Alertas

🚨 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:

Envia alertas por email quando:

⚙️ 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:

🔍 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:

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

🔐 Segurança

📈 Métricas e Observabilidade

Todos os eventos de alerta são enviados para Application Insights:

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

  1. Create an API token in the Sender dashboard (the audissey.io domain must be verified there).
  2. 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

Full setup guide: Email com Sender

📋 TODO

🚀 Próximos Passos

  1. Configurar Sender: Setup Guide
  2. Testar localmente: npm run start:api + trigger alerts
  3. Deploy em staging e testar
  4. Monitorar em Application Insights