Microservicio de alertas para SEMS. Gestiona umbrales, reglas de inactividad, alertas y notificaciones (email/SMS), y consume solo eventos agrupados de energia y analytics por Kafka/Event Hubs.
Este servicio ahora prioriza configuracion desde un Config Service usando:
GET /api/v1/config/{service-name}GET /api/v1/config/services(fallback)GET /api/v1/config/kafka
Variable principal:
CONFIG_SERVICE_URL(ej. URL interna del Config Service)
Si el Config Service no devuelve valores, el servicio usa fallback local seguro dentro del esquema nuevo: consume energy.events y analytics.events, y publica alerts.events.
Mantener en .env solo variables sensibles o propias del despliegue:
PORT(recomendado para contenedores/Azure)SERVER_PORT(compatibilidad legacy local)SERVICE_NAMECONFIG_SERVICE_URLDATABASE_URLKAFKA_ENABLEDKAFKA_BROKERSKAFKA_CONSUMPTION_TOPICSKAFKA_ALERTS_TOPICALERT_DEFAULT_STATUSKAFKA_SECURITY_PROTOCOLKAFKA_SASL_MECHANISMKAFKA_USERNAMEKAFKA_PASSWORDKAFKA_SASL_USERNAMEKAFKA_SASL_PASSWORDGIN_MODETWILIO_ACCOUNT_SIDTWILIO_API_KEYTWILIO_API_SECRETTWILIO_PHONE_NUMBERMAIL_PORTMAIL_USERNAMEMAIL_PASSWORDMAIL_FROM
Opcional para desarrollo local sin Config Service:
KAFKA_ENABLED(truepara consumir/publicar;falsepara levantar solo HTTP)KAFKA_BROKERS(ej.kafka:9092en Docker local o Event Hubs en Azure)KAFKA_CONSUMER_GROUPKAFKA_CONSUMPTION_TOPICSKAFKA_ALERTS_TOPICALERT_DEFAULT_STATUS(por defectoopen; el micro normalizapendingyactiveaopen)KAFKA_TOPICS(topics a autocrear en Docker, separados por comas)MAIL_HOST
GET /api/v1/healthGET /api/v1/alertsGET /api/v1/alerts/:idGET /api/v1/users/:userId/alertsPOST /api/v1/alertsPATCH /api/v1/alerts/:id/statusPOST /api/v1/thresholdsGET /api/v1/users/:userId/thresholdsPOST /api/v1/inactivity-rulesGET /api/v1/users/:userId/inactivity-rulesPOST /api/v1/notification-preferencesGET /api/v1/users/:userId/notification-preferencesPOST /api/v1/kafka/publish-test(publica un evento de prueba en Kafka)POST /api/v1/diagnostics/validate(valida DB, Kafka/Event Hubs y variables clave)GET /swagger/index.html(UI para pruebas)
- Copia
.env.examplea.env. - Define credenciales reales (DB, Twilio, correo).
- Si no tienes Config Service, define tambien
KAFKA_ENABLED,KAFKA_BROKERSy opcionalmenteKAFKA_CONSUMER_GROUP/KAFKA_CONSUMPTION_TOPICS. - Ejecuta:
go mod tidy
go run main.goTopics agrupados usados por este microservicio:
- Consume
energy.events - Consume
analytics.events - Publica
alerts.events energy.consumption.recorded,analytics.anomaly.detected,analytics.recommendation.generatedyalert.createdsoneventType, no topics fisicos.
Envelope estandar de salida:
eventTypeeventIdoccurredAtdata
El proyecto incluye docker-compose.yml con PostgreSQL y Kafka locales:
docker compose up --buildAl levantar Docker Compose, el servicio kafka-topics-init espera a Kafka y crea automaticamente los topics definidos en KAFKA_TOPICS.
API local:
http://localhost:8085
Swagger local:
http://localhost:8085/swagger/index.html
Build:
docker build -t sems-alert-service:latest .Run (ejemplo local):
docker run --rm -p 8080:8080 ^
-e PORT=8080 ^
-e GIN_MODE=release ^
-e CONFIG_SERVICE_URL=https://config-service.internal ^
-e KAFKA_BROKERS=kafka:9092 ^
-e DATABASE_URL="postgres://USER:PASSWORD@HOST:5432/DB_NAME?sslmode=disable" ^
sems-alert-service:latestPara Azure Container Apps, configurar variables de entorno (sin localhost):
PORT=8080SERVICE_NAME=alert-serviceGIN_MODE=releaseCONFIG_SERVICE_URL(URL interna/privada del Config Service)KAFKA_ENABLED=trueKAFKA_BROKERS(broker privado, ej.broker:9092)KAFKA_CONSUMPTION_TOPICS=energy.events,analytics.eventsKAFKA_ALERTS_TOPIC=alerts.eventsALERT_DEFAULT_STATUS=openKAFKA_SECURITY_PROTOCOLKAFKA_SASL_MECHANISMKAFKA_USERNAMEKAFKA_PASSWORDKAFKA_SASL_USERNAME=$ConnectionStringKAFKA_SASL_PASSWORD=<Event-Hubs-connection-string>DATABASE_URL
Ejemplo de creacion/actualizacion (referencial):
az containerapp update \
--name sems-alert-service \
--resource-group <RESOURCE_GROUP> \
--set-env-vars PORT=8080 GIN_MODE=release SERVICE_NAME=alert-service \
--set-env-vars CONFIG_SERVICE_URL=https://<config-service-interno> \
--set-env-vars KAFKA_BROKERS=<broker-privado>:9092 \
--set-env-vars KAFKA_CONSUMPTION_TOPICS=energy.events,analytics.events \
--set-env-vars KAFKA_ALERTS_TOPIC=alerts.events \
--set-env-vars KAFKA_SECURITY_PROTOCOL=SASL_SSL \
--set-env-vars KAFKA_SASL_MECHANISM=PLAIN \
--set-env-vars KAFKA_USERNAME=<kafka-username> \
--set-env-vars KAFKA_PASSWORD=<kafka-password> \
--set-env-vars DATABASE_URL=<database-url>- Guardar secretos en Azure Key Vault o secretos de ACA:
KAFKA_USERNAMEKAFKA_PASSWORDDATABASE_URLTWILIO_*MAIL_USERNAMEMAIL_PASSWORD
- Evitar hardcodear topics/brokers en la app; centralizarlos en Config Service.
- Exponer solo puertos necesarios y usar networking privado entre microservicios cuando sea posible.
- Las migraciones GORM se ejecutan al iniciar.
- El dominio mantiene independencia de frameworks e infraestructura (DDD).
- El consumidor Kafka se desactiva automaticamente si faltan brokers o topics.
Alertsopera solo conenergy.events,analytics.eventsyalerts.events.- Para Azure/Event Hubs debes tener creados los Event Hubs
energy.eventsyanalytics.events, porque el micro los consume. - El routing de consumo depende exclusivamente de
eventType. - Si un mensaje llega sin
eventType, el micro lo rechaza como invalido. alert.createdse publica solo comoeventTypedentro dealerts.events.- Soporte legacy desactivado en runtime:
KAFKA_CONSUMPTION_TOPIC,KAFKA_TOPIC_DEVICE_READING_CREATED,KAFKA_TOPIC_ALERT_CREATED,device.events,iam.events,payments.events,subscriptions.events,billing.eventsyalert.events.