这是一个批量整理提交,包含以下主要改动: 1. 删除多处冗余的空行和未使用的导入 2. 修复文件末尾缺少换行符的问题 3. 调整部分模块的导入顺序与代码排版 4. 修复部分配置默认值与策略逻辑 5. 新增多个功能模块与辅助工具 6. 完善异常处理与日志记录 7. 修复速率限制、消息缓存、权限校验等逻辑bug 8. 废弃部分旧有API与配置项并添加警告提示
54 lines
1.7 KiB
Python
54 lines
1.7 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
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
|
|
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
|
|
self._cache.move_to_end(key)
|
|
return ts
|
|
|
|
async def clear(self) -> None:
|
|
async with self._lock:
|
|
self._cache.clear()
|
|
|
|
def _evict_expired_locked(self) -> None:
|
|
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)
|
|
|
|
async def size(self) -> int:
|
|
async with self._lock:
|
|
self._evict_expired_locked()
|
|
return len(self._cache)
|