2026-05-12 00:43:59 +08:00
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
|
|
|
import asyncio
|
|
|
|
|
from collections import defaultdict
|
2026-05-13 16:07:59 +08:00
|
|
|
from collections.abc import Coroutine
|
|
|
|
|
from typing import Any
|
2026-05-12 00:43:59 +08:00
|
|
|
|
2026-05-12 14:51:53 +08:00
|
|
|
_SEQUENTIAL_TIMEOUT_S = 300
|
2026-05-12 00:43:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class FeishuSequentialQueue:
|
2026-05-12 14:51:53 +08:00
|
|
|
def __init__(self, timeout_s: float = _SEQUENTIAL_TIMEOUT_S):
|
2026-05-12 00:43:59 +08:00
|
|
|
self._queues: dict[str, asyncio.Queue] = {}
|
|
|
|
|
self._locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock)
|
2026-05-12 14:51:53 +08:00
|
|
|
self._timeout_s = timeout_s
|
2026-05-12 00:43:59 +08:00
|
|
|
|
|
|
|
|
async def acquire(self, key: str) -> None:
|
|
|
|
|
lock = self._locks[key]
|
2026-05-12 14:51:53 +08:00
|
|
|
try:
|
|
|
|
|
await asyncio.wait_for(lock.acquire(), timeout=self._timeout_s)
|
2026-05-13 16:07:59 +08:00
|
|
|
except TimeoutError:
|
2026-05-12 14:51:53 +08:00
|
|
|
raise RuntimeError(f"[Sequential] Timeout acquiring lock for key '{key}'")
|
2026-05-12 00:43:59 +08:00
|
|
|
|
|
|
|
|
def release(self, key: str) -> None:
|
|
|
|
|
lock = self._locks.get(key)
|
|
|
|
|
if lock and lock.locked():
|
|
|
|
|
lock.release()
|
|
|
|
|
|
2026-05-12 14:51:53 +08:00
|
|
|
async def run_sequential(self, key: str, coro: Coroutine[Any, Any, Any]) -> None:
|
2026-05-12 00:43:59 +08:00
|
|
|
try:
|
2026-05-12 14:51:53 +08:00
|
|
|
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}'")
|
2026-05-12 00:43:59 +08:00
|
|
|
|
|
|
|
|
def remove(self, key: str) -> None:
|
2026-05-12 14:51:53 +08:00
|
|
|
lock = self._locks.pop(key, None)
|
|
|
|
|
if lock and lock.locked():
|
|
|
|
|
lock.release()
|
2026-05-12 00:43:59 +08:00
|
|
|
|
|
|
|
|
def clear(self) -> None:
|
2026-05-12 14:51:53 +08:00
|
|
|
for lock in self._locks.values():
|
|
|
|
|
if lock.locked():
|
|
|
|
|
lock.release()
|
2026-05-13 16:07:59 +08:00
|
|
|
self._locks.clear()
|