All checks were successful
CI/CD Pipeline / build-and-deploy (push) Successful in 16s
- players absent from two consecutive bulk answers (deleted/renamed on Lichess) are paused
like closed accounts with their own notice; ❓ mark; stats service answers 404 instead
of "0 games" for unknown users
- /getgamers table stays unmarked, a legend line under it lists closed / not-found players
- daily SUMMARY is computed from events.log (survives restarts); lichess_429 comes from the
stats service /health, which now exposes lichess_429_24h / lichess_429_total
- admin /status reads its numbers through Database.get_admin_stats
- tests/: 36 bot + 15 service unittest cases, run_tests.sh runs them inside the real images,
CI runs them after the build and before pushing/deploying
- docs: USER_GUIDE/about/API_DOCUMENTATION rewritten for the current code, ARCHITECTURE.md and
two sub-READMEs removed, 7 obsolete helper scripts removed, CURRENT_STATE updated
- .claude/agents/designer.md: Telegram-aware designer role
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
175 lines
8.6 KiB
Python
175 lines
8.6 KiB
Python
"""
|
|
Bulk player status refresh.
|
|
|
|
Every config.PLAYER_STATUS_REFRESH_MINUTES this asks the stats service
|
|
(POST /users/status -> one Lichess POST /api/users per 300 names) for every
|
|
player that at least one user tracks with a period set, and stores the answer
|
|
in gamer_status: whether the account is closed and how many games the player
|
|
has played in total (sum of perfs.*.games, puzzle excluded).
|
|
|
|
periodic_check (periodic.py) reads that table before each games request: an
|
|
unchanged games_total means no game was finished since the pair's last check,
|
|
so the games/user call for that window is skipped and the checkpoint is
|
|
advanced; a closed account pauses the pair's checks (and tells the owner once).
|
|
This turns ~450 individual games/user calls per hour, ~95 % of which found 0
|
|
games, into a couple of bulk calls per refresh.
|
|
|
|
The refresh must never be a hard dependency: if it fails (or has never run),
|
|
periodic_check falls back to today's behaviour and requests every window.
|
|
"""
|
|
import asyncio
|
|
import logging
|
|
import time
|
|
from typing import Optional
|
|
|
|
import config
|
|
from database import Database
|
|
from lichess_api import LichessAPI
|
|
from notifications import AdminNotifier
|
|
from events import event
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Lichess accepts at most this many names per POST /api/users.
|
|
BULK_CHUNK_SIZE = 300
|
|
|
|
|
|
class PlayerStatusRefresher:
|
|
# The initial refresh at bot startup (refresh_with_retries): on prod the bot
|
|
# and the stats service start in the same second, so the very first call
|
|
# regularly dies with "Connection reset by peer" and the first 15 minutes
|
|
# then ran without status. 4 attempts 5 s apart cover the service's boot.
|
|
INITIAL_REFRESH_ATTEMPTS = 4
|
|
INITIAL_REFRESH_RETRY_DELAY_SECONDS = 5.0
|
|
|
|
# run_forever: tell the admin after this many consecutive failed refreshes
|
|
# (3 x PLAYER_STATUS_REFRESH_MINUTES = ~45 min without status, i.e. exactly
|
|
# when periodic_check starts treating the stored status as stale) and again
|
|
# every ADMIN_NOTIFY_FAILURE_THRESHOLD failures after that.
|
|
ADMIN_NOTIFY_FAILURE_THRESHOLD = 3
|
|
|
|
def __init__(self, db: Database, lichess_api: LichessAPI, notifier: Optional[AdminNotifier] = None):
|
|
self.db = db
|
|
self.lichess_api = lichess_api
|
|
self.notifier = notifier # None: no admin notifications (tests)
|
|
|
|
async def refresh_once(self) -> dict:
|
|
"""
|
|
One refresh pass over all tracked players. Returns a summary dict
|
|
{'tracked', 'answered', 'closed', 'not_found', 'seconds'}; raises on
|
|
failure (the caller decides whether that is fatal — run_forever just
|
|
retries). 'not_found' = players flagged as unknown to Lichess after this
|
|
pass (absent from two consecutive successful answers).
|
|
"""
|
|
started = time.monotonic()
|
|
tracked = self.db.get_all_tracked_gamers()
|
|
if not tracked:
|
|
logger.info("🩺 Player status refresh: 0 tracked, nothing to do")
|
|
event('status_refresh', tracked=0, answered=0, closed=0, not_found=0, took_s=0.0, ok=True)
|
|
return {'tracked': 0, 'answered': 0, 'closed': 0, 'not_found': 0, 'seconds': 0.0}
|
|
|
|
# Lichess answers with the canonical spelling; match on the lowercase id,
|
|
# which is exactly username.lower() (usernames are case-insensitive there).
|
|
by_lower = {g['username'].lower(): g['id'] for g in tracked}
|
|
rows = []
|
|
closed = 0
|
|
not_found = 0
|
|
for start in range(0, len(tracked), BULK_CHUNK_SIZE):
|
|
chunk = tracked[start:start + BULK_CHUNK_SIZE]
|
|
players = await self.lichess_api.get_users_status([g['username'] for g in chunk])
|
|
if players is None:
|
|
event('status_refresh', tracked=len(tracked), answered=len(rows), closed=closed,
|
|
not_found=not_found, took_s=time.monotonic() - started, ok=False)
|
|
raise RuntimeError(f"users/status returned no data for chunk {start // BULK_CHUNK_SIZE + 1}")
|
|
# checked_at is taken after the answer arrives, per chunk: it must not be
|
|
# newer than the data it describes.
|
|
checked_at = int(time.time())
|
|
chunk_rows = []
|
|
for p in players:
|
|
gamer_id = by_lower.get(str(p.get('id') or '').lower())
|
|
if gamer_id is None:
|
|
continue
|
|
disabled = bool(p.get('disabled', False))
|
|
closed += 1 if disabled else 0
|
|
chunk_rows.append({
|
|
'gamer_id': gamer_id,
|
|
'disabled': disabled,
|
|
'seen_at': p.get('seen_at'),
|
|
'games_total': p.get('games_total'),
|
|
'checked_at': checked_at,
|
|
})
|
|
# Names Lichess did not return in a successful (HTTP 200) answer are
|
|
# accounts it no longer knows: deleted or renamed. They get a miss
|
|
# counted (and are flagged not_found from the second consecutive
|
|
# miss, see Database.mark_gamer_statuses_missing); a name present
|
|
# again resets that via upsert_gamer_statuses. Done per chunk so a
|
|
# failing later chunk never marks an unanswered chunk as missing.
|
|
answered_ids = {r['gamer_id'] for r in chunk_rows}
|
|
missing_ids = [g['id'] for g in chunk if g['id'] not in answered_ids]
|
|
self.db.upsert_gamer_statuses(chunk_rows)
|
|
if missing_ids:
|
|
not_found += self.db.mark_gamer_statuses_missing(missing_ids, checked_at)
|
|
rows.extend(chunk_rows)
|
|
seconds = time.monotonic() - started
|
|
logger.info(
|
|
f"🩺 Player status refresh: {len(tracked)} tracked, {len(rows)} answered, "
|
|
f"{closed} closed, {not_found} not found, took {seconds:.1f}s"
|
|
)
|
|
event('status_refresh', tracked=len(tracked), answered=len(rows), closed=closed,
|
|
not_found=not_found, took_s=seconds, ok=True)
|
|
return {'tracked': len(tracked), 'answered': len(rows), 'closed': closed,
|
|
'not_found': not_found, 'seconds': seconds}
|
|
|
|
async def refresh_with_retries(self, attempts: int = INITIAL_REFRESH_ATTEMPTS,
|
|
delay: float = INITIAL_REFRESH_RETRY_DELAY_SECONDS) -> Optional[dict]:
|
|
"""
|
|
refresh_once() with up to `attempts` tries `delay` seconds apart (startup
|
|
use, see INITIAL_REFRESH_ATTEMPTS). Retries are logged at WARNING;
|
|
returns the summary of the successful pass, or None when every attempt
|
|
failed (the caller logs that and continues without status).
|
|
"""
|
|
last_error = None
|
|
for attempt in range(1, attempts + 1):
|
|
try:
|
|
return await self.refresh_once()
|
|
except Exception as e:
|
|
last_error = e
|
|
if attempt < attempts:
|
|
logger.warning(
|
|
f"⚠️ Player status refresh attempt {attempt}/{attempts} failed: {e}; "
|
|
f"retrying in {delay:g}s"
|
|
)
|
|
await asyncio.sleep(delay)
|
|
logger.error(f"❌ Player status refresh failed {attempts} times in a row: {last_error}")
|
|
return None
|
|
|
|
async def run_forever(self):
|
|
"""
|
|
Refresh every PLAYER_STATUS_REFRESH_MINUTES; log and retry at the next
|
|
tick on any error. Consecutive failures are counted: at every
|
|
ADMIN_NOTIFY_FAILURE_THRESHOLD-th one the admin is told (the periodic
|
|
checks are then running without status, i.e. requesting every window);
|
|
a successful refresh resets the counter.
|
|
"""
|
|
interval = config.PLAYER_STATUS_REFRESH_MINUTES * 60
|
|
consecutive_failures = 0
|
|
while True:
|
|
try:
|
|
await asyncio.sleep(interval)
|
|
await self.refresh_once()
|
|
consecutive_failures = 0
|
|
except asyncio.CancelledError:
|
|
break
|
|
except Exception as e:
|
|
consecutive_failures += 1
|
|
logger.error(
|
|
f"❌ Player status refresh failed ({consecutive_failures} in a row), "
|
|
f"will retry in {config.PLAYER_STATUS_REFRESH_MINUTES} min: {e}"
|
|
)
|
|
import traceback
|
|
logger.error(traceback.format_exc())
|
|
if self.notifier is not None and consecutive_failures % self.ADMIN_NOTIFY_FAILURE_THRESHOLD == 0:
|
|
try:
|
|
await self.notifier.notify_status_refresh_failing(consecutive_failures, repr(e))
|
|
except Exception as notify_err:
|
|
logger.error(f"Failed to notify admin about failing status refresh: {notify_err}")
|