修复 load_markets 超时后狂打交易所:失败退避 90 秒,避免反复请求导致封 IP。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
dekun
2026-08-13 00:47:47 +08:00
parent 39878de7fc
commit 702d9d3be8
5 changed files with 138 additions and 6 deletions
+38
View File
@@ -0,0 +1,38 @@
"""交易所 load_markets 失败退避:避免超时后每次调用都狂打 API 导致封 IP."""
from __future__ import annotations
import time
from typing import Any, Callable, Optional
class MarketsLoadGuard:
def __init__(self, *, backoff_sec: float = 60.0, label: str = "markets") -> None:
self.loaded = False
self.backoff_sec = float(backoff_sec)
self.label = label
self._fail_until = 0.0
self._last_error: Optional[str] = None
def ensure(self, load_fn: Callable[[], Any], *, force: bool = False) -> None:
if self.loaded and not force:
return
now = time.time()
if not force and now < self._fail_until:
wait = max(0.0, self._fail_until - now)
raise RuntimeError(
f"{self.label} load backing off {wait:.0f}s after: {self._last_error or 'previous failure'}"
)
try:
load_fn()
self.loaded = True
self._fail_until = 0.0
self._last_error = None
except Exception as e:
self.loaded = False
self._last_error = str(e)
self._fail_until = now + self.backoff_sec
print(
f"[{self.label}] load_markets failed; backoff {self.backoff_sec:.0f}s: {e}",
flush=True,
)
raise