From edc29c5ad71212afbdc148b25e83634e880381ec Mon Sep 17 00:00:00 2001 From: "mateo.gayrard" Date: Thu, 3 Dec 2026 11:15:34 +0100 Subject: [PATCH] feat: statistiques d'utilisation de l'API Riot (ligne RIOT du journal) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - RiotStats : requêtes par endpoint (sans identifiants), codes de réponse, latence, 429 par type, Retry-After cumulé, temps d'attente du limiteur local - quotas de la clé et consommation lus dans les en-têtes Riot (X-App-Rate-Limit*, X-Method-Rate-Limit*) - toutes les minutes, une ligne RIOT {json} sur botdiff.audit, lisible par un outil de supervision - tests et documentation Co-Authored-By: Claude Opus 5.5 --- audit.py | 8 +++- bot.py | 18 ++++++- docs/fonctionnement.md | 10 ++++ riot_api.py | 106 +++++++++++++++++++++++++++++++++++++++-- tests/test_riot_api.py | 57 ++++++++++++++++++++++ 5 files changed, 194 insertions(+), 5 deletions(-) diff --git a/audit.py b/audit.py index a1de635..8690830 100644 --- a/audit.py +++ b/audit.py @@ -1,7 +1,8 @@ """Journal structuré des commandes et des événements du bot. Chaque commande exécutée (slash ou « $ ») produit une ligne `CMD {json}`, chaque événement notable -(alerte de partie, récap, rappel d'objectifs) une ligne `EVT {json}`, sur le logger `botdiff.audit`. +(alerte de partie, récap, rappel d'objectifs) une ligne `EVT {json}`, et chaque minute une ligne `RIOT {json}` +résume l'utilisation de l'API Riot (requêtes, codes, quotas de la clé), sur le logger `botdiff.audit`. Le moniteur (botdiff-monitor) lit ces lignes dans les logs Docker pour l'historique des commandes. """ @@ -77,5 +78,10 @@ def log_event(kind: str, **data: Any) -> None: logger.info("EVT %s", json.dumps(payload, ensure_ascii=False, separators=(",", ":"), default=str)) +def log_riot(payload: dict[str, Any]) -> None: + """Statistiques d'utilisation de l'API Riot sur la dernière minute (ligne RIOT {json}).""" + logger.info("RIOT %s", json.dumps(payload, ensure_ascii=False, separators=(",", ":"), default=str)) + + def command_name(command: Any) -> str: return getattr(command, "qualified_name", None) or getattr(command, "name", None) or "?" diff --git a/bot.py b/bot.py index 0f8e0aa..3814241 100644 --- a/bot.py +++ b/bot.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio import logging from typing import Any @@ -9,7 +10,7 @@ from discord import app_commands from discord.ext import commands -from audit import command_name, log_command +from audit import command_name, log_command, log_riot from database import Database from embeds import utils as embed_utils from embeds.views import MatchDetailsButton, ProfileButton @@ -19,6 +20,7 @@ logger = logging.getLogger("botdiff.bot") EXTENSIONS = ("cogs.tracking", "cogs.commands", "cogs.prefix") +RIOT_STATS_INTERVAL_S = 60 class BotDiff(commands.Bot): @@ -46,6 +48,17 @@ async def setup_hook(self) -> None: await self.tree.set_translator(CommandTranslator()) await self.tree.sync() logger.info("Commandes slash synchronisées.") + self._riot_stats_task = asyncio.create_task(self._publish_riot_stats()) + + async def _publish_riot_stats(self) -> None: + """Toutes les minutes : une ligne RIOT {json} (utilisation de l'API et quotas de la clé).""" + limits = ",".join(f"{n}:{int(w) if w == int(w) else w}" for n, w in self.riot.limiter.limits) + while True: + await asyncio.sleep(RIOT_STATS_INTERVAL_S) + try: + log_riot({**self.riot.stats.snapshot(), "local_limits": limits}) + except Exception: # la publication ne doit jamais arrêter le bot + logger.exception("Statistiques API Riot non publiées") async def on_app_command_completion( self, interaction: discord.Interaction, command: app_commands.Command | app_commands.ContextMenu @@ -56,6 +69,9 @@ async def on_ready(self) -> None: logger.info("Connecté en tant que %s (ID: %s)", self.user, self.user and self.user.id) async def close(self) -> None: + task = getattr(self, "_riot_stats_task", None) + if task is not None: + task.cancel() await super().close() # décharge les cogs (arrête la boucle de suivi) await self.riot.close() await embed_utils.close_session() diff --git a/docs/fonctionnement.md b/docs/fonctionnement.md index d8b09b5..e1764ba 100644 --- a/docs/fonctionnement.md +++ b/docs/fonctionnement.md @@ -129,4 +129,14 @@ EVT {"type":"match_alert","match_id":"EUW1_123","guild_id":1,"players":"['Bob#EU - `status` : `ok`, `user_error` (erreur expliquée à l'utilisateur, `error` contient la clé du message) ou `error` (bug, le détail est aussi dans les logs `ERROR`). - Événements : `match_alert` (alerte de partie envoyée), `weekly_recap` (classement hebdo), `goal_reminder` (point objectifs). +Toutes les minutes, une ligne `RIOT {json}` résume l'utilisation de l'API Riot depuis la précédente : + +``` +RIOT {"window_s":60,"requests":42,"status":{"200":40,"404":2},"endpoints":{"match-v5 match":{"n":12,"errors":0,"avg_ms":180}},"app_limit":"20:1,100:120","app_count":"3:1,45:120","method":{},"limiter_wait_s":0.0,"retry_after_s":0,"rate_limited":{},"local_limits":"20:1,100:120"} +``` + +- `app_limit` / `app_count` : quotas de la clé et consommation renvoyés par Riot (en-têtes `X-App-Rate-Limit*`), par fenêtre « requêtes:secondes ». +- `status` : codes de réponse (`429` : quota dépassé, `401`/`403` : clé invalide ou expirée, `0` : erreur réseau). +- `limiter_wait_s` : temps passé à attendre le limiteur local, `rate_limited` : 429 par type (`application`, `method`, `service`). + Ces lignes servent à suivre l'activité du bot (historique des commandes, erreurs, temps de réponse) depuis un outil de supervision. diff --git a/riot_api.py b/riot_api.py index f36342b..9de63a1 100644 --- a/riot_api.py +++ b/riot_api.py @@ -53,6 +53,95 @@ def region_for_platform(platform: str) -> str: _RETRY = object() # sentinelle interne : la requête doit être retentée +_ENDPOINTS = ( + ("/riot/account/v1/accounts/by-riot-id/", "account-v1 by-riot-id"), + ("/riot/account/v1/accounts/by-puuid/", "account-v1 by-puuid"), + ("/lol/summoner/v4/", "summoner-v4"), + ("/lol/league/v4/", "league-v4"), +) + + +def endpoint_name(url: str) -> str: + """Nom stable d'un endpoint Riot (sans identifiants), pour les statistiques.""" + path = url.split("://", 1)[-1].split("/", 1)[-1] + path = "/" + path.split("?", 1)[0] + for prefix, name in _ENDPOINTS: + if path.startswith(prefix): + return name + if path.startswith("/lol/match/v5/matches/"): + return "match-v5 ids" if path.endswith("/ids") else "match-v5 match" + return "/".join(path.strip("/").split("/")[:3]) or "?" + + +class RiotStats: + """Compteurs d'utilisation de l'API Riot, publiés puis remis à zéro à chaque `snapshot()`. + + Les en-têtes de Riot donnent la limite de la clé et sa consommation courante : + X-App-Rate-Limit "20:1,100:120" et X-App-Rate-Limit-Count "3:1,45:120" (idem par méthode). + """ + + def __init__(self) -> None: + self.app_limit: str | None = None + self.app_count: str | None = None + self.method: dict[str, dict[str, str | None]] = {} + self._reset() + + def _reset(self) -> None: + self.started = time.monotonic() + self.requests = 0 + self.status: dict[str, int] = {} + self.endpoints: dict[str, dict[str, Any]] = {} + self.limiter_wait_s = 0.0 + self.retry_after_s = 0 + self.limit_types: dict[str, int] = {} + + def record(self, endpoint: str, status: int, ms: float, headers: Any = None) -> None: + self.requests += 1 + key = str(status) + self.status[key] = self.status.get(key, 0) + 1 + ep = self.endpoints.setdefault(endpoint, {"n": 0, "errors": 0, "ms_total": 0.0}) + ep["n"] += 1 + ep["ms_total"] += ms + if status != 200: + ep["errors"] += 1 + if headers is None: + return + if headers.get("X-App-Rate-Limit"): + self.app_limit = headers.get("X-App-Rate-Limit") + self.app_count = headers.get("X-App-Rate-Limit-Count") + if headers.get("X-Method-Rate-Limit"): + self.method[endpoint] = { + "limit": headers.get("X-Method-Rate-Limit"), + "count": headers.get("X-Method-Rate-Limit-Count"), + } + if status == 429: + kind = headers.get("X-Rate-Limit-Type", "service") + self.limit_types[kind] = self.limit_types.get(kind, 0) + 1 + try: + self.retry_after_s += int(headers.get("Retry-After", 0)) + except ValueError: + pass + + def snapshot(self) -> dict[str, Any]: + """Statistiques depuis le dernier appel, puis remise à zéro (les limites connues sont gardées).""" + payload = { + "window_s": round(time.monotonic() - self.started), + "requests": self.requests, + "status": self.status, + "endpoints": { + name: {"n": e["n"], "errors": e["errors"], "avg_ms": round(e["ms_total"] / e["n"])} + for name, e in self.endpoints.items() + }, + "app_limit": self.app_limit, + "app_count": self.app_count, + "method": self.method, + "limiter_wait_s": round(self.limiter_wait_s, 1), + "retry_after_s": self.retry_after_s, + "rate_limited": self.limit_types, + } + self._reset() + return payload + class RiotAPIError(Exception): """Erreur renvoyée par l'API Riot (status 0 = erreur réseau).""" @@ -80,7 +169,9 @@ def __init__(self, limits: list[tuple[int, float]]) -> None: self._lock = asyncio.Lock() self._max_window = max((w for _, w in limits), default=0.0) - async def acquire(self) -> None: + async def acquire(self) -> float: + """Attend une place dans les fenêtres ; renvoie le temps attendu (secondes).""" + waited = 0.0 async with self._lock: while True: now = time.monotonic() @@ -94,9 +185,10 @@ async def acquire(self) -> None: wait = max(wait, recent[-limit] + window - now) if wait <= 0: self._calls.append(now) - return + return waited logger.debug("Limite de débit atteinte, pause de %.2fs", wait) await asyncio.sleep(wait) + waited += wait class RiotAPI: @@ -117,6 +209,7 @@ def __init__( self.region = region self.account_region = ACCOUNT_REGIONS.get(region, region) self.limiter = RateLimiter(DEFAULT_RATE_LIMITS if rate_limits is None else rate_limits) + self.stats = RiotStats() self._session: aiohttp.ClientSession | None = None self._match_cache: OrderedDict[str, Match] = OrderedDict() self._match_pending: dict[str, asyncio.Future[Match]] = {} @@ -135,11 +228,14 @@ async def _request(self, url: str, params: dict[str, Any] | None = None) -> Any: session = await self._get_session() headers = {"X-Riot-Token": self.api_key} + endpoint = endpoint_name(url) for attempt in range(1, self.MAX_RETRIES + 1): - await self.limiter.acquire() + self.stats.limiter_wait_s += await self.limiter.acquire() + started = time.monotonic() try: result = await self._get_once(session, url, headers, params, attempt) except (TimeoutError, aiohttp.ClientError) as exc: + self.stats.record(endpoint, 0, (time.monotonic() - started) * 1000) raise RiotAPIError(0, f"Erreur réseau : {exc!r}") from exc if result is not _RETRY: return result @@ -154,7 +250,11 @@ async def _get_once( params: dict[str, Any] | None, attempt: int, ) -> Any: + started = time.monotonic() async with session.get(url, headers=headers, params=params) as resp: + self.stats.record( + endpoint_name(url), resp.status, (time.monotonic() - started) * 1000, resp.headers + ) if resp.status == 200: return await resp.json() if resp.status == 429: diff --git a/tests/test_riot_api.py b/tests/test_riot_api.py index 2a0fb11..efb66d6 100644 --- a/tests/test_riot_api.py +++ b/tests/test_riot_api.py @@ -245,3 +245,60 @@ async def test_cache_limite_en_taille(monkeypatch) -> None: await riot.get_match("EUW1_100") # le plus ancien a été évincé assert riot.calls["match_detail"] == 4 + + +# ── Statistiques d'utilisation (ligne RIOT du journal) ───── +@pytest.mark.parametrize( + "url, name", + [ + ( + "https://europe.api.riotgames.com/riot/account/v1/accounts/by-riot-id/A/EUW", + "account-v1 by-riot-id", + ), + ("https://europe.api.riotgames.com/riot/account/v1/accounts/by-puuid/p", "account-v1 by-puuid"), + ("https://euw1.api.riotgames.com/lol/league/v4/entries/by-puuid/p", "league-v4"), + ("https://europe.api.riotgames.com/lol/match/v5/matches/by-puuid/p/ids?count=5", "match-v5 ids"), + ("https://europe.api.riotgames.com/lol/match/v5/matches/EUW1_1", "match-v5 match"), + ], +) +def test_endpoint_name(url, name) -> None: + assert riot_api.endpoint_name(url) == name + + +def test_stats_quotas_et_remise_a_zero() -> None: + stats = riot_api.RiotStats() + headers = { + "X-App-Rate-Limit": "20:1,100:120", + "X-App-Rate-Limit-Count": "3:1,45:120", + "X-Method-Rate-Limit": "2000:10", + "X-Method-Rate-Limit-Count": "7:10", + } + stats.record("match-v5 match", 200, 120.0, headers) + stats.record("match-v5 match", 404, 80.0, {}) + stats.record("league-v4", 429, 50.0, {"Retry-After": "3", "X-Rate-Limit-Type": "application"}) + snap = stats.snapshot() + assert snap["requests"] == 3 and snap["status"] == {"200": 1, "404": 1, "429": 1} + assert snap["endpoints"]["match-v5 match"] == {"n": 2, "errors": 1, "avg_ms": 100} + assert (snap["app_limit"], snap["app_count"]) == ("20:1,100:120", "3:1,45:120") + assert snap["method"]["match-v5 match"] == {"limit": "2000:10", "count": "7:10"} + assert snap["rate_limited"] == {"application": 1} and snap["retry_after_s"] == 3 + again = stats.snapshot() + assert again["requests"] == 0 and again["app_limit"] == "20:1,100:120" # les quotas connus restent + + +async def test_requetes_comptees(server, client) -> None: + await client._request(server["base"] + "/ok") + with pytest.raises(RiotAPIError): + await client._request(server["base"] + "/not-found") + snap = client.stats.snapshot() + assert snap["requests"] == 2 and snap["status"] == {"200": 1, "404": 1} + + +async def test_attente_du_limiteur_comptee(server) -> None: + c = RiotAPI("KEY", rate_limits=[(1, 0.2)]) + try: + await c._request(server["base"] + "/ok") + await c._request(server["base"] + "/ok") + assert c.stats.snapshot()["limiter_wait_s"] >= 0.1 + finally: + await c.close()