1. 统一调整多个文件的导入排序,将TYPE_CHECKING相关导入放在正确位置 2. 修复rate_limiter中当限制数<=0时直接返回false的逻辑 3. 为message_cache新增更新消息内容的方法 4. 重构extract_graph_content支持日记类型内容提取 5. 调整@提及匹配的正则表达式,避免误匹配 6. 完善invite_manager,添加客户端和凭据支持并实现自动接受群邀请逻辑 7. 调整adapter.py中的导入顺序和初始化逻辑 8. 修复monitor中的编辑事件处理,改为异步处理并实现消息更新缓存 9. 调整datetime导入顺序,统一使用UTC在前的格式
50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import time
|
|
|
|
from yuxi.utils.logging_config import logger
|
|
|
|
|
|
class RateLimiter:
|
|
def __init__(self, limit: int = 30, window: float = 60.0):
|
|
self._limit = limit
|
|
self._window = window
|
|
self._tokens = float(limit)
|
|
self._last_refill = time.monotonic()
|
|
self._lock = asyncio.Lock()
|
|
|
|
async def acquire(self) -> bool:
|
|
if self._limit <= 0:
|
|
return False
|
|
async with self._lock:
|
|
now = time.monotonic()
|
|
elapsed = now - self._last_refill
|
|
refill = elapsed * (self._limit / self._window)
|
|
self._tokens = min(float(self._limit), self._tokens + refill)
|
|
self._last_refill = now
|
|
|
|
if self._tokens >= 1.0:
|
|
self._tokens -= 1.0
|
|
return True
|
|
|
|
wait_s = (1.0 - self._tokens) * (self._window / self._limit)
|
|
logger.debug(f"[Urbit] Rate limit: token exhausted, need ~{wait_s:.1f}s")
|
|
return False
|
|
|
|
async def wait_and_acquire(self, timeout: float = 30.0) -> bool:
|
|
if self._limit <= 0:
|
|
return False
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
if await self.acquire():
|
|
return True
|
|
wait_s = (1.0 - max(0, self._tokens)) * (self._window / self._limit)
|
|
await asyncio.sleep(min(wait_s, 1.0))
|
|
logger.warning("[Urbit] Rate limiter wait timed out")
|
|
return False
|
|
|
|
@property
|
|
def available_tokens(self) -> float:
|
|
return max(0.0, self._tokens)
|