ForcePilot/backend/package/yuxi/channels/adapters/feishu/thread_bindings.py

49 lines
1.5 KiB
Python
Raw Normal View History

from __future__ import annotations
import time
class ThreadBindingManager:
DEFAULT_TTL_S = 3600
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
def bind(self, thread_id: str, session_id: str) -> None:
self._bindings[thread_id] = session_id
self._reverse[session_id] = thread_id
self._timestamps[thread_id] = time.monotonic()
def unbind_thread(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)
def unbind_session(self, session_id: str) -> None:
thread_id = self._reverse.pop(session_id, None)
if thread_id:
self._bindings.pop(thread_id, None)
self._timestamps.pop(thread_id, None)
def get_session(self, thread_id: str) -> str | None:
session_id = self._bindings.get(thread_id)
if session_id:
ts = self._timestamps.get(thread_id, 0)
if time.monotonic() - ts > self._ttl_s:
self.unbind_thread(thread_id)
return None
return session_id
def get_thread(self, session_id: str) -> str | None:
return self._reverse.get(session_id)
def clear(self) -> None:
self._bindings.clear()
self._reverse.clear()
self._timestamps.clear()