ForcePilot/backend/package/yuxi/channels/adapters/feishu/sent_cache.py
Kris a6fa7245e5 feat(feishu): 完整实现飞书适配器核心模块
新增飞书机器人适配器全套功能,包括:
- 基础适配器入口与工具导出
- 消息格式化、卡片渲染、回复调度逻辑
- 会话ID生成、模型覆盖策略
- 消息发送缓存、顺序队列管理
- 飞书签名验证、加解密webhook请求
- 审批权限校验、机器人菜单事件处理
- 文档评论、钉消息、语音转码处理
- 静态/动态目录管理、子代理生命周期管理
- 各类工具集:聊天、云盘、文档、知识库API封装
2026-05-12 00:43:59 +08:00

59 lines
2.0 KiB
Python

from __future__ import annotations
import time
from typing import Any
DEFAULT_MAX_ENTRIES = 1000
DEFAULT_TTL_S = 600
class FeishuSentCache:
def __init__(self, max_entries: int = DEFAULT_MAX_ENTRIES, ttl_s: int = DEFAULT_TTL_S):
self._cache: dict[str, dict[str, Any]] = {}
self._timestamps: dict[str, float] = {}
self._max_entries = max_entries
self._ttl_s = ttl_s
def cache_sent(self, msg_id: str, chat_id: str, metadata: dict[str, Any] | None = None) -> None:
self._evict_expired()
key = self._make_key(msg_id, chat_id)
self._cache[key] = {"message_id": msg_id, "chat_id": chat_id, "metadata": metadata or {}}
self._timestamps[key] = time.monotonic()
if len(self._cache) > self._max_entries:
oldest = min(self._timestamps, key=self._timestamps.get)
self._cache.pop(oldest, None)
self._timestamps.pop(oldest, None)
def get_sent(self, msg_id: str, chat_id: str) -> dict[str, Any] | None:
key = self._make_key(msg_id, chat_id)
entry = self._cache.get(key)
if entry is None:
return None
ts = self._timestamps.get(key, 0)
if time.monotonic() - ts > self._ttl_s:
self._cache.pop(key, None)
self._timestamps.pop(key, None)
return None
return entry
def invalidate(self, msg_id: str, chat_id: str) -> None:
key = self._make_key(msg_id, chat_id)
self._cache.pop(key, None)
self._timestamps.pop(key, None)
@staticmethod
def _make_key(msg_id: str, chat_id: str) -> str:
return f"{chat_id}:{msg_id}"
def _evict_expired(self) -> None:
now = time.monotonic()
expired = [k for k, ts in self._timestamps.items() if now - ts > self._ttl_s]
for k in expired:
self._cache.pop(k, None)
self._timestamps.pop(k, None)
def clear(self) -> None:
self._cache.clear()
self._timestamps.clear()