这是一个批量整理提交,包含以下主要改动: 1. 删除多处冗余的空行和未使用的导入 2. 修复文件末尾缺少换行符的问题 3. 调整部分模块的导入顺序与代码排版 4. 修复部分配置默认值与策略逻辑 5. 新增多个功能模块与辅助工具 6. 完善异常处理与日志记录 7. 修复速率限制、消息缓存、权限校验等逻辑bug 8. 废弃部分旧有API与配置项并添加警告提示
47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from collections import defaultdict
|
|
from typing import Any, Coroutine
|
|
|
|
_SEQUENTIAL_TIMEOUT_S = 300
|
|
|
|
|
|
class FeishuSequentialQueue:
|
|
def __init__(self, timeout_s: float = _SEQUENTIAL_TIMEOUT_S):
|
|
self._queues: dict[str, asyncio.Queue] = {}
|
|
self._locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
|
|
self._timeout_s = timeout_s
|
|
|
|
async def acquire(self, key: str) -> None:
|
|
lock = self._locks[key]
|
|
try:
|
|
await asyncio.wait_for(lock.acquire(), timeout=self._timeout_s)
|
|
except asyncio.TimeoutError:
|
|
raise RuntimeError(f"[Sequential] Timeout acquiring lock for key '{key}'")
|
|
|
|
def release(self, key: str) -> None:
|
|
lock = self._locks.get(key)
|
|
if lock and lock.locked():
|
|
lock.release()
|
|
|
|
async def run_sequential(self, key: str, coro: Coroutine[Any, Any, Any]) -> None:
|
|
try:
|
|
await asyncio.wait_for(self.acquire(key), timeout=self._timeout_s)
|
|
try:
|
|
await coro
|
|
finally:
|
|
self.release(key)
|
|
except TimeoutError:
|
|
raise RuntimeError(f"[Sequential] Timeout waiting for key '{key}'")
|
|
|
|
def remove(self, key: str) -> None:
|
|
lock = self._locks.pop(key, None)
|
|
if lock and lock.locked():
|
|
lock.release()
|
|
|
|
def clear(self) -> None:
|
|
for lock in self._locks.values():
|
|
if lock.locked():
|
|
lock.release()
|
|
self._locks.clear() |