Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion audit.py
Original file line number Diff line number Diff line change
@@ -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.
"""

Expand Down Expand Up @@ -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 "?"
18 changes: 17 additions & 1 deletion bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

from __future__ import annotations

import asyncio
import logging
from typing import Any

import discord
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
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand Down
10 changes: 10 additions & 0 deletions docs/fonctionnement.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
106 changes: 103 additions & 3 deletions riot_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""
Expand Down Expand Up @@ -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()
Expand All @@ -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:
Expand All @@ -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]] = {}
Expand All @@ -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
Expand All @@ -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:
Expand Down
57 changes: 57 additions & 0 deletions tests/test_riot_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()