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

51 lines
1.5 KiB
Python
Raw Normal View History

from __future__ import annotations
import time
from typing import Any
class FeishuClientCache:
def __init__(self, max_clients: int = 10):
self._clients: dict[str, Any] = {}
self._token_expiry: dict[str, float] = {}
self._max_clients = max_clients
def get(self, account_id: str) -> Any | None:
entry = self._clients.get(account_id)
if entry is not None:
expiry = self._token_expiry.get(account_id, 0)
if expiry > 0 and time.time() > expiry:
self._clients.pop(account_id, None)
self._token_expiry.pop(account_id, None)
return None
return entry
def set(self, account_id: str, client: Any, token_expiry: float = 0) -> None:
if len(self._clients) >= self._max_clients and account_id not in self._clients:
oldest = next(iter(self._clients))
self._clients.pop(oldest, None)
self._token_expiry.pop(oldest, None)
self._clients[account_id] = client
if token_expiry > 0:
self._token_expiry[account_id] = token_expiry
def get_or_create(
self,
account_id: str,
factory,
*args,
token_expiry: float = 0,
**kwargs,
) -> Any:
client = self.get(account_id)
if client is not None:
return client
client = factory(*args, **kwargs)
self.set(account_id, client, token_expiry)
return client
def clear(self) -> None:
self._clients.clear()
self._token_expiry.clear()