from __future__ import annotations import time from collections import OrderedDict class TelegramDeduplicator: def __init__(self, max_size: int = 10000, ttl_seconds: int = 25560): self._cache: OrderedDict[str, float] = OrderedDict() self._max_size = max_size self._ttl_seconds = ttl_seconds def is_duplicate(self, key: str) -> bool: if not key: return False now = time.monotonic() self._evict_expired(now) if key in self._cache: return True self._cache[key] = now while len(self._cache) > self._max_size: self._cache.popitem(last=False) return False def mark_seen(self, key: str) -> None: if not key: return now = time.monotonic() self._evict_expired(now) self._cache[key] = now while len(self._cache) > self._max_size: self._cache.popitem(last=False) def reset(self) -> None: self._cache.clear() @property def ttl_seconds(self) -> int: return self._ttl_seconds @property def max_entries(self) -> int: return self._max_size def _evict_expired(self, now: float) -> None: expired = [k for k, v in self._cache.items() if now - v > self._ttl_seconds] for k in expired: del self._cache[k]