ForcePilot/backend/package/yuxi/channels/adapters/feishu/chat_cache.py
Kris 69b7139863 refactor(feishu): 清理冗余代码并补全飞书工具集实现
1.  移除多个文件中的空行、冗余导入
2.  修复文件末尾缺少换行符的问题
3.  新增并补全飞书多类工具API实现:
    - 多维表格:更新、删除记录,列出视图
    - 文档:更新、追加、删除块
    - 云文档:上传、下载文件
    - 群组:创建、添加成员、更新信息、创建公告
    - 目录:重构用户部门缓存逻辑
4.  优化消息发送、回复、转发等API的错误处理和逻辑
5.  新增消息列表查询、已读状态查询等功能
2026-05-13 16:07:59 +08:00

51 lines
1.7 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()