chore(): small improvements

This commit is contained in:
ITQ
2026-02-23 23:29:03 +03:00
parent 85bed92364
commit ffd887dc39
11 changed files with 197 additions and 20 deletions
+25 -6
View File
@@ -82,11 +82,15 @@ def rule_create(
event_type: str,
channel: NotificationChannel,
experiment: Any | None = None,
rate_limit_window_seconds: int = 60,
rate_limit_max_notifications: int = 1,
) -> NotificationRule:
rule = NotificationRule(
event_type=event_type,
channel=channel,
experiment=experiment,
rate_limit_window_seconds=rate_limit_window_seconds,
rate_limit_max_notifications=rate_limit_max_notifications,
)
rule.save()
return rule
@@ -97,7 +101,12 @@ def rule_update(
rule: NotificationRule,
**fields: Any,
) -> NotificationRule:
allowed = {"event_type", "is_active"}
allowed = {
"event_type",
"is_active",
"rate_limit_window_seconds",
"rate_limit_max_notifications",
}
for key in fields:
if key not in allowed:
raise ValueError(f"Field '{key}' cannot be updated.")
@@ -149,12 +158,17 @@ def notification_enqueue(
logs: list[NotificationLog] = []
for rule in rules:
event_key = _build_event_key(event_type, payload)
if NotificationLog.objects.filter(
event_key = _build_event_key(
event_type,
payload,
rule.rate_limit_window_seconds,
)
sent_or_pending = NotificationLog.objects.filter(
event_key=event_key,
channel=rule.channel,
status__in=[NotificationStatus.PENDING, NotificationStatus.SENT],
).exists():
).count()
if sent_or_pending >= rule.rate_limit_max_notifications:
continue
log = NotificationLog.objects.create(
@@ -176,8 +190,13 @@ def notification_enqueue(
return logs
def _build_event_key(event_type: str, payload: NotificationPayload) -> str:
bucket = int(timezone.now().timestamp()) // 60
def _build_event_key(
event_type: str,
payload: NotificationPayload,
window_seconds: int,
) -> str:
normalized_window = max(window_seconds, 1)
bucket = int(timezone.now().timestamp()) // normalized_window
return f"{event_type}:{payload.experiment_id}:{bucket}"