这是一个批量整理提交,包含以下主要改动: 1. 删除多处冗余的空行和未使用的导入 2. 修复文件末尾缺少换行符的问题 3. 调整部分模块的导入顺序与代码排版 4. 修复部分配置默认值与策略逻辑 5. 新增多个功能模块与辅助工具 6. 完善异常处理与日志记录 7. 修复速率限制、消息缓存、权限校验等逻辑bug 8. 废弃部分旧有API与配置项并添加警告提示
50 lines
1.5 KiB
Python
50 lines
1.5 KiB
Python
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()
|