- periodic: stale-backlog suppression compared the window length with an absolute 2h, so every pair with period 180/360/720/1440 min was suppressed on every check (prod: 20 pairs of 16 users, 62 suppressions in 10 days). Now stale means the window exceeds the configured period by more than 2h (PeriodicMonitor._is_stale_backlog). - SharedTokenGate min_gap 6s -> 3s. Measured with a separate test account: the JSON "Please only run N request(s) at a time" 429 is a concurrency limit (2 streams per IP / per token, slot freed at stream end) that a sequential client cannot trip, so the old 6s "cooldown" rationale was wrong; the HTML "Too many requests" 429 is an edge burst limiter (~0.45-0.9 req/s sustained) that 2-3s spacing avoids. - lichess_client: on 429 log the body prefix (so the two limiters are distinguishable) and pause the gate 60s for the burst limiter only; re-raise exactly as before. - /lastYear_or_1000games uses interactive priority (was waiting behind the backlog) - /test_admin_notify only works from the admin chat - stats service honours LOG_LEVEL and silences httpx INFO (bulk of its 808 MB log) Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
159 lines
6.7 KiB
Python
159 lines
6.7 KiB
Python
"""
|
|
Rate limiter for Lichess API requests
|
|
Ensures minimum delay between requests
|
|
"""
|
|
import asyncio
|
|
import time
|
|
import logging
|
|
from collections import deque
|
|
from typing import Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class RateLimiter:
|
|
"""
|
|
Rate limiter that ensures minimum delay between requests.
|
|
Thread-safe and async-safe.
|
|
"""
|
|
|
|
def __init__(self, min_delay: float = 0.2):
|
|
"""
|
|
Initialize rate limiter.
|
|
|
|
Args:
|
|
min_delay: Minimum delay in seconds between requests (default: 0.2)
|
|
"""
|
|
self.min_delay = min_delay
|
|
self.last_request_time: Optional[float] = None
|
|
self.lock = asyncio.Lock()
|
|
|
|
async def wait_if_needed(self):
|
|
"""
|
|
Wait if necessary to maintain minimum delay between requests.
|
|
Should be called before each API request.
|
|
"""
|
|
async with self.lock:
|
|
now = time.time()
|
|
|
|
if self.last_request_time is not None:
|
|
elapsed = now - self.last_request_time
|
|
if elapsed < self.min_delay:
|
|
wait_time = self.min_delay - elapsed
|
|
logger.debug(f"Rate limiter: waiting {wait_time:.3f} seconds")
|
|
await asyncio.sleep(wait_time)
|
|
now = time.time()
|
|
|
|
self.last_request_time = now
|
|
|
|
# Global rate limiter instance
|
|
_rate_limiter = RateLimiter(min_delay=0.2)
|
|
|
|
def get_rate_limiter() -> RateLimiter:
|
|
"""Get the global rate limiter instance"""
|
|
return _rate_limiter
|
|
|
|
class SharedTokenGate:
|
|
"""
|
|
Serializes AND paces games/user + user/activity calls sharing LICHESS_APP_TOKEN.
|
|
|
|
There are two different 429s on GET /api/games/user/{u} (measured 2026-10
|
|
with a separate test account; Lichess sends no Retry-After / X-RateLimit
|
|
headers for either):
|
|
|
|
(a) lila ConcurrencyLimit, JSON body {"error":"Please only run N request(s)
|
|
at a time"}: 2 concurrent streams per IP and 2 per OAuth token. The slot
|
|
is released when the stream ends, so a strictly sequential client can
|
|
never trip it, and an inter-request gap does NOT help. Seeing it means
|
|
the slots are held by some OTHER process using the same token/IP.
|
|
Serialization (busy flag + queues below) is all this gate can do for it.
|
|
|
|
(b) edge burst limiter, HTML body "Too many requests. Read
|
|
https://http.lichess.org/429": a token bucket of roughly burst 5-6 then
|
|
~0.45-0.9 req/s sustained. Gap 0.3s -> 429 at the 9th request, 1.0s ->
|
|
at the 15th, 2.0s and 3.0s -> none. This is what min_gap protects
|
|
against: the gate tracks the last release time and forces a minimum gap
|
|
before the next request may start. Official rule after ANY 429: wait a
|
|
full minute — see pause().
|
|
|
|
Two-tier priority: background periodic checks queue behind interactive
|
|
on-demand requests (/today etc.), so a user command doesn't have to wait
|
|
out an entire backlog of checks (observed ~2min on prod) — just whatever
|
|
single request is already in flight. acquire()/release() (not a plain
|
|
`async with`) because the priority has to be picked at call time.
|
|
"""
|
|
|
|
def __init__(self, min_gap: float = 3.0):
|
|
self._min_gap = min_gap
|
|
self._last_release_time: Optional[float] = None
|
|
self._paused_until: float = 0.0
|
|
self._busy = False
|
|
self._interactive_waiters: "deque[asyncio.Future]" = deque()
|
|
self._background_waiters: "deque[asyncio.Future]" = deque()
|
|
|
|
async def acquire(self, priority: str = "background"):
|
|
"""priority: "interactive" (/today etc.) jumps ahead of "background" (periodic checks)."""
|
|
if not self._busy and not self._interactive_waiters and not self._background_waiters:
|
|
self._busy = True
|
|
else:
|
|
fut = asyncio.get_event_loop().create_future()
|
|
queue = self._interactive_waiters if priority == "interactive" else self._background_waiters
|
|
queue.append(fut)
|
|
await fut
|
|
|
|
if self._last_release_time is not None:
|
|
elapsed = time.time() - self._last_release_time
|
|
if elapsed < self._min_gap:
|
|
wait_time = self._min_gap - elapsed
|
|
logger.debug(f"Shared token gate: waiting {wait_time:.3f}s before next games/user or user/activity call")
|
|
await asyncio.sleep(wait_time)
|
|
|
|
# Global pause after a 429 (see pause()). Checked in a loop: pause() may be
|
|
# called again while we sleep. Applies to every priority — the limiter is
|
|
# per token/IP, an interactive request would just burn the minute too.
|
|
while True:
|
|
remaining = self._paused_until - time.time()
|
|
if remaining <= 0:
|
|
break
|
|
logger.info(f"Shared token gate: paused after 429, holding next call for {remaining:.1f}s")
|
|
await asyncio.sleep(remaining)
|
|
|
|
def pause(self, seconds: float):
|
|
"""
|
|
Hold every subsequent acquire() (any priority) until `seconds` from now.
|
|
Lichess' rule after any 429 is to wait a full minute; this is how the
|
|
client honours it for the whole shared token. Never blocks release(),
|
|
so it is safe to call from the error path of a request that still holds
|
|
(or has just released) the gate. Later/longer pauses extend, shorter
|
|
ones never cut an active pause short.
|
|
"""
|
|
until = time.time() + seconds
|
|
if until > self._paused_until:
|
|
self._paused_until = until
|
|
|
|
def release(self):
|
|
self._last_release_time = time.time()
|
|
if self._interactive_waiters:
|
|
nxt = self._interactive_waiters.popleft()
|
|
elif self._background_waiters:
|
|
nxt = self._background_waiters.popleft()
|
|
else:
|
|
self._busy = False
|
|
return
|
|
if not nxt.done():
|
|
nxt.set_result(None)
|
|
|
|
# min_gap=3.0: Lichess documents no number for this endpoint's inter-request
|
|
# limit (the games/user docs only mention a streaming throttle, games/sec within
|
|
# one response). Measured (see SharedTokenGate docstring): the edge burst limiter
|
|
# tolerates a sustained 1 req/2s and 1 req/3s indefinitely, while 1 req/1s trips
|
|
# it at the 15th request. 3s keeps a margin over the measured 2s and is safely
|
|
# under the ~0.45 req/s sustained refill. The earlier 6s was chosen when the
|
|
# "Please only run N request(s) at a time" 429 was blamed on spacing; that one is
|
|
# the concurrency limiter and is unaffected by the gap. Revisit if the HTML
|
|
# "Too many requests" 429 shows up in prod at this spacing.
|
|
_shared_token_gate = SharedTokenGate(min_gap=3.0)
|
|
|
|
def get_shared_token_gate() -> SharedTokenGate:
|
|
"""Gate serializing+pacing lichess.org calls made with the shared LICHESS_APP_TOKEN. Use acquire()/release()."""
|
|
return _shared_token_gate
|
|
|