From 39aecf5cd9d6eed69cf700a620bc2a051bbc3645 Mon Sep 17 00:00:00 2001 From: "mateo.gayrard" Date: Thu, 3 Dec 2026 12:14:30 +0100 Subject: [PATCH] perf: /profile, /history et /match plus rapides pour les joueurs suivis MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - joueur suivi : PUUID lu en base, plus d'appel Account-V1 en série avant le reste - derniers matchs, rang et profil gardés en mémoire ; les commandes acceptent des données de moins de 150 s (la boucle de suivi les rafraîchit toutes les 2 min), la boucle elle interroge toujours Riot (détection des parties inchangée) - liste de matchs fusionnée quand la boucle ne demande que les 5 derniers, liste courte (moins de parties que demandé) reconnue comme complète - tests (tests/test_perf.py) Co-Authored-By: Claude Opus 5.5 --- cogs/commands.py | 19 +++++++++---- cogs/tracking.py | 4 +-- riot_api.py | 49 ++++++++++++++++++++++++++++++-- services.py | 10 ++++--- tests/test_perf.py | 71 ++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 140 insertions(+), 13 deletions(-) create mode 100644 tests/test_perf.py diff --git a/cogs/commands.py b/cogs/commands.py index b252c8f..43f97e0 100644 --- a/cogs/commands.py +++ b/cogs/commands.py @@ -37,6 +37,7 @@ from models import PlayerRef from ranks import APEX_TIERS, Rank, find_solo_queue from services import ( + COMMAND_CACHE_S, UserFacingError, load_history, load_profile, @@ -268,8 +269,8 @@ async def language(self, interaction: discord.Interaction, language: app_command async def test_alert(self, interaction: discord.Interaction, riot_id: str, tag: str) -> None: lang = self.lang(interaction) await interaction.response.defer(thinking=True) - player = await resolve_player(self.bot.riot, riot_id, tag) - match_ids = await self.bot.riot.get_match_ids(player.puuid, count=1) + player = await self._player(interaction, riot_id, tag) + match_ids = await self.bot.riot.recent_match_ids(player.puuid, 1, COMMAND_CACHE_S) if not match_ids: raise UserFacingError("no_recent_game", player=player.display) match = await self.bot.riot.get_match(match_ids[0]) @@ -292,7 +293,7 @@ async def history( ) -> None: own, tag = self._own_or_tracked_tag(interaction, riot_id, tag) await interaction.response.defer(thinking=True) - player = own or await resolve_player(self.bot.riot, riot_id or "", tag or "") + 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) @@ -304,7 +305,7 @@ async def profile( ) -> None: own, tag = self._own_or_tracked_tag(interaction, riot_id, tag) await interaction.response.defer(thinking=True) - player = own or await resolve_player(self.bot.riot, riot_id or "", tag or "") + 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) ) @@ -382,7 +383,7 @@ async def _goal_set( target = target_label(tier, target_division) await interaction.response.defer(thinking=True) - entries = await self.bot.riot.get_league_entries_by_puuid(self.bot.platform, player.puuid) + entries = await self.bot.riot.league_entries(self.bot.platform, player.puuid, COMMAND_CACHE_S) solo = find_solo_queue(entries) current = Rank(solo["tier"], solo["rank"], solo.get("leaguePoints")) if solo else None if current is not None: @@ -525,6 +526,14 @@ def _own_or_tracked_tag( ) return accounts[0].ref, None + async def _player(self, interaction: discord.Interaction, riot_id: str, tag: str) -> PlayerRef: + """Joueur suivi sur ce serveur : PUUID depuis la base (pas d'appel Riot). Sinon : demandé à Riot.""" + if interaction.guild_id is not None and tag: + tracked = self.bot.db.find_player(riot_id, tag, interaction.guild_id) + if tracked is not None: + return tracked.ref + return await resolve_player(self.bot.riot, riot_id, tag) + def _tracked_player(self, guild_id: int, riot_id: str, tag: str | None) -> TrackedPlayer: tag = self._tracked_tag(guild_id, riot_id, tag) player = self.bot.db.find_player(riot_id, tag, guild_id) diff --git a/cogs/tracking.py b/cogs/tracking.py index 1f64fdc..4394d57 100644 --- a/cogs/tracking.py +++ b/cogs/tracking.py @@ -64,7 +64,7 @@ async def _get(self, key: tuple[str, str], fetch: Callable[[], Awaitable[Any]]) async def match_ids(self, puuid: str) -> list[str]: return await self._get( - ("ids", puuid), lambda: self.bot.riot.get_match_ids(puuid, count=RECENT_MATCH_COUNT) + ("ids", puuid), lambda: self.bot.riot.recent_match_ids(puuid, RECENT_MATCH_COUNT) ) async def match(self, match_id: str) -> Match: @@ -72,7 +72,7 @@ async def match(self, match_id: str) -> Match: async def solo_rank(self, puuid: str) -> Rank | None: async def fetch() -> Rank | None: - entries = await self.bot.riot.get_league_entries_by_puuid(self.bot.platform, puuid) + entries = await self.bot.riot.league_entries(self.bot.platform, puuid) solo = find_solo_queue(entries) if solo is None: return None diff --git a/riot_api.py b/riot_api.py index 9de63a1..645b4a0 100644 --- a/riot_api.py +++ b/riot_api.py @@ -8,8 +8,10 @@ import asyncio import logging +import math import time from collections import OrderedDict, deque +from collections.abc import Awaitable, Callable from typing import Any from urllib.parse import quote @@ -210,6 +212,9 @@ def __init__( 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() + # Données récentes réutilisables par les commandes (alimentées aussi par la boucle de suivi) + self._ids_cache: dict[str, tuple[float, list[str], float]] = {} # (instant, ids, nb couverts) + self._ttl_cache: dict[tuple[str, ...], tuple[float, Any]] = {} self._session: aiohttp.ClientSession | None = None self._match_cache: OrderedDict[str, Match] = OrderedDict() self._match_pending: dict[str, asyncio.Future[Match]] = {} @@ -322,9 +327,49 @@ async def _fetch_match(self, match_id: str) -> Match: self._match_cache.popitem(last=False) return match - async def get_recent_matches(self, puuid: str, count: int) -> list[Match]: + # ── Données récentes en cache ─────────────────────────── + # max_age = 0 : toujours interroger Riot (et mettre à jour le cache) ; c'est le cas de la boucle de suivi. + # Les commandes passent max_age > 0 et réutilisent ce que la boucle vient de récupérer. + + async def recent_match_ids(self, puuid: str, count: int, max_age: float = 0.0) -> list[str]: + """Les `count` derniers matchs (du plus récent au plus ancien).""" + now = time.monotonic() + hit = self._ids_cache.get(puuid) + if max_age and hit and now - hit[0] <= max_age and hit[2] >= count: + return hit[1][:count] + ids = await self.get_match_ids(puuid, count=count) + # Moins de matchs que demandé : la liste est complète, elle répond à toute demande + covers = len(ids) if len(ids) >= count else math.inf + known = hit[1] if hit else [] + if covers != math.inf and ids and ids[-1] in known: + # la nouvelle liste recouvre l'ancienne : on garde les plus anciens déjà connus au-delà + older = [mid for mid in known[known.index(ids[-1]) + 1 :] if mid not in ids] + ids = ids + older + covers = len(ids) if hit[2] != math.inf else math.inf + self._ids_cache[puuid] = (time.monotonic(), ids, covers) + return ids[:count] + + async def _cached(self, key: tuple[str, ...], max_age: float, fetch: Callable[[], Awaitable[Any]]) -> Any: + hit = self._ttl_cache.get(key) + if max_age and hit and time.monotonic() - hit[0] <= max_age: + return hit[1] + value = await fetch() + self._ttl_cache[key] = (time.monotonic(), value) + return value + + async def league_entries(self, platform: str, puuid: str, max_age: float = 0.0) -> list[dict[str, Any]]: + return await self._cached( + ("league", platform, puuid), max_age, lambda: self.get_league_entries_by_puuid(platform, puuid) + ) + + async def summoner(self, platform: str, puuid: str, max_age: float = 0.0) -> dict[str, Any]: + return await self._cached( + ("summoner", platform, puuid), max_age, lambda: self.get_summoner_by_puuid(platform, puuid) + ) + + async def get_recent_matches(self, puuid: str, count: int, max_age: float = 0.0) -> list[Match]: """Les `count` dernières parties d'un joueur (celles en erreur sont ignorées).""" - match_ids = await self.get_match_ids(puuid, count=count) + match_ids = await self.recent_match_ids(puuid, count, max_age) results = await asyncio.gather(*(self.get_match(mid) for mid in match_ids), return_exceptions=True) matches = [] for mid, res in zip(match_ids, results, strict=True): diff --git a/services.py b/services.py index 93c8930..fc11015 100644 --- a/services.py +++ b/services.py @@ -16,6 +16,8 @@ logger = logging.getLogger("botdiff.services") PROFILE_MATCH_COUNT = 10 +# Âge maximal des données Riot réutilisées par les commandes (la boucle de suivi les rafraîchit toutes les 2 min) +COMMAND_CACHE_S = 150 HISTORY_MATCH_COUNT = 5 Message = tuple[list[discord.Embed], list[discord.File], discord.ui.View] @@ -65,16 +67,16 @@ async def load_profile( riot: RiotAPI, platform: str, player: PlayerRef, lang: str = DEFAULT_LANGUAGE ) -> Message: summoner, league_entries, matches = await asyncio.gather( - riot.get_summoner_by_puuid(platform, player.puuid), - riot.get_league_entries_by_puuid(platform, player.puuid), - riot.get_recent_matches(player.puuid, PROFILE_MATCH_COUNT), + riot.summoner(platform, player.puuid, COMMAND_CACHE_S), + riot.league_entries(platform, player.puuid, COMMAND_CACHE_S), + riot.get_recent_matches(player.puuid, PROFILE_MATCH_COUNT, COMMAND_CACHE_S), ) embed, files, view = await build_profile_embed(player, summoner, league_entries, matches, lang) return [embed], files, view async def load_history(riot: RiotAPI, player: PlayerRef, lang: str = DEFAULT_LANGUAGE) -> Message: - matches = await riot.get_recent_matches(player.puuid, HISTORY_MATCH_COUNT) + matches = await riot.get_recent_matches(player.puuid, HISTORY_MATCH_COUNT, COMMAND_CACHE_S) if not matches: raise UserFacingError("no_recent_games", player=player.display) return await build_history_embed(player, matches, lang) diff --git a/tests/test_perf.py b/tests/test_perf.py new file mode 100644 index 0000000..2660b9b --- /dev/null +++ b/tests/test_perf.py @@ -0,0 +1,71 @@ +"""Commandes rapides : données Riot récentes réutilisées, pas d'appel inutile pour un joueur suivi.""" + +from __future__ import annotations + +import time + +from .conftest import PA, FakeInteraction, invoke + + +async def test_ids_en_cache_et_fusion(riot) -> None: + riot.match_ids[PA] = [f"EUW1_{i}" for i in range(20, 0, -1)] + assert await riot.recent_match_ids(PA, 10) == [f"EUW1_{i}" for i in range(20, 10, -1)] + assert riot.calls["match_ids"] == 1 + # une commande accepte des données récentes : pas de nouvel appel + assert len(await riot.recent_match_ids(PA, 5, max_age=60)) == 5 + assert riot.calls["match_ids"] == 1 + # la boucle de suivi (5 derniers, toujours frais) voit une nouvelle partie... + riot.match_ids[PA] = ["EUW1_21", *riot.match_ids[PA]] + assert await riot.recent_match_ids(PA, 5) == ["EUW1_21", "EUW1_20", "EUW1_19", "EUW1_18", "EUW1_17"] + # ...et le cache garde les plus anciens déjà connus : 10 derniers servis sans appel + assert await riot.recent_match_ids(PA, 10, max_age=60) == [f"EUW1_{i}" for i in range(21, 11, -1)] + assert riot.calls["match_ids"] == 2 + + +async def test_cache_perime_ou_trop_court(riot, monkeypatch) -> None: + riot.match_ids[PA] = [f"EUW1_{i}" for i in range(10, 0, -1)] + await riot.recent_match_ids(PA, 3) + await riot.recent_match_ids(PA, 5, max_age=60) # pas assez de matchs en cache + assert riot.calls["match_ids"] == 2 + real = time.monotonic + monkeypatch.setattr(time, "monotonic", lambda: real() + 120) + await riot.recent_match_ids(PA, 5, max_age=60) # trop vieux + assert riot.calls["match_ids"] == 3 + + +async def test_rang_en_cache(riot) -> None: + await riot.league_entries("euw1", PA) + await riot.league_entries("euw1", PA, max_age=60) + assert riot.calls["league"] == 1 + await riot.league_entries("euw1", PA) # max_age = 0 : toujours frais (boucle de suivi) + assert riot.calls["league"] == 2 + + +async def test_profil_d_un_joueur_suivi_sans_appel_account(tracked_bot, cmds, riot, monkeypatch) -> None: + puuid_calls = [] + + async def no_lookup(name, tag): + puuid_calls.append((name, tag)) + raise AssertionError("le PUUID d'un joueur suivi vient de la base") + + monkeypatch.setattr(riot, "get_puuid", no_lookup) + await invoke(cmds, cmds.profile, FakeInteraction(tracked_bot), "Alice", None) + await invoke(cmds, cmds.history, FakeInteraction(tracked_bot), "Alice", None) + assert puuid_calls == [] + + +async def test_commandes_reutilisent_la_boucle_de_suivi(tracked_bot, cmds, riot) -> None: + await riot.recent_match_ids(PA, 10) # comme la boucle de suivi + await riot.league_entries(tracked_bot.platform, PA) + before = dict(riot.calls) + await invoke(cmds, cmds.profile, FakeInteraction(tracked_bot), "Alice", None) + await invoke(cmds, cmds.history, FakeInteraction(tracked_bot), "Alice", None) + assert riot.calls["match_ids"] == before["match_ids"] and riot.calls["league"] == before["league"] + + +async def test_joueur_avec_peu_de_parties(riot) -> None: + riot.match_ids[PA] = ["EUW1_2", "EUW1_1"] + assert await riot.recent_match_ids(PA, 10) == ["EUW1_2", "EUW1_1"] + assert await riot.recent_match_ids(PA, 5, max_age=60) == ["EUW1_2", "EUW1_1"] + assert await riot.recent_match_ids(PA, 20, max_age=60) == ["EUW1_2", "EUW1_1"] + assert riot.calls["match_ids"] == 1 # liste complète : aucune relance