2026-05-12 14:51:53 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import time
|
|
|
|
|
from collections import OrderedDict
|
|
|
|
|
from typing import Any
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class OutboundCacheManager:
|
|
|
|
|
def __init__(self, max_size: int = 500):
|
|
|
|
|
self._cache: OrderedDict[str, dict[str, Any]] = OrderedDict()
|
|
|
|
|
self._max_size = max_size
|
|
|
|
|
|
2026-05-13 16:16:02 +08:00
|
|
|
def record(self, target: str, content: str, message_id: str | None = None) -> str:
|
2026-05-12 14:51:53 +08:00
|
|
|
entry = {
|
|
|
|
|
"channel": target,
|
|
|
|
|
"content": content,
|
|
|
|
|
"timestamp": time.time(),
|
|
|
|
|
}
|
2026-05-13 16:16:02 +08:00
|
|
|
cache_key = message_id or f"{target}:{len(self._cache)}"
|
|
|
|
|
if message_id:
|
|
|
|
|
entry["message_id"] = message_id
|
2026-05-12 14:51:53 +08:00
|
|
|
self._cache[cache_key] = entry
|
|
|
|
|
while len(self._cache) > self._max_size:
|
|
|
|
|
self._cache.popitem(last=False)
|
2026-05-13 16:16:02 +08:00
|
|
|
return cache_key
|
2026-05-12 14:51:53 +08:00
|
|
|
|
|
|
|
|
def get_all(self) -> list[dict[str, Any]]:
|
|
|
|
|
return list(self._cache.values())
|
2026-05-13 16:16:02 +08:00
|
|
|
|
|
|
|
|
def find_by_message_id(self, message_id: str) -> dict[str, Any] | None:
|
|
|
|
|
for entry in self._cache.values():
|
|
|
|
|
if entry.get("message_id") == message_id:
|
|
|
|
|
return entry
|
|
|
|
|
return None
|