2026-05-12 00:48:57 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
2026-05-12 14:51:53 +08:00
|
|
|
import asyncio
|
2026-05-12 00:48:57 +08:00
|
|
|
import time
|
|
|
|
|
from collections import OrderedDict
|
|
|
|
|
|
|
|
|
|
DEFAULT_CACHE_TTL_S = 3600.0
|
|
|
|
|
DEFAULT_MAX_ENTRIES = 2048
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SentMessageCache:
|
|
|
|
|
def __init__(self, max_entries: int = DEFAULT_MAX_ENTRIES, ttl_s: float = DEFAULT_CACHE_TTL_S):
|
|
|
|
|
self._cache: OrderedDict[str, tuple[str, float]] = OrderedDict()
|
|
|
|
|
self._max_entries = max_entries
|
|
|
|
|
self._ttl = ttl_s
|
2026-05-12 14:51:53 +08:00
|
|
|
self._lock = asyncio.Lock()
|
|
|
|
|
|
|
|
|
|
async def put(self, key: str, thread_ts: str) -> None:
|
|
|
|
|
async with self._lock:
|
|
|
|
|
self._evict_expired_locked()
|
|
|
|
|
if key in self._cache:
|
|
|
|
|
self._cache.move_to_end(key)
|
|
|
|
|
elif len(self._cache) >= self._max_entries:
|
|
|
|
|
self._cache.popitem(last=False)
|
|
|
|
|
self._cache[key] = (thread_ts, time.monotonic())
|
|
|
|
|
|
|
|
|
|
async def get(self, key: str) -> str | None:
|
|
|
|
|
async with self._lock:
|
|
|
|
|
self._evict_expired_locked()
|
|
|
|
|
entry = self._cache.get(key)
|
|
|
|
|
if entry is None:
|
|
|
|
|
return None
|
|
|
|
|
ts, stored_at = entry
|
|
|
|
|
if time.monotonic() - stored_at > self._ttl:
|
|
|
|
|
self._cache.pop(key, None)
|
|
|
|
|
return None
|
2026-05-12 00:48:57 +08:00
|
|
|
self._cache.move_to_end(key)
|
2026-05-12 14:51:53 +08:00
|
|
|
return ts
|
|
|
|
|
|
|
|
|
|
async def clear(self) -> None:
|
|
|
|
|
async with self._lock:
|
|
|
|
|
self._cache.clear()
|
|
|
|
|
|
|
|
|
|
def _evict_expired_locked(self) -> None:
|
2026-05-12 00:48:57 +08:00
|
|
|
now = time.monotonic()
|
|
|
|
|
expired = [k for k, (_, t) in self._cache.items() if now - t > self._ttl]
|
|
|
|
|
for k in expired:
|
|
|
|
|
self._cache.pop(k, None)
|
|
|
|
|
|
2026-05-12 14:51:53 +08:00
|
|
|
async def size(self) -> int:
|
|
|
|
|
async with self._lock:
|
|
|
|
|
self._evict_expired_locked()
|
|
|
|
|
return len(self._cache)
|