|
| 1 | +""" |
| 2 | +Notification deduplication with exponential backoff for Telegram alerts. |
| 3 | +""" |
| 4 | + |
| 5 | +import json |
| 6 | +import logging |
| 7 | +import os |
| 8 | +import time |
| 9 | + |
| 10 | +import redis.asyncio as redis |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | +REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379") |
| 15 | +KEY_PREFIX = "qa:notif" |
| 16 | +DEDUPE_TTL = 4 * 3600 # 4 hours in seconds |
| 17 | + |
| 18 | +BACKOFF_SCHEDULE = [0, 60, 300, 1800] # 1st=immediate, 2nd=60s, 3rd=5m, 4th=30m |
| 19 | +CIRCUIT_BREAK_THRESHOLD = 3 # skip after 3 consecutive misses |
| 20 | + |
| 21 | + |
| 22 | +class NotificationDedupe: |
| 23 | + """Per-user per-position deduplication with exponential backoff.""" |
| 24 | + |
| 25 | + def __init__(self, redis_url: str = REDIS_URL) -> None: |
| 26 | + self._redis_url = redis_url |
| 27 | + self._client: redis.Redis | None = None |
| 28 | + |
| 29 | + async def _get_client(self) -> redis.Redis: |
| 30 | + if self._client is None: |
| 31 | + self._client = redis.from_url(self._redis_url, decode_responses=True) |
| 32 | + return self._client |
| 33 | + |
| 34 | + def _key(self, telegram_id: str, position_id: str) -> str: |
| 35 | + return f"{KEY_PREFIX}:{telegram_id}:{position_id}" |
| 36 | + |
| 37 | + async def should_send(self, telegram_id: str, position_id: str) -> bool: |
| 38 | + """Return True if the notification should be sent (not deduped).""" |
| 39 | + try: |
| 40 | + client = await self._get_client() |
| 41 | + key = self._key(telegram_id, position_id) |
| 42 | + raw = await client.get(key) |
| 43 | + if raw is None: |
| 44 | + return True |
| 45 | + |
| 46 | + data = json.loads(raw) |
| 47 | + count = data.get("count", 0) |
| 48 | + last_ts = data.get("last_ts", 0) |
| 49 | + elapsed = time.time() - last_ts |
| 50 | + |
| 51 | + if count >= CIRCUIT_BREAK_THRESHOLD: |
| 52 | + idx = min(count - 1, len(BACKOFF_SCHEDULE) - 1) |
| 53 | + if elapsed < BACKOFF_SCHEDULE[idx]: |
| 54 | + logger.debug( |
| 55 | + "Dedupe: circuit-break for %s:%s (%d misses, %.0fs elapsed)", |
| 56 | + telegram_id, position_id, count, elapsed, |
| 57 | + ) |
| 58 | + return False |
| 59 | + |
| 60 | + idx = min(count, len(BACKOFF_SCHEDULE) - 1) |
| 61 | + if elapsed < BACKOFF_SCHEDULE[idx]: |
| 62 | + logger.debug( |
| 63 | + "Dedupe: skip for %s:%s (%d sends, %.0fs elapsed)", |
| 64 | + telegram_id, position_id, count, elapsed, |
| 65 | + ) |
| 66 | + return False |
| 67 | + |
| 68 | + return True |
| 69 | + |
| 70 | + except Exception as e: |
| 71 | + logger.error("Dedupe check failed, allowing send: %s", e) |
| 72 | + return True |
| 73 | + |
| 74 | + async def record_send(self, telegram_id: str, position_id: str) -> None: |
| 75 | + """Record that a notification was sent (increment count).""" |
| 76 | + try: |
| 77 | + client = await self._get_client() |
| 78 | + key = self._key(telegram_id, position_id) |
| 79 | + raw = await client.get(key) |
| 80 | + if raw is None: |
| 81 | + data = {"count": 1, "last_ts": time.time()} |
| 82 | + else: |
| 83 | + data = json.loads(raw) |
| 84 | + data["count"] = data.get("count", 0) + 1 |
| 85 | + data["last_ts"] = time.time() |
| 86 | + await client.set(key, json.dumps(data), ex=DEDUPE_TTL) |
| 87 | + except Exception as e: |
| 88 | + logger.error("Dedupe record_send failed: %s", e) |
| 89 | + |
| 90 | + async def record_success(self, telegram_id: str, position_id: str) -> None: |
| 91 | + """Record a successful send – reset count on success.""" |
| 92 | + try: |
| 93 | + client = await self._get_client() |
| 94 | + key = self._key(telegram_id, position_id) |
| 95 | + data = {"count": 0, "last_ts": time.time()} |
| 96 | + await client.set(key, json.dumps(data), ex=DEDUPE_TTL) |
| 97 | + except Exception as e: |
| 98 | + logger.error("Dedupe record_success failed: %s", e) |
| 99 | + |
| 100 | + async def record_failure(self, telegram_id: str, position_id: str) -> None: |
| 101 | + """Record a failed send (increment failure count).""" |
| 102 | + try: |
| 103 | + client = await self._get_client() |
| 104 | + key = self._key(telegram_id, position_id) |
| 105 | + raw = await client.get(key) |
| 106 | + if raw is None: |
| 107 | + data = {"count": 1, "last_ts": time.time()} |
| 108 | + else: |
| 109 | + data = json.loads(raw) |
| 110 | + data["count"] = data.get("count", 0) + 1 |
| 111 | + data["last_ts"] = time.time() |
| 112 | + await client.set(key, json.dumps(data), ex=DEDUPE_TTL) |
| 113 | + except Exception as e: |
| 114 | + logger.error("Dedupe record_failure failed: %s", e) |
0 commit comments