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
66 changes: 66 additions & 0 deletions audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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),
Expand Down
18 changes: 11 additions & 7 deletions cogs/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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."))
Expand All @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion cogs/prefix.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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)
Expand Down
13 changes: 8 additions & 5 deletions embeds/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

from PIL import Image, ImageDraw, ImageFont

import audit

from . import utils
from .utils import (
DDRAGON_CHAMPION_ICON,
Expand Down Expand Up @@ -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)
Expand Down
8 changes: 6 additions & 2 deletions riot_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import aiohttp

import audit
from models import Match

logger = logging.getLogger("botdiff.riot_api")
Expand Down Expand Up @@ -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
Expand Down
34 changes: 33 additions & 1 deletion tests/test_audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down Expand Up @@ -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
3 changes: 2 additions & 1 deletion tests/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
9 changes: 9 additions & 0 deletions tests/test_riot_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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