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