Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
8b8cc24
v2.0.0-beta: 10 autonomous cron workflows + CTO self-merge
germanf Jul 3, 2026
aef15a8
v2.1.0-beta: Phase B — Memory & Self-Improvement (#121)
germanf Jul 3, 2026
8d5bb68
5.3.c — Health check expansion: memory, CPU, backup, MCP, backends
Jul 7, 2026
2843b80
Merge pull request #123 from germanf/feature/health-check-expansion
germanf Jul 7, 2026
21e4d48
5.3.a — Alerting system: webhook channel, REST API, health integratio…
Jul 7, 2026
23f8981
Merge pull request #126 from germanf/feature/alerting-system
germanf Jul 7, 2026
6696218
5.4.a — Real-time SSE Jobs Page: job list + live log viewer with Even…
Jul 7, 2026
6932311
Merge pull request #127 from germanf/feature/realtime-jobs
germanf Jul 7, 2026
8224879
5.1.a — Map-Reduce in Orchestrator: backend factory + endpoint, front…
Jul 7, 2026
7cc90f1
fix: parallelism validation, empty input guard, chunk denominator
Jul 7, 2026
f423b15
Merge pull request #128 from germanf/feature/map-reduce
germanf Jul 9, 2026
06efd24
5.4.b — Alert UI in Dashboard: Active Alerts widget with polling + ac…
Jul 9, 2026
d71689b
fix: ack error handling, consistent polling, remove unused CSS
Jul 9, 2026
7a7abd6
Merge pull request #129 from germanf/feature/alert-ui
germanf Jul 10, 2026
f0124a1
5.3.b — Prometheus metrics endpoint at /metrics with health_check gauge
Jul 10, 2026
7568ebb
Merge pull request #130 from germanf/feature/prometheus-metrics
germanf Jul 10, 2026
cc46e89
5.4.c — Health Timeline: degraded/unavailable lines, summary bar
Jul 10, 2026
35201ea
Merge pull request #131 from germanf/feature/health-timeline
germanf Jul 11, 2026
4333d4e
5.3.d — Backup Integrity Verification: PRAGMA integrity_check on all …
Jul 11, 2026
590c0f1
Merge pull request #132 from germanf/feature/backup-integrity
germanf Oct 28, 2026
c2555db
Merge branch 'main' into dev
germanf Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
5.3.a — Alerting system: webhook channel, REST API, health integratio…
…n, configurable thresholds
  • Loading branch information
KyoX
KyoX committed Jul 7, 2026
commit 21e4d480822a0603bd848bedde6285c38fa613a8
44 changes: 40 additions & 4 deletions dashboard/alerts.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import uuid
from collections import deque
from dataclasses import dataclass, field
from datetime import UTC, datetime

import httpx
from loguru import logger

from dashboard.config import ALERT_WEBHOOK_URL


@dataclass
class Alert:
Expand All @@ -19,8 +23,8 @@ class Alert:

class AlertManager:
def __init__(self, max_alerts: int = 1000):
self._alerts: list[Alert] = []
self._max_alerts = max_alerts
self._alerts: deque[Alert] = deque(maxlen=max_alerts)
self._suppressed: dict[str, float] = {} # component -> last alert time for rate limiting

def emit(self, component: str, severity: str, message: str, details: dict | None = None) -> Alert:
alert = Alert(
Expand All @@ -33,10 +37,32 @@ def emit(self, component: str, severity: str, message: str, details: dict | None
self._alerts.append(alert)
log_fn = logger.critical if severity == "critical" else logger.warning if severity == "warning" else logger.info
log_fn("[{}] {}: {} — {}", severity.upper(), component, message, details or "")
if len(self._alerts) > self._max_alerts:
self._alerts.pop(0)
if ALERT_WEBHOOK_URL:
try:
import asyncio
asyncio.create_task(self._dispatch_webhook(alert))
except RuntimeError:
pass # no event loop in this thread
return alert

async def _dispatch_webhook(self, alert: Alert) -> None:
if not ALERT_WEBHOOK_URL:
return
try:
async with httpx.AsyncClient(timeout=10) as client:
await client.post(ALERT_WEBHOOK_URL, json={
"event": "alert",
"id": alert.id,
"component": alert.component,
"severity": alert.severity,
"message": alert.message,
"details": alert.details,
"created_at": alert.created_at.isoformat(),
})
logger.debug("Webhook dispatched for alert {}", alert.id)
except Exception as e:
logger.warning("Webhook dispatch failed: {}", e)

def list(self, severity: str | None = None, component: str | None = None, limit: int = 50) -> list[Alert]:
result = list(self._alerts)
if severity:
Expand All @@ -62,5 +88,15 @@ def acknowledge_all(self, component: str | None = None, by: str = "system") -> i
count += 1
return count

def rate_limited(self, component: str, interval: float = 300.0) -> bool:
"""Return True if an alert for this component was emitted within `interval` seconds."""
import time
now = time.time()
last = self._suppressed.get(component)
if last is not None and now - last < interval:
return True
self._suppressed[component] = now
return False


alerts = AlertManager()
4 changes: 4 additions & 0 deletions dashboard/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@
UPLOADS_DIR = BASE_DIR / "data" / "uploads"
_vault = os.environ.get("VAULT_DIR")
VAULT_DIR = Path(_vault) if _vault else None

# ── Alerting ───────────────────────────────────────────────────────────────
ALERT_WEBHOOK_URL: str | None = os.environ.get("ALERT_WEBHOOK_URL")
ALERT_HEALTH_DEGRADED_INTERVAL: int = int(os.environ.get("ALERT_HEALTH_DEGRADED_INTERVAL", "300"))
16 changes: 16 additions & 0 deletions dashboard/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

from loguru import logger

from dashboard.config import ALERT_HEALTH_DEGRADED_INTERVAL


@dataclass
class HealthComponent:
Expand Down Expand Up @@ -57,6 +59,20 @@ async def run_all(self) -> list[HealthComponent]:
overall=overall,
components=[c.__dict__ for c in results],
))
# Auto-alert on degraded/unavailable (rate-limited per component)
try:
from dashboard.alerts import alerts
for c in results:
if c.status in ("degraded", "unavailable"):
if not alerts.rate_limited(c.name, ALERT_HEALTH_DEGRADED_INTERVAL):
alerts.emit(
component=f"health.{c.name}",
severity="warning" if c.status == "degraded" else "critical",
message=f"Health check {c.name} is {c.status}",
details=c.details,
)
except Exception:
pass # alert emission failures should not break health checks
return results

async def run(self, name: str) -> HealthComponent | None:
Expand Down
33 changes: 21 additions & 12 deletions dashboard/routes/alerts.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,17 @@
from dashboard.alerts import alerts
from dashboard.rate_limit import limiter

router = APIRouter(prefix="/api", tags=["alerts"])
router = APIRouter(prefix="/api/alerts", tags=["alerts"])


@router.get("/alerts")
@router.get("")
@limiter.limit("30/minute")
async def list_alerts(request: Request, severity: str | None = None, component: str | None = None, limit: int = 50):
async def list_alerts(
request: Request,
severity: str | None = None,
component: str | None = None,
limit: int = 50,
):
return JSONResponse([
{
"id": a.id,
Expand All @@ -25,16 +30,20 @@ async def list_alerts(request: Request, severity: str | None = None, component:
])


@router.post("/alerts/{alert_id}/acknowledge")
@router.post("/{alert_id}/acknowledge")
@limiter.limit("30/minute")
async def acknowledge_alert(request: Request, alert_id: str):
if alerts.acknowledge(alert_id):
return JSONResponse({"status": "acknowledged"})
return JSONResponse({"status": "not_found"}, status_code=404)
async def acknowledge_alert(request: Request, alert_id: str, body: dict | None = None):
by = (body or {}).get("by", "ui")
ok = alerts.acknowledge(alert_id, by=by)
if not ok:
return JSONResponse({"error": "Alert not found"}, status_code=404)
return JSONResponse({"status": "acknowledged"})


@router.post("/alerts/acknowledge-all")
@router.post("/acknowledge-all")
@limiter.limit("10/minute")
async def acknowledge_all(request: Request, component: str | None = None):
count = alerts.acknowledge_all(component=component)
return JSONResponse({"status": "acknowledged", "count": count})
async def acknowledge_all(request: Request, body: dict | None = None):
component = (body or {}).get("component")
by = (body or {}).get("by", "ui")
count = alerts.acknowledge_all(component=component, by=by)
return JSONResponse({"acknowledged": count})