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

88 lines
3.1 KiB
Python

from __future__ import annotations
import asyncio
import time
class ThreadBindingManager:
DEFAULT_TTL_S = 3600
CLEANUP_INTERVAL_S = 300
def __init__(self, ttl_s: int = DEFAULT_TTL_S):
self._bindings: dict[str, str] = {}
self._reverse: dict[str, str] = {}
self._timestamps: dict[str, float] = {}
self._ttl_s = ttl_s
self._lock = asyncio.Lock()
self._cleanup_task: asyncio.Task | None = None
async def bind(self, thread_id: str, session_id: str) -> None:
async with self._lock:
self._bindings[thread_id] = session_id
self._reverse[session_id] = thread_id
self._timestamps[thread_id] = time.monotonic()
async def unbind_thread(self, thread_id: str) -> None:
async with self._lock:
session_id = self._bindings.pop(thread_id, None)
if session_id:
self._reverse.pop(session_id, None)
self._timestamps.pop(thread_id, None)
async def unbind_session(self, session_id: str) -> None:
async with self._lock:
thread_id = self._reverse.pop(session_id, None)
if thread_id:
self._bindings.pop(thread_id, None)
self._timestamps.pop(thread_id, None)
async def get_session(self, thread_id: str) -> str | None:
async with self._lock:
session_id = self._bindings.get(thread_id)
if session_id:
ts = self._timestamps.get(thread_id, 0)
if time.monotonic() - ts > self._ttl_s:
await self._unbind_thread_unlocked(thread_id)
return None
return session_id
async def get_thread(self, session_id: str) -> str | None:
async with self._lock:
return self._reverse.get(session_id)
async def clear(self) -> None:
async with self._lock:
self._bindings.clear()
self._reverse.clear()
self._timestamps.clear()
def start_cleanup(self) -> None:
if self._cleanup_task is None or self._cleanup_task.done():
self._cleanup_task = asyncio.create_task(self._cleanup_loop())
def stop_cleanup(self) -> None:
if self._cleanup_task and not self._cleanup_task.done():
self._cleanup_task.cancel()
self._cleanup_task = None
async def _cleanup_loop(self) -> None:
while True:
try:
await asyncio.sleep(self.CLEANUP_INTERVAL_S)
await self._purge_expired()
except asyncio.CancelledError:
return
async def _purge_expired(self) -> None:
async with self._lock:
now = time.monotonic()
expired = [tid for tid, ts in self._timestamps.items() if now - ts > self._ttl_s]
for thread_id in expired:
await self._unbind_thread_unlocked(thread_id)
async def _unbind_thread_unlocked(self, thread_id: str) -> None:
session_id = self._bindings.pop(thread_id, None)
if session_id:
self._reverse.pop(session_id, None)
self._timestamps.pop(thread_id, None)