ForcePilot/backend/package/yuxi/channels/adapters/feishu/chat_cache.py
Kris 1f78c44b03 refactor: 整理并清理项目中的冗余代码与格式问题
这是一个批量整理提交,包含以下主要改动:
1.  删除多处冗余的空行和未使用的导入
2.  修复文件末尾缺少换行符的问题
3.  调整部分模块的导入顺序与代码排版
4.  修复部分配置默认值与策略逻辑
5.  新增多个功能模块与辅助工具
6.  完善异常处理与日志记录
7.  修复速率限制、消息缓存、权限校验等逻辑bug
8.  废弃部分旧有API与配置项并添加警告提示
2026-05-12 14:51:53 +08:00

50 lines
1.6 KiB
Python

from __future__ import annotations
import asyncio
import time
from collections import OrderedDict
class ChatNameCache:
DEFAULT_TTL_S = 1800
DEFAULT_MAX_ENTRIES = 500
def __init__(self, ttl_s: int = DEFAULT_TTL_S, max_entries: int = DEFAULT_MAX_ENTRIES):
self._ttl_s = ttl_s
self._max_entries = max_entries
self._cache: OrderedDict[str, tuple[str, float]] = OrderedDict()
self._lock = asyncio.Lock()
@staticmethod
def _make_key(account_id: str, chat_id: str) -> str:
return f"{account_id}:{chat_id}"
async def get(self, account_id: str, chat_id: str) -> str | None:
async with self._lock:
key = self._make_key(account_id, chat_id)
entry = self._cache.get(key)
if entry is None:
return None
name, ts = entry
if time.monotonic() - ts > self._ttl_s:
self._cache.pop(key, None)
return None
self._cache.move_to_end(key)
return name
async def set(self, account_id: str, chat_id: str, name: str) -> None:
async with self._lock:
key = self._make_key(account_id, chat_id)
self._cache[key] = (name, time.monotonic())
self._cache.move_to_end(key)
if len(self._cache) > self._max_entries:
self._cache.popitem(last=False)
async def invalidate(self, account_id: str, chat_id: str) -> None:
async with self._lock:
key = self._make_key(account_id, chat_id)
self._cache.pop(key, None)
async def clear(self) -> None:
async with self._lock:
self._cache.clear()