80 lines
3.3 KiB
Python
80 lines
3.3 KiB
Python
"""规则级通知门禁。
|
||
|
||
两条规则(按 message_notifications 行存储):
|
||
|
||
1. **通知间隔**(interval_minutes,1~1440 分钟):
|
||
同一规则两次通知尝试之间至少间隔 N 分钟,间隔期内的事件直接静默。
|
||
与实例级的同类型冷却(如 Token 异常 3 小时)叠加生效——实际间隔取两者中更长的。
|
||
2. **失败 N 次才通知**(fail_threshold,1=每次都通知):
|
||
仅对失败/异常类事件计数;同一规则同一事件连续触发到第 N 次才放行一次,
|
||
放行后计数清零重新累计。成功类、消息类事件不计数、不受影响。
|
||
|
||
状态保存在内存,进程重启后计数与间隔记录清零(重启后首条通知不受旧间隔约束)。
|
||
"""
|
||
|
||
import logging
|
||
import threading
|
||
import time
|
||
from typing import Any, Dict, Optional
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
class NotificationGate:
|
||
def __init__(self) -> None:
|
||
self._lock = threading.Lock()
|
||
self._last_sent: Dict[int, float] = {} # rule_id -> 上次放行时间戳
|
||
self._fail_count: Dict[tuple, int] = {} # (rule_id, event_type) -> 连续失败计数
|
||
|
||
def allow(self, rule: Dict[str, Any], event_type: Optional[str] = None) -> bool:
|
||
"""判断这条规则此刻是否应该发送。
|
||
|
||
通过即记为一次「通知尝试」并推进间隔计时——间隔语义是两次尝试之间的最小间隔。
|
||
"""
|
||
try:
|
||
rule_id = rule.get("id")
|
||
if not rule_id:
|
||
return True
|
||
|
||
interval = int(rule.get("interval_minutes") or 1)
|
||
threshold = int(rule.get("fail_threshold") or 1)
|
||
if interval < 1:
|
||
interval = 1
|
||
if threshold < 1:
|
||
threshold = 1
|
||
|
||
from app.notification_events import is_failure_event
|
||
|
||
failure_key = (rule_id, event_type) if is_failure_event(event_type) else None
|
||
|
||
with self._lock:
|
||
now = time.time()
|
||
|
||
# 连续失败计数(仅失败类事件、且阈值 > 1 时生效)
|
||
if failure_key is not None and threshold > 1:
|
||
count = self._fail_count.get(failure_key, 0)
|
||
if count < threshold:
|
||
count += 1
|
||
self._fail_count[failure_key] = count
|
||
if count < threshold:
|
||
# 还没到 N 次:静默,且不推进间隔计时
|
||
return False
|
||
# 已到阈值:继续走间隔检查;若被间隔挡住,计数保留,
|
||
# 间隔一过或下次失败即可放行(第 N 次失败不应被无限顺延丢失)。
|
||
|
||
# 通知间隔
|
||
last = self._last_sent.get(rule_id)
|
||
if last is not None and (now - last) < interval * 60:
|
||
return False
|
||
|
||
if failure_key is not None:
|
||
self._fail_count.pop(failure_key, None)
|
||
self._last_sent[rule_id] = now
|
||
return True
|
||
except Exception as e: # 门禁故障绝不能挡住正常通知
|
||
logger.error(f"通知门禁判断失败(放行): {e}")
|
||
return True
|
||
|
||
|
||
notification_gate = NotificationGate()
|