46 lines
1.3 KiB
Python
46 lines
1.3 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import time
|
||
|
|
from typing import Any
|
||
|
|
|
||
|
|
DEFAULT_CACHE_TTL_SEC = 3600
|
||
|
|
|
||
|
|
|
||
|
|
class SentMessageCache:
|
||
|
|
def __init__(self, ttl_sec: int = DEFAULT_CACHE_TTL_SEC):
|
||
|
|
self._ttl_sec = ttl_sec
|
||
|
|
self._cache: dict[str, dict[str, Any]] = {}
|
||
|
|
|
||
|
|
def put(self, message_id: str, recipient: str, content: str, metadata: dict[str, Any] | None = None):
|
||
|
|
self._cache[message_id] = {
|
||
|
|
"message_id": message_id,
|
||
|
|
"recipient": recipient,
|
||
|
|
"content": content,
|
||
|
|
"sent_at": time.time(),
|
||
|
|
"metadata": metadata or {},
|
||
|
|
}
|
||
|
|
self._cleanup()
|
||
|
|
|
||
|
|
def get(self, message_id: str) -> dict[str, Any] | None:
|
||
|
|
entry = self._cache.get(message_id)
|
||
|
|
if not entry:
|
||
|
|
return None
|
||
|
|
if time.time() - entry["sent_at"] > self._ttl_sec:
|
||
|
|
del self._cache[message_id]
|
||
|
|
return None
|
||
|
|
return entry
|
||
|
|
|
||
|
|
def remove(self, message_id: str):
|
||
|
|
self._cache.pop(message_id, None)
|
||
|
|
|
||
|
|
def _cleanup(self):
|
||
|
|
boundary = time.time() - self._ttl_sec
|
||
|
|
expired = [k for k, v in self._cache.items() if v["sent_at"] < boundary]
|
||
|
|
for k in expired:
|
||
|
|
del self._cache[k]
|
||
|
|
|
||
|
|
@property
|
||
|
|
def size(self) -> int:
|
||
|
|
self._cleanup()
|
||
|
|
return len(self._cache)
|