LichessStatTgWeb/LichessWebServices/rate_limiter.py
vrubelroman 99b1275834
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 16s
v1.5.0: startup status-refresh retries, /today skips dormant players, unknown-command hint, /cancel fix
- player status: initial bulk refresh retries 4x5s (bot and stats service start in the
  same second on prod, the first attempt failed with connection reset); admin is
  notified after 3 consecutive failed refreshes
- /today, /yesterday, /week: players whose bulk status shows they were not online since
  the period start (or whose account is closed) are skipped without any Lichess call;
  stats service paces user/activity at 8.5s (Lichess allows 15 per 2 min per IP), so a
  user with 16+ tracked players no longer hits 429 mid-command
- unknown /commands in private chats get the usual hint and a cmd name=unknown event
- /addtoken -> /cancel used to crash (sync lambda awaited by PTB 20); now an async handler
- version 1.5.0, CHANGELOG entry for everything since 1.1.0 that shipped today
- docs: CURRENT_STATE.md rewritten for 30aaa34, README brought in line with the code
  (port 8002, module list, commands, .env vars, DB tables, events.log section)

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-20 23:21:53 +00:00

218 lines
9.3 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
class ActivityRateLimiter:
"""
Extra pacing for GET /api/user/{u}/activity ONLY, on top of SharedTokenGate.
Lichess limits that endpoint to 15 requests per 2 minutes per IP (lila
Limiters.scala, a fixed window) — independent of the games/user burst
limiter that the 3 s shared-token gap protects against. /today, /yesterday
and /week call it once per tracked player, so a user with 16+ players
always got a 429 mid-command. min_delay=8.5 s means at most 14 calls in any
120 s, process-wide, whatever the caller mix.
Usage (see LichessClient.get_user_activity):
async with activity_limiter: # waits out the gap, holds the lock
await gate.acquire("interactive") # then queues for the shared token
try:
activity_limiter.mark() # stamp at the moment of the request
... request ...
finally:
gate.release()
The gap is measured from mark() (the actual request start) and the wait
happens BEFORE the gate is acquired, so the gate is never held while this
limiter sleeps: games/user calls (periodic checks, accuracy fetches)
continue to flow between two activity calls. The lock is held across the
gate acquire so that two concurrent activity callers cannot both pass the
wait and then fire 3 s apart; holding it cannot deadlock, because nothing
that holds the gate ever waits for this lock.
"""
def __init__(self, min_delay: float = 8.5):
self.min_delay = min_delay
self._last_request_time: Optional[float] = None
self._lock = asyncio.Lock()
async def __aenter__(self):
await self._lock.acquire()
if self._last_request_time is not None:
wait_time = self.min_delay - (time.time() - self._last_request_time)
if wait_time > 0:
logger.info(f"Activity rate limiter: waiting {wait_time:.1f}s before next user/activity call (15 per 2 min at Lichess)")
await asyncio.sleep(wait_time)
return self
def mark(self):
"""Record that a user/activity request is being sent now (call while holding the lock)."""
self._last_request_time = time.time()
async def __aexit__(self, exc_type, exc, tb):
self._lock.release()
return False
_activity_rate_limiter = ActivityRateLimiter(min_delay=8.5)
def get_activity_rate_limiter() -> ActivityRateLimiter:
"""Process-wide limiter for GET user/{u}/activity: at most one call per 8.5 s (Lichess: 15 per 2 min per IP)."""
return _activity_rate_limiter