From a4c23067b46f641cf630fd3a9377e8a61c5e2971 Mon Sep 17 00:00:00 2001 From: "mateo.gayrard" Date: Thu, 3 Dec 2026 12:31:55 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20d=C3=A9tail=20des=20=C3=A9tapes=20de=20?= =?UTF-8?q?chaque=20commande=20(Riot,=20Data=20Dragon,=20pr=C3=A9paration,?= =?UTF-8?q?=20envoi)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ligne CMD : phases = riot_ms et riot_calls (durée réelle, requêtes parallèles comptées une fois), limiter_ms, ddragon_ms et ddragon_calls (icônes), build_ms (préparation de la réponse) et send_ms (envoi à Discord) pour /profile et /history - étapes partagées avec les sous-tâches via contextvars - test du récap de session rendu stable : la phrase d'accroche tirée au hasard peut citer les LP Co-Authored-By: Claude Opus 5.5 --- audit.py | 66 ++++++++++++++++++++++++++++++++++++++++++ cogs/commands.py | 18 +++++++----- cogs/prefix.py | 3 +- embeds/images.py | 13 +++++---- riot_api.py | 8 +++-- tests/test_audit.py | 34 +++++++++++++++++++++- tests/test_commands.py | 3 +- tests/test_riot_api.py | 9 ++++++ 8 files changed, 137 insertions(+), 17 deletions(-) diff --git a/audit.py b/audit.py index 6b2fb23..fb244f5 100644 --- a/audit.py +++ b/audit.py @@ -11,6 +11,9 @@ import json import logging import time +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar from datetime import UTC, datetime from typing import Any @@ -39,12 +42,74 @@ def command_options(interaction: Any, extra: dict[str, Any] | None = None) -> di DISCORD_MS = "botdiff_discord_ms" # délai entre le clic (côté Discord) et la réception par le bot +PHASES = "botdiff_phases" +# Étapes de la commande en cours (Riot, Data Dragon, préparation, envoi). Le dictionnaire est partagé +# avec les sous-tâches (asyncio.gather copie le contexte, pas le dictionnaire). +_phases: ContextVar[dict[str, Any] | None] = ContextVar("botdiff_phases", default=None) + + +def start_phases(interaction: Any) -> None: + extras = getattr(interaction, "extras", None) + phases: dict[str, Any] = {} + if isinstance(extras, dict): + extras[PHASES] = phases + _phases.set(phases) + + +@contextmanager +def timed(name: str) -> Iterator[None]: + """Durée d'une étape séquentielle de la commande en cours (ex. préparation, envoi).""" + phases = _phases.get() + started = time.monotonic() + try: + yield + finally: + if phases is not None: + phases[f"{name}_ms"] = phases.get(f"{name}_ms", 0) + (time.monotonic() - started) * 1000 + + +@contextmanager +def waiting(name: str) -> Iterator[None]: + """Temps passé à attendre un service externe : requêtes parallèles comptées une seule fois (durée réelle).""" + phases = _phases.get() + if phases is None: + yield + return + inflight = f"_{name}_inflight" + if not phases.get(inflight): + phases[f"_{name}_since"] = time.monotonic() + phases[inflight] = phases.get(inflight, 0) + 1 + phases[f"{name}_calls"] = phases.get(f"{name}_calls", 0) + 1 + try: + yield + finally: + phases[inflight] -= 1 + if not phases[inflight]: + elapsed = (time.monotonic() - phases[f"_{name}_since"]) * 1000 + phases[f"{name}_ms"] = phases.get(f"{name}_ms", 0) + elapsed + + +def add_phase(name: str, ms: float) -> None: + phases = _phases.get() + if phases is not None: + phases[f"{name}_ms"] = phases.get(f"{name}_ms", 0) + ms + + +def _public_phases(interaction: Any) -> dict[str, int]: + extras = getattr(interaction, "extras", None) + phases = extras.get(PHASES) if isinstance(extras, dict) else None + if not phases: + return {} + return {k: round(v) for k, v in phases.items() if not k.startswith("_") and isinstance(v, int | float)} + + def mark_received(interaction: Any) -> None: """À appeler dès la réception d'une commande : sépare le délai Discord du temps de traitement du bot.""" extras = getattr(interaction, "extras", None) if not isinstance(extras, dict) or RECEIVED in extras: return extras[RECEIVED] = time.monotonic() + start_phases(interaction) created = getattr(interaction, "created_at", None) if isinstance(created, datetime): extras[DISCORD_MS] = max(0, round((datetime.now(UTC) - created).total_seconds() * 1000)) @@ -84,6 +149,7 @@ def log_command( "src": source, "status": status, **_timings(interaction, started), + "phases": _public_phases(interaction), "guild_id": getattr(interaction, "guild_id", None), "guild": getattr(guild, "name", None), "user_id": getattr(user, "id", None), diff --git a/cogs/commands.py b/cogs/commands.py index d4d600b..93f30b5 100644 --- a/cogs/commands.py +++ b/cogs/commands.py @@ -50,7 +50,7 @@ if TYPE_CHECKING: from bot import BotDiff -from audit import command_name, log_command # noqa: E402 +from audit import command_name, log_command, timed # noqa: E402 logger = logging.getLogger("botdiff.commands") @@ -326,8 +326,10 @@ async def history( own, tag = self._own_or_tracked_tag(interaction, riot_id, tag) await interaction.response.defer(thinking=True) player = own or await self._player(interaction, riot_id or "", tag or "") - embeds, files, view = await load_history(self.bot.riot, player, self.lang(interaction)) - await interaction.followup.send(embeds=embeds, files=files, view=view) + with timed("build"): + embeds, files, view = await load_history(self.bot.riot, player, self.lang(interaction)) + with timed("send"): + await interaction.followup.send(embeds=embeds, files=files, view=view) @app_commands.guild_only() @app_commands.command(name="profile", description=_("Show a player's full profile and stats.")) @@ -338,10 +340,12 @@ async def profile( own, tag = self._own_or_tracked_tag(interaction, riot_id, tag) await interaction.response.defer(thinking=True) player = own or await self._player(interaction, riot_id or "", tag or "") - embeds, files, view = await load_profile( - self.bot.riot, self.bot.platform, player, self.lang(interaction) - ) - await interaction.followup.send(embeds=embeds, files=files, view=view) + with timed("build"): + embeds, files, view = await load_profile( + self.bot.riot, self.bot.platform, player, self.lang(interaction) + ) + with timed("send"): + await interaction.followup.send(embeds=embeds, files=files, view=view) # ── Objectifs de rang ─────────────────────────────────── # Une seule commande avec une action, pour ne pas encombrer la liste des commandes de Discord. diff --git a/cogs/prefix.py b/cogs/prefix.py index ffcfe70..5859cef 100644 --- a/cogs/prefix.py +++ b/cogs/prefix.py @@ -25,7 +25,7 @@ if TYPE_CHECKING: from bot import BotDiff -from audit import RECEIVED, command_name, log_command # noqa: E402 +from audit import RECEIVED, command_name, log_command, start_phases # noqa: E402 logger = logging.getLogger("botdiff.prefix") @@ -258,6 +258,7 @@ async def run(self, message: discord.Message, command: app_commands.Command, tex cog = command.binding started = time.monotonic() interaction.extras[RECEIVED] = started # mesure aussi la durée des commandes en erreur + start_phases(interaction) try: await command.callback(cog, interaction, **kwargs) # type: ignore[arg-type] log_command(interaction, command_name(command), source="prefix", started=started, options=kwargs) diff --git a/embeds/images.py b/embeds/images.py index 690ceef..849e0ac 100644 --- a/embeds/images.py +++ b/embeds/images.py @@ -14,6 +14,8 @@ from PIL import Image, ImageDraw, ImageFont +import audit + from . import utils from .utils import ( DDRAGON_CHAMPION_ICON, @@ -65,11 +67,12 @@ async def download_image(url: str) -> Image.Image | None: _image_cache.move_to_end(url) return cached try: - async with utils.get_session().get(url) as resp: - if resp.status != 200: - logger.warning("Image introuvable (%s) : %s", resp.status, url) - return None - data = await resp.read() + with audit.waiting("ddragon"): + async with utils.get_session().get(url) as resp: + if resp.status != 200: + logger.warning("Image introuvable (%s) : %s", resp.status, url) + return None + data = await resp.read() img = Image.open(io.BytesIO(data)).convert("RGBA") except Exception as exc: logger.warning("Impossible de télécharger l'image %s : %s", url, exc) diff --git a/riot_api.py b/riot_api.py index 645b4a0..dd936c7 100644 --- a/riot_api.py +++ b/riot_api.py @@ -17,6 +17,7 @@ import aiohttp +import audit from models import Match logger = logging.getLogger("botdiff.riot_api") @@ -235,10 +236,13 @@ async def _request(self, url: str, params: dict[str, Any] | None = None) -> Any: endpoint = endpoint_name(url) for attempt in range(1, self.MAX_RETRIES + 1): - self.stats.limiter_wait_s += await self.limiter.acquire() + waited = await self.limiter.acquire() + self.stats.limiter_wait_s += waited + audit.add_phase("limiter", waited * 1000) started = time.monotonic() try: - result = await self._get_once(session, url, headers, params, attempt) + with audit.waiting("riot"): + 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 diff --git a/tests/test_audit.py b/tests/test_audit.py index 9081195..8298aec 100644 --- a/tests/test_audit.py +++ b/tests/test_audit.py @@ -10,7 +10,7 @@ from audit import command_options, log_command, log_event -from .conftest import FakeInteraction, invoke +from .conftest import FakeInteraction, invoke # noqa: F401 from .test_prefix import prefix, send # noqa: F401 (fixture réutilisée) @@ -88,3 +88,35 @@ async def test_prefix_mesure_le_traitement_meme_en_erreur(caplog, prefix) -> Non await send(prefix, "$history Nobody") (err,) = records(caplog) assert err["status"] == "user_error" and err["bot_ms"] is not None and err["discord_ms"] is None + + +async def test_detail_par_etape_d_un_profil(caplog, tracked_bot, cmds) -> None: + from audit import mark_received + + caplog.set_level(logging.INFO, "botdiff.audit") + it = FakeInteraction(tracked_bot) + it.extras = {} + mark_received(it) + await invoke(cmds, cmds.profile, it, "Alice", None) + log_command(it, "profile", source="slash") + (cmd,) = records(caplog) + phases = cmd["phases"] + assert "build_ms" in phases and "send_ms" in phases # le faux client Riot ne passe pas par HTTP + assert not any(k.startswith("_") for k in phases) # compteurs internes non publiés + + +async def test_requetes_paralleles_comptees_une_fois() -> None: + import asyncio + + from audit import _phases, waiting + + phases: dict = {} + _phases.set(phases) + + async def call(): + with waiting("riot"): + await asyncio.sleep(0.05) + + await asyncio.gather(*(call() for _ in range(5))) + assert phases["riot_calls"] == 5 + assert 40 <= phases["riot_ms"] < 150 # durée réelle, pas 5 × 50 ms diff --git a/tests/test_commands.py b/tests/test_commands.py index 2f649ad..60b112a 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -225,7 +225,8 @@ async def test_test_alert_recap_de_session(bot, cmds, riot, monkeypatch) -> None assert embed.description.split("\n")[0] in variants_of( "session_bad", player="Alice#EUW", wins=1, losses=2 ) - assert "✅❌❌" in embed.description and "LP" not in embed.description + details = "\n".join(embed.description.split("\n")[1:]) # la phrase d'accroche peut citer les LP + assert "✅❌❌" in details and "LP" not in details def test_permissions() -> None: diff --git a/tests/test_riot_api.py b/tests/test_riot_api.py index efb66d6..55efa38 100644 --- a/tests/test_riot_api.py +++ b/tests/test_riot_api.py @@ -302,3 +302,12 @@ async def test_attente_du_limiteur_comptee(server) -> None: assert c.stats.snapshot()["limiter_wait_s"] >= 0.1 finally: await c.close() + + +async def test_appels_riot_comptes_dans_la_commande_en_cours(server, client) -> None: + from audit import _phases + + phases: dict = {} + _phases.set(phases) + await client._request(server["base"] + "/ok") + assert phases["riot_calls"] == 1 and phases["riot_ms"] >= 0 and "limiter_ms" in phases