stop infinite retry loop on rejected Lichess tokens
All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 12s

A gamer's periodic check would get permanently stuck if their stored token
was revoked/expired: our stats API collapsed both "Lichess rejected the
token" (401/403, permanent) and genuine transient errors into the same 502
response, so the bot treated an invalid token exactly like a network blip —
retrying the same window forever at a capped 300s backoff, never advancing
the checkpoint (observed in prod: Dor1zz stuck for 100+ consecutive errors
over 8+ hours, admin alerts firing every 25 failures).

Preserve the distinction that already existed one layer down (lichess_client.py
already tells 401/403 apart from other failures) instead of collapsing it in
stats_service.py: add PuzzleOfPeriodResponse.auth_failed, have main.py return
401 specifically for that case, and have the bot raise a distinct
InvalidTokenError instead of returning None. On InvalidTokenError, the bot now
clears the token for that pair, notifies the user to reconnect via /addtoken,
and continues tracking games normally instead of stalling forever.
This commit is contained in:
vrubelroman 2026-07-05 07:37:14 +00:00
parent 8080921141
commit 619c00aa06
7 changed files with 70 additions and 16 deletions

View file

@ -6,6 +6,12 @@ from rate_limiter import get_rate_limiter
logger = logging.getLogger(__name__)
class InvalidTokenError(Exception):
"""Raised when Lichess rejects a stored token (401) — permanent, not worth retrying."""
pass
class LichessAPI:
def __init__(self):
self.lichess_base_url = LICHESS_API_BASE_URL
@ -125,10 +131,17 @@ class LichessAPI:
return None
async def get_puzzles_period(self, token: str, since: int, until: int, max_puzzles: int = 150) -> Optional[Dict[str, Any]]:
"""Get puzzles for a specific period"""
"""
Get puzzles for a specific period.
Raises InvalidTokenError on a 401 (Lichess rejected the token permanent,
the caller should stop retrying with this token) instead of returning None,
so callers can tell that apart from a transient failure (network error,
Lichess hiccup) where retrying the same window later makes sense.
"""
await self.rate_limiter.wait_if_needed()
headers = {"Authorization": f"Bearer {token}"}
try:
async with aiohttp.ClientSession() as session:
async with session.get(
@ -138,9 +151,14 @@ class LichessAPI:
) as response:
if response.status == 200:
return await response.json()
elif response.status == 401:
logger.warning(f"Puzzles period: token rejected by Lichess (401)")
raise InvalidTokenError("Lichess rejected the token")
else:
logger.error(f"Failed to get puzzles period: {response.status}")
return None
except InvalidTokenError:
raise
except Exception as e:
logger.error(f"Error getting puzzles period: {e}")
return None