Repository navigation
Expand file tree
/
Copy pathalert_manager.py
More file actions
89 lines (73 loc) · 2.7 KB
/
Copy pathalert_manager.py
File metadata and controls
89 lines (73 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""
alert_manager.py - Gestiona el ciclo de vida de las alertas y los re-envíos
"""
import threading
import time
from alert_detector import Alert
from config_store import load_config
def _get_resend_interval() -> int:
try:
cfg = load_config()
return int(cfg.get("resend_interval", 30))
except Exception:
return 30
class AlertManager:
"""
Mantiene el diccionario de alertas activas y lanza un thread de re-envío.
"""
def __init__(self, notifier):
self.notifier = notifier
self._active_alerts: dict[str, Alert] = {}
self._lock = threading.Lock()
self._running = False
self._thread = None
def start(self):
self._running = True
self._thread = threading.Thread(target=self._resend_loop, daemon=True)
self._thread.start()
def stop(self):
self._running = False
def add_alert(self, alert: Alert):
"""Añade una nueva alerta y la envía inmediatamente."""
with self._lock:
self._active_alerts[alert.id] = alert
self.notifier.send_alert(alert)
alert.send_count += 1
def acknowledge_all(self) -> int:
"""Confirma todas las alertas activas. Devuelve el número confirmado."""
with self._lock:
count = len(self._active_alerts)
self._active_alerts.clear()
return count
def acknowledge_by_id(self, alert_id: str) -> bool:
"""Confirma una alerta específica por ID."""
with self._lock:
if alert_id in self._active_alerts:
del self._active_alerts[alert_id]
return True
return False
def active_count(self) -> int:
with self._lock:
return len(self._active_alerts)
def get_active_summary(self) -> str:
with self._lock:
if not self._active_alerts:
return "No active alerts."
lines = [f"Active alerts ({len(self._active_alerts)}):"]
for a in self._active_alerts.values():
lines.append(f" [{a.id}] {a.category.value}: {a.text[:60]}...")
return "\n".join(lines)
def _resend_loop(self):
"""Thread background: re-envía alertas no confirmadas cada N segundos."""
while self._running:
interval = _get_resend_interval()
time.sleep(interval)
with self._lock:
pending = list(self._active_alerts.values())
if pending:
if len(pending) == 1:
self.notifier.send_alert(pending[0])
else:
self.notifier.send_resend_summary(pending)
for alert in pending:
alert.send_count += 1