diff --git a/audit.py b/audit.py index 8690830..6b2fb23 100644 --- a/audit.py +++ b/audit.py @@ -35,13 +35,35 @@ def command_options(interaction: Any, extra: dict[str, Any] | None = None) -> di return {k: _value(v) for k, v in raw.items() if not k.startswith("_")} -def _elapsed_ms(interaction: Any, started: float | None) -> int | None: - if started is not None: - return round((time.monotonic() - started) * 1000) +RECEIVED = "botdiff_received" # instant (monotonic) où le bot a reçu la commande +DISCORD_MS = "botdiff_discord_ms" # délai entre le clic (côté Discord) et la réception par le bot + + +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() + created = getattr(interaction, "created_at", None) + if isinstance(created, datetime): + extras[DISCORD_MS] = max(0, round((datetime.now(UTC) - created).total_seconds() * 1000)) + + +def _timings(interaction: Any, started: float | None) -> dict[str, int | None]: + """ms : durée totale vue par l'utilisateur quand on la connaît (sinon le traitement) ; + bot_ms : traitement par le bot, réponse comprise ; discord_ms : délai avant réception.""" + extras = getattr(interaction, "extras", None) + extras = extras if isinstance(extras, dict) else {} + received = started if started is not None else extras.get(RECEIVED) + bot_ms = round((time.monotonic() - received) * 1000) if received is not None else None + discord_ms = extras.get(DISCORD_MS) created = getattr(interaction, "created_at", None) if isinstance(created, datetime): - return max(0, round((datetime.now(UTC) - created).total_seconds() * 1000)) - return None + total = max(0, round((datetime.now(UTC) - created).total_seconds() * 1000)) + else: + total = bot_ms + return {"ms": total, "bot_ms": bot_ms, "discord_ms": discord_ms} def log_command( @@ -61,7 +83,7 @@ def log_command( "cmd": command, "src": source, "status": status, - "ms": _elapsed_ms(interaction, started), + **_timings(interaction, started), "guild_id": getattr(interaction, "guild_id", None), "guild": getattr(guild, "name", None), "user_id": getattr(user, "id", None), diff --git a/bot.py b/bot.py index 1ce57d0..c3fd086 100644 --- a/bot.py +++ b/bot.py @@ -10,7 +10,7 @@ from discord import app_commands from discord.ext import commands -from audit import command_name, log_command, log_riot +from audit import command_name, log_command, log_riot, mark_received from database import Database from embeds import utils as embed_utils from embeds.views import MatchDetailsButton, ProfileButton @@ -48,6 +48,7 @@ async def setup_hook(self) -> None: # Boutons persistants : fonctionnent encore après un redémarrage. self.add_dynamic_items(ProfileButton, MatchDetailsButton) await self.tree.set_translator(CommandTranslator()) + self.tree.interaction_check = self._mark_received # type: ignore[method-assign] await self.tree.sync() logger.info("Commandes slash synchronisées.") self._riot_stats_task = asyncio.create_task(self._publish_riot_stats()) @@ -62,6 +63,12 @@ async def _publish_riot_stats(self) -> None: except Exception: # la publication ne doit jamais arrêter le bot logger.exception("Statistiques API Riot non publiées") + @staticmethod + async def _mark_received(interaction: discord.Interaction) -> bool: + """Premier point de passage d'une commande slash : on note l'heure de réception (mesure des durées).""" + mark_received(interaction) + return True + async def on_app_command_completion( self, interaction: discord.Interaction, command: app_commands.Command | app_commands.ContextMenu ) -> None: diff --git a/cogs/prefix.py b/cogs/prefix.py index 203b5d3..ffcfe70 100644 --- a/cogs/prefix.py +++ b/cogs/prefix.py @@ -25,7 +25,7 @@ if TYPE_CHECKING: from bot import BotDiff -from audit import command_name, log_command # noqa: E402 +from audit import RECEIVED, command_name, log_command # noqa: E402 logger = logging.getLogger("botdiff.prefix") @@ -57,6 +57,7 @@ def __init__(self, bot: BotDiff, message: discord.Message, command: app_commands self.permissions = getattr(message.author, "guild_permissions", discord.Permissions.none()) self.command = command self.namespace = types.SimpleNamespace() + self.extras: dict[str, Any] = {} self._replied = False self._deferred = False self.response = _Response(self) @@ -256,6 +257,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 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/docs/fonctionnement.md b/docs/fonctionnement.md index 6ddc86f..f023d0d 100644 --- a/docs/fonctionnement.md +++ b/docs/fonctionnement.md @@ -126,6 +126,7 @@ EVT {"type":"match_alert","match_id":"EUW1_123","guild_id":1,"players":"['Bob#EU ``` - `src` : `slash` ou `prefix` (commandes « $ »). +- Durées : `ms` est la durée totale vue par l'utilisateur (du clic à la réponse), `bot_ms` le traitement par le bot (réponse comprise), `discord_ms` le délai entre le clic et la réception par le bot (commandes slash uniquement). - `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). diff --git a/tests/test_audit.py b/tests/test_audit.py index 426c68a..9081195 100644 --- a/tests/test_audit.py +++ b/tests/test_audit.py @@ -62,3 +62,29 @@ async def test_prefix_success_and_error(caplog, prefix) -> None: # noqa: F811 ok, err = records(caplog) assert (ok["cmd"], ok["src"], ok["status"]) == ("list", "prefix", "ok") and ok["ms"] is not None assert (err["cmd"], err["src"], err["status"]) == ("history", "prefix", "user_error") + + +async def test_durees_separees_discord_et_bot(caplog, bot) -> None: + import asyncio + from datetime import UTC, datetime, timedelta + + from audit import mark_received + + caplog.set_level(logging.INFO, "botdiff.audit") + it = FakeInteraction(bot) + it.extras = {} + it.created_at = datetime.now(UTC) - timedelta(milliseconds=300) # clic 300 ms avant la réception + mark_received(it) + await asyncio.sleep(0.05) # traitement + log_command(it, "goal all", source="slash") + (cmd,) = records(caplog) + assert 250 <= cmd["discord_ms"] <= 400 + assert 50 <= cmd["bot_ms"] < 250 + assert cmd["ms"] >= cmd["discord_ms"] + cmd["bot_ms"] - 5 + + +async def test_prefix_mesure_le_traitement_meme_en_erreur(caplog, prefix) -> None: # noqa: F811 + caplog.set_level(logging.INFO, "botdiff.audit") + 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