ForcePilot/backend/package/yuxi/channels/adapters/bluebubbles/reply_cache.py

39 lines
1.2 KiB
Python
Raw Normal View History

from __future__ import annotations
import time
class ReplyCache:
MAX_ENTRIES = 512
TTL_SECONDS = 600
def __init__(self) -> None:
self._cache: dict[tuple[str, str], tuple[str, float]] = {}
def resolve(self, chat_guid: str, short_id: str) -> str | None:
key = (chat_guid, short_id)
entry = self._cache.get(key)
if entry is None:
return None
uuid, ts = entry
if time.monotonic() - ts > self.TTL_SECONDS:
del self._cache[key]
return None
return uuid
def store(self, chat_guid: str, short_id: str, full_uuid: str) -> None:
key = (chat_guid, short_id)
self._cache[key] = (full_uuid, time.monotonic())
self._trim()
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[1] > 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][1])[: len(self._cache) - self.MAX_ENTRIES]
for k, _ in oldest:
del self._cache[k]