import hashlib import time from collections import OrderedDict class InboundDedupeStore: def __init__(self, max_entries: int = 2048, ttl_seconds: int = 300): self._store: OrderedDict[str, float] = OrderedDict() self.max_entries = max_entries self.ttl_seconds = ttl_seconds @staticmethod def _hash(guid: str, account_id: str) -> str: return hashlib.sha256(f"{account_id}:{guid}".encode()).hexdigest() def is_duplicate(self, guid: str, account_id: str) -> bool: key = self._hash(guid, account_id) now = time.time() self._evict_expired(now) if key in self._store: return True self._store[key] = now while len(self._store) > self.max_entries: self._store.popitem(last=False) return False def _evict_expired(self, now: float): deadline = now - self.ttl_seconds while self._store: _key, ts = next(iter(self._store.items())) if ts < deadline: self._store.popitem(last=False) else: break def clear(self): self._store.clear() def __len__(self) -> int: return len(self._store)