from __future__ import annotations import time from typing import Any class SentMessageCache: MAX_ENTRIES = 1024 TTL_SECONDS = 600 def __init__(self) -> None: self._cache: dict[str, dict[str, Any]] = {} def track(self, message_id: str, chat_guid: str, metadata: dict[str, Any] | None = None) -> None: self._cache[message_id] = { "chat_guid": chat_guid, "metadata": metadata or {}, "sent_at": time.monotonic(), } self._trim() def lookup(self, message_id: str) -> dict[str, Any] | None: entry = self._cache.get(message_id) if entry is None: return None if time.monotonic() - entry["sent_at"] > self.TTL_SECONDS: del self._cache[message_id] return None return entry def remove(self, message_id: str) -> None: self._cache.pop(message_id, None) def _trim(self) -> None: if len(self._cache) > self.MAX_ENTRIES: now = time.monotonic() expired = [k for k, v in self._cache.items() if now - v["sent_at"] > self.TTL_SECONDS] for k in expired: del self._cache[k] if len(self._cache) > self.MAX_ENTRIES: oldest = sorted(self._cache.items(), key=lambda x: x[1]["sent_at"])[ : len(self._cache) - self.MAX_ENTRIES ] for k, _ in oldest: del self._cache[k]