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
19 changes: 14 additions & 5 deletions cogs/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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])
Expand All @@ -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)

Expand All @@ -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)
)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions cogs/tracking.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,15 @@ 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:
return await self._get(("match", match_id), lambda: self.bot.riot.get_match(match_id))

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
Expand Down
49 changes: 47 additions & 2 deletions riot_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]] = {}
Expand Down Expand Up @@ -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):
Expand Down
10 changes: 6 additions & 4 deletions services.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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)
71 changes: 71 additions & 0 deletions tests/test_perf.py
Original file line number Diff line number Diff line change
@@ -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