From 5ce8c777c4a1f931f389915e4d87a6afa59dc92b Mon Sep 17 00:00:00 2001 From: TO Date: Fri, 20 Nov 2026 21:08:35 +0100 Subject: [PATCH] Fetch Mastery Points from the Riot API and add the champion sort preference (#76) The tracker asks Riot for each Account's champion mastery (platform host) right after a successful sync, and after a Match fetched by id is added, so no new polling. Lists are stored per Account in one transaction and read back with Tracker::mastery (None = never fetched). A failed fetch keeps the last values and records no problem. Preferences gain champion_sort (mastery or name). Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- crates/core/src/config.rs | 49 +++ crates/core/src/follow.rs | 5 + crates/core/src/lib.rs | 2 +- crates/core/src/riot.rs | 74 ++++- crates/core/src/tracker.rs | 89 +++++- crates/core/tests/common/mod.rs | 50 +++ .../tests/fixtures/riot/champion_mastery.json | 34 ++ crates/core/tests/mastery.rs | 292 ++++++++++++++++++ 9 files changed, 593 insertions(+), 4 deletions(-) create mode 100644 crates/core/tests/fixtures/riot/champion_mastery.json create mode 100644 crates/core/tests/mastery.rs diff --git a/README.md b/README.md index 87e0093..893a52d 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ region = "europe" # facultatif, "europe" par défaut Le Compte connecté au client de League of Legends est suivi automatiquement. `riot_id` ne sert que de repli, quand le client est fermé au premier lancement. -L'application y écrit aussi ses préférences (`close_to_tray`, `theme`, `update_channel` : `stable` ou `beta`, absent tant que le canal de la version installée s'applique) et `tray_notice_shown`, qui passe à `true` une fois affichée la notification indiquant que la fenêtre fermée continue dans la zone de notification. Le remettre à `false` la fait réapparaître à la prochaine fermeture. +L'application y écrit aussi ses préférences (`close_to_tray`, `theme`, `update_channel` : `stable` ou `beta`, absent tant que le canal de la version installée s'applique, `champion_sort` : `mastery` ou `name`, absent tant que le joueur n'a pas choisi, le tri se faisant alors par points de maîtrise) et `tray_notice_shown`, qui passe à `true` une fois affichée la notification indiquant que la fenêtre fermée continue dans la zone de notification. Le remettre à `false` la fait réapparaître à la prochaine fermeture. La base des Parties, `arena-tracker.db`, est créée dans le même dossier, ainsi que `seasons.toml`, la table des Saisons : elle peut être modifiée, et les changements sont pris en compte au lancement suivant. La clé API ne doit jamais être commitée. diff --git a/crates/core/src/config.rs b/crates/core/src/config.rs index 922cc5f..59d538f 100644 --- a/crates/core/src/config.rs +++ b/crates/core/src/config.rs @@ -30,6 +30,9 @@ pub struct Preferences { /// `None` until the player chooses: the installed version's channel applies. #[serde(skip_serializing_if = "Option::is_none")] pub update_channel: Option, + /// `None` until the player chooses: the cards are sorted by Mastery Points. + #[serde(skip_serializing_if = "Option::is_none")] + pub champion_sort: Option, } impl Default for Preferences { @@ -38,6 +41,7 @@ impl Default for Preferences { close_to_tray: true, theme: ThemePreference::System, update_channel: None, + champion_sort: None, } } } @@ -51,6 +55,15 @@ pub enum ThemePreference { Dark, } +/// How the champion cards are ordered. Saved only when chosen: without a choice the sort is by +/// Mastery Points (`Mastery`), highest first; `Name` is A to Z. +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum ChampionSort { + Mastery, + Name, +} + /// The releases an installation follows. Saved only when chosen in the settings: installing or /// updating to a beta never changes a saved choice. #[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] @@ -138,6 +151,41 @@ mod tests { assert!(config.preferences.close_to_tray); assert_eq!(config.preferences.theme, ThemePreference::System); assert_eq!(config.preferences.update_channel, None); + assert_eq!(config.preferences.champion_sort, None); + } + + #[test] + fn the_champion_sort_is_saved_only_once_chosen() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + let mut config = Config::load_or_default(&path).unwrap(); + config.preferences.theme = ThemePreference::Dark; + config.save(&path).unwrap(); + assert!( + !std::fs::read_to_string(&path) + .unwrap() + .contains("champion_sort") + ); + assert_eq!(Config::load(&path).unwrap().preferences.champion_sort, None); + + config.preferences.champion_sort = Some(ChampionSort::Name); + config.save(&path).unwrap(); + assert!( + std::fs::read_to_string(&path) + .unwrap() + .contains("champion_sort = \"name\"") + ); + assert_eq!( + Config::load(&path).unwrap().preferences.champion_sort, + Some(ChampionSort::Name) + ); + assert_eq!( + load("champion_sort = \"mastery\"\n") + .unwrap() + .preferences + .champion_sort, + Some(ChampionSort::Mastery) + ); } #[test] @@ -211,6 +259,7 @@ mod tests { close_to_tray: false, theme: ThemePreference::Dark, update_channel: Some(UpdateChannel::Beta), + champion_sort: Some(ChampionSort::Name), }; config.save(&path).unwrap(); assert!( diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs index 6870462..23aa7b7 100644 --- a/crates/core/src/follow.rs +++ b/crates/core/src/follow.rs @@ -424,6 +424,8 @@ impl Tracker { if report.added > 0 { self.follow().pending.retain(|p| p.game_id.is_some()); } + // Riot has just answered for this Account: one more request for its points. + self.refresh_mastery(&report.account.puuid); Ok(report) } Err(e) => Err(self.record(UpdateProblem::from(&e))), @@ -476,6 +478,9 @@ impl Tracker { Ok(fetched) => { let added = usize::from(fetched == Fetched::Added); self.clear_problem(added); + if added > 0 { + self.refresh_mastery(&account.puuid); + } (added, fetched != Fetched::NotFound) } Err(e) => { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index effa473..55fb112 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -18,7 +18,7 @@ pub use champ_select::{ChampSelect, ChampSelectReader}; pub use champion_search::ChampionSearch; pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon}; pub use client::{ClientError, ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow}; -pub use config::{Config, Preferences, ThemePreference, UpdateChannel, data_dir}; +pub use config::{ChampionSort, Config, Preferences, ThemePreference, UpdateChannel, data_dir}; pub use date::Date; pub use error::{Error, SourceError}; pub use follow::{ diff --git a/crates/core/src/riot.rs b/crates/core/src/riot.rs index 9b22058..67fc6ba 100644 --- a/crates/core/src/riot.rs +++ b/crates/core/src/riot.rs @@ -3,6 +3,7 @@ use std::sync::{Mutex, PoisonError}; use std::thread; use std::time::{Duration, Instant}; +use serde::Deserialize; use ureq::{Agent, Body}; use crate::error::SourceError; @@ -42,6 +43,10 @@ impl RiotApi { } fn get(&self, path_and_query: &str) -> Result { + self.get_on(&self.host, path_and_query) + } + + fn get_on(&self, host: &str, path_and_query: &str) -> Result { let key = self .key .lock() @@ -55,7 +60,7 @@ impl RiotApi { Instant::now(), ); thread::sleep(wait); - let url = format!("{}{path_and_query}", self.host); + let url = format!("{host}{path_and_query}"); get(&self.agent, &url, Some(&key), |body| body.read_to_string()) } } @@ -132,6 +137,29 @@ impl MatchHistorySource for RiotApi { fn fetch_match(&self, match_id: &str) -> Result { self.get(&format!("/lol/match/v5/matches/{}", encode(match_id))) } + + /// Mastery lives on the platform host (e.g. `euw1`), not on the regional one. + fn champion_mastery( + &self, + platform: &str, + puuid: &str, + ) -> Result, SourceError> { + // The platform becomes part of the host: nothing but letters and digits goes through. + if platform.is_empty() || !platform.bytes().all(|b| b.is_ascii_alphanumeric()) { + return Err(SourceError::Other(format!( + "Plateforme invalide : {platform}" + ))); + } + let host = format!( + "https://{}.api.riotgames.com", + platform.to_ascii_lowercase() + ); + let path = format!( + "/lol/champion-mastery/v4/champion-masteries/by-puuid/{}", + encode(puuid) + ); + decode_mastery(&self.get_on(&host, &path)?) + } } fn decode_account(body: &str) -> Result { @@ -143,6 +171,21 @@ fn decode_ids(body: &str) -> Result, SourceError> { .map_err(|e| SourceError::Other(format!("Liste de Parties illisible : {e}"))) } +fn decode_mastery(body: &str) -> Result, SourceError> { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Entry { + champion_id: u32, + champion_points: u64, + } + let entries: Vec = serde_json::from_str(body) + .map_err(|e| SourceError::Other(format!("Maîtrise illisible : {e}")))?; + Ok(entries + .into_iter() + .map(|e| (e.champion_id, e.champion_points)) + .collect()) +} + /// Percent-encodes everything but RFC 3986 unreserved characters. pub(crate) fn encode(segment: &str) -> String { let mut out = String::new(); @@ -194,6 +237,26 @@ mod tests { Err(SourceError::MissingKey) ); assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey)); + assert_eq!( + api.champion_mastery("EUW1", "p"), + Err(SourceError::MissingKey) + ); + } + + #[test] + fn an_invalid_platform_is_rejected_without_a_request() { + // With a key, a request would be attempted (and fail on the network, not as `Other`). + let api = RiotApi::new("RGAPI-test".into(), "europe"); + for platform in ["", "euw1.evil.example/", "eu w1", "euw1@host", "é"] { + assert!( + matches!( + api.champion_mastery(platform, "p"), + Err(SourceError::Other(_)) + ), + "{platform:?}" + ); + } + assert!(api.sent.lock().unwrap().is_empty()); } #[test] @@ -218,6 +281,15 @@ mod tests { ); } + #[test] + fn decodes_the_champion_mastery_response() { + let points = + decode_mastery(include_str!("../tests/fixtures/riot/champion_mastery.json")).unwrap(); + assert_eq!(points, [(222, 154_320), (103, 27_500), (51, 0)]); + assert_eq!(decode_mastery("[]").unwrap(), []); + assert!(decode_mastery("{}").is_err()); + } + #[test] fn decodes_a_match_id_list() { assert_eq!( diff --git a/crates/core/src/tracker.rs b/crates/core/src/tracker.rs index 5334f78..b244202 100644 --- a/crates/core/src/tracker.rs +++ b/crates/core/src/tracker.rs @@ -1,4 +1,4 @@ -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::thread; @@ -28,6 +28,16 @@ pub trait MatchHistorySource: Send + Sync { ) -> Result, SourceError>; /// The raw Match payload (JSON text) exactly as the API returned it. fn fetch_match(&self, match_id: &str) -> Result; + /// The Account's Mastery Points as (champion id, points), for the champions it has points + /// with only. `platform` is a platform id such as "EUW1" (not a routing region). Sources + /// that cannot tell answer an error. + fn champion_mastery( + &self, + _platform: &str, + _puuid: &str, + ) -> Result, SourceError> { + Err(SourceError::NotFound) + } } impl MatchHistorySource for Arc { @@ -49,6 +59,14 @@ impl MatchHistorySource for Arc { fn fetch_match(&self, match_id: &str) -> Result { (**self).fetch_match(match_id) } + + fn champion_mastery( + &self, + platform: &str, + puuid: &str, + ) -> Result, SourceError> { + (**self).champion_mastery(platform, puuid) + } } const SCHEMA: &str = " @@ -75,6 +93,12 @@ CREATE TABLE IF NOT EXISTS champions ( key TEXT NOT NULL, name TEXT NOT NULL ); +CREATE TABLE IF NOT EXISTS mastery ( + puuid TEXT NOT NULL, + champion_id INTEGER NOT NULL, + points INTEGER NOT NULL, + PRIMARY KEY (puuid, champion_id) +); CREATE TABLE IF NOT EXISTS meta ( name TEXT PRIMARY KEY, value TEXT NOT NULL @@ -258,6 +282,65 @@ impl Tracker { Ok(mark.and_then(|ms| ms.parse().ok())) } + /// The Mastery Points Riot last returned for the Account, by champion id. `None`: never + /// fetched for this Account, so every value is unknown. `Some(map)`: the last list Riot + /// returned; it holds only the champions with points, so once a list is known a champion + /// missing from it has 0 points. Never touches the network. + pub fn mastery(&self, puuid: &str) -> Result>, Error> { + let db = self.db(); + let known: Option = db + .query_row( + "SELECT value FROM meta WHERE name = ?1", + [mastery_key(puuid)], + |row| row.get(0), + ) + .optional()?; + if known.is_none() { + return Ok(None); + } + let mut stmt = db.prepare("SELECT champion_id, points FROM mastery WHERE puuid = ?1")?; + let points = stmt + .query_map([puuid], |row| { + Ok((row.get(0)?, row.get::<_, i64>(1)? as u64)) + })? + .collect::>()?; + Ok(Some(points)) + } + + /// One request for the Account's Mastery Points, on the platform of its latest stored + /// Match (none stored: no request). A success replaces the stored list in one transaction; + /// a failure changes nothing, so the last values stay. Called only when the tracker is + /// already talking to Riot about this Account; its errors are not reported anywhere. + pub(crate) fn refresh_mastery(&self, puuid: &str) { + let Ok(Some(platform)) = self.platform_of(puuid) else { + return; + }; + let Ok(list) = self.history.champion_mastery(&platform, puuid) else { + return; + }; + // Ignored like the fetch itself: the previous values stay. + let _ = self.store_mastery(puuid, &list); + } + + fn store_mastery(&self, puuid: &str, list: &[(u32, u64)]) -> Result<(), Error> { + let mut db = self.db(); + let tx = db.transaction()?; + tx.execute("DELETE FROM mastery WHERE puuid = ?1", [puuid])?; + { + let mut insert = tx.prepare( + "INSERT OR REPLACE INTO mastery (puuid, champion_id, points) VALUES (?1, ?2, ?3)", + )?; + for &(champion_id, points) in list { + insert.execute(params![puuid, champion_id, points as i64])?; + } + } + tx.execute( + "INSERT OR REPLACE INTO meta (name, value) VALUES (?1, '1')", + [mastery_key(puuid)], + )?; + Ok(tx.commit()?) + } + /// The platform prefix of this Account's Match ids (e.g. "EUW1"), from its latest Match. pub(crate) fn platform_of(&self, puuid: &str) -> Result, Error> { let id: Option = self @@ -321,6 +404,10 @@ fn synced_until_key(puuid: &str) -> String { format!("synced_until_ms:{puuid}") } +fn mastery_key(puuid: &str) -> String { + format!("mastery:{puuid}") +} + /// What became of one Match fetched by id. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Fetched { diff --git a/crates/core/tests/common/mod.rs b/crates/core/tests/common/mod.rs index dd03d19..688891a 100644 --- a/crates/core/tests/common/mod.rs +++ b/crates/core/tests/common/mod.rs @@ -142,6 +142,11 @@ pub struct FakeHistory { fetches: Arc, listed: Arc, calls: Arc, + /// Mastery Points by puuid, as Riot lists them (champions with points only). + mastery: Mutex>>, + /// Mastery requests fail with this until it is cleared. + mastery_failure: Mutex>, + mastery_calls: Arc, } impl FakeHistory { @@ -157,6 +162,9 @@ impl FakeHistory { fetches: Arc::default(), listed: Arc::default(), calls: Arc::default(), + mastery: Mutex::default(), + mastery_failure: Mutex::default(), + mastery_calls: Arc::default(), } .with_account(account, payloads) } @@ -264,6 +272,31 @@ impl FakeHistory { self.calls.clone() } + /// The Mastery Points Riot lists for this Account (without any, its mastery request + /// answers "not found"). + pub fn with_mastery(self, puuid: &str, points: &[(u32, u64)]) -> FakeHistory { + self.set_mastery(puuid, points); + self + } + + /// Replaces the Mastery Points Riot lists for this Account. + pub fn set_mastery(&self, puuid: &str, points: &[(u32, u64)]) { + self.mastery + .lock() + .unwrap() + .insert(puuid.into(), points.to_vec()); + } + + /// Every mastery request fails with this error until `None` is set (a sync is not affected). + pub fn fail_mastery_with(&self, error: Option) { + *self.mastery_failure.lock().unwrap() = error; + } + + /// Mastery requests made, failed ones included. They are not counted by `call_counter`. + pub fn mastery_counter(&self) -> Arc { + self.mastery_calls.clone() + } + fn enter(&self) -> Result<(), SourceError> { self.calls.fetch_add(1, Ordering::SeqCst); match &*self.failure.lock().unwrap() { @@ -346,6 +379,23 @@ impl MatchHistorySource for FakeHistory { self.fetches.fetch_add(1, Ordering::SeqCst); Ok(raw) } + + fn champion_mastery( + &self, + _platform: &str, + puuid: &str, + ) -> Result, SourceError> { + self.mastery_calls.fetch_add(1, Ordering::SeqCst); + if let Some(error) = &*self.mastery_failure.lock().unwrap() { + return Err(error.clone()); + } + self.mastery + .lock() + .unwrap() + .get(puuid) + .cloned() + .ok_or(SourceError::NotFound) + } } /// Champion reference data served from memory. diff --git a/crates/core/tests/fixtures/riot/champion_mastery.json b/crates/core/tests/fixtures/riot/champion_mastery.json new file mode 100644 index 0000000..219de8e --- /dev/null +++ b/crates/core/tests/fixtures/riot/champion_mastery.json @@ -0,0 +1,34 @@ +[ + { + "puuid": "fixture-puuid-self", + "championId": 222, + "championLevel": 42, + "championPoints": 154320, + "lastPlayTime": 1775000000000, + "championPointsSinceLastLevel": 3320, + "championPointsUntilNextLevel": 0, + "markRequiredForNextLevel": 0, + "tokensEarned": 0, + "milestoneGrades": ["S-", "A"] + }, + { + "puuid": "fixture-puuid-self", + "championId": 103, + "championLevel": 12, + "championPoints": 27500, + "lastPlayTime": 1774000000000, + "championPointsSinceLastLevel": 1500, + "championPointsUntilNextLevel": 4500, + "tokensEarned": 0 + }, + { + "puuid": "fixture-puuid-self", + "championId": 51, + "championLevel": 1, + "championPoints": 0, + "lastPlayTime": 1773000000000, + "championPointsSinceLastLevel": 0, + "championPointsUntilNextLevel": 1800, + "tokensEarned": 0 + } +] diff --git a/crates/core/tests/mastery.rs b/crates/core/tests/mastery.rs new file mode 100644 index 0000000..ec02715 --- /dev/null +++ b/crates/core/tests/mastery.rs @@ -0,0 +1,292 @@ +mod common; + +use std::collections::HashMap; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use arena_tracker_core::{Account, SourceError, Tracker}; +use common::{ + FakeClient, FakeHistory, PlayedMatch, SELF_PUUID, at, date, payload, payloads, played_by, + played_match, recorded_account, +}; + +const OTHER_PUUID: &str = "fixture-puuid-other"; +const NOW: i64 = 1_775_000_000_000; + +fn other_account() -> Account { + Account { + puuid: OTHER_PUUID.into(), + game_name: "Autre".into(), + tag_line: "FIX".into(), + } +} + +fn own_matches() -> Vec { + vec![played_match(222, 1, at(date(2026, 4, 2), 0))] +} + +fn map(points: &[(u32, u64)]) -> Option> { + Some(points.iter().copied().collect()) +} + +struct World { + dir: tempfile::TempDir, + history: Arc, + client: FakeClient, + requests: Arc, +} + +impl World { + fn new(history: FakeHistory) -> World { + let requests = history.mastery_counter(); + World { + dir: tempfile::tempdir().unwrap(), + history: Arc::new(history), + client: FakeClient::recorded(), + requests, + } + } + + /// The recorded Account (one Match, points known to Riot) and another one with a Match. + fn two_accounts() -> World { + let theirs = payload( + "EUW1_theirs", + 1750, + 103, + "Ahri", + 3, + true, + at(date(2026, 4, 3), 0), + ); + World::new( + FakeHistory::new(recorded_account(), payloads(&own_matches())) + .with_account(other_account(), vec![played_by(&theirs, OTHER_PUUID)]) + .with_mastery(SELF_PUUID, &[(222, 154_320), (103, 27_500)]) + .with_mastery(OTHER_PUUID, &[(103, 900)]), + ) + } + + fn tracker(&self) -> Tracker { + Tracker::open( + &self.dir.path().join("arena.db"), + Box::new(self.history.clone()), + ) + .unwrap() + .with_client(Box::new(self.client.clone())) + } + + fn requests(&self) -> usize { + self.requests.load(Ordering::SeqCst) + } + + fn round(&self, tracker: &Tracker) { + tracker.follow_client(NOW, None, &mut |_| {}); + } +} + +#[test] +fn an_account_never_fetched_has_unknown_points() { + let world = World::two_accounts(); + let tracker = world.tracker(); + + assert_eq!(tracker.mastery(SELF_PUUID).unwrap(), None); + + world.round(&tracker); + assert_eq!(tracker.mastery(OTHER_PUUID).unwrap(), None); +} + +#[test] +fn the_first_round_stores_the_points_of_the_synced_account() { + let world = World::two_accounts(); + let tracker = world.tracker(); + + world.round(&tracker); + + assert_eq!( + tracker.mastery(SELF_PUUID).unwrap(), + map(&[(222, 154_320), (103, 27_500)]) + ); + assert_eq!(world.requests(), 1); + assert_eq!(tracker.status().problem, None); +} + +#[test] +fn another_account_has_its_own_points() { + let world = World::two_accounts(); + let tracker = world.tracker(); + world.round(&tracker); + + world.client.sign_in("Autre", "FIX"); + world.round(&tracker); + + assert_eq!(tracker.mastery(OTHER_PUUID).unwrap(), map(&[(103, 900)])); + assert_eq!( + tracker.mastery(SELF_PUUID).unwrap(), + map(&[(222, 154_320), (103, 27_500)]) + ); + assert_eq!(world.requests(), 2); +} + +#[test] +fn the_points_are_kept_for_the_next_launch() { + let world = World::two_accounts(); + world.round(&world.tracker()); + + let reopened = world.tracker(); + + assert_eq!( + reopened.mastery(SELF_PUUID).unwrap(), + map(&[(222, 154_320), (103, 27_500)]) + ); +} + +#[test] +fn a_refresh_replaces_the_list_with_the_one_riot_returns() { + let world = World::two_accounts(); + let tracker = world.tracker(); + world.round(&tracker); + + world + .history + .set_mastery(SELF_PUUID, &[(222, 160_000), (51, 40)]); + tracker.refresh(&mut |_| {}).unwrap(); + + assert_eq!( + tracker.mastery(SELF_PUUID).unwrap(), + map(&[(222, 160_000), (51, 40)]), + "103 is gone from the list: it has no points now" + ); + assert_eq!(world.requests(), 2); + + // An empty list is a known list: nothing is unknown any more. + world.history.set_mastery(SELF_PUUID, &[]); + tracker.refresh(&mut |_| {}).unwrap(); + assert_eq!(tracker.mastery(SELF_PUUID).unwrap(), map(&[])); +} + +#[test] +fn a_failed_fetch_keeps_the_last_values_and_records_no_problem() { + let world = World::two_accounts(); + let tracker = world.tracker(); + world.round(&tracker); + let last = map(&[(222, 154_320), (103, 27_500)]); + + for error in [ + SourceError::InvalidKey, + SourceError::Network("hors ligne".into()), + SourceError::MissingKey, + SourceError::NotFound, + ] { + world.history.fail_mastery_with(Some(error)); + let report = tracker.refresh(&mut |_| {}).unwrap(); + + assert_eq!(report.account, recorded_account()); + assert_eq!(tracker.mastery(SELF_PUUID).unwrap(), last); + assert_eq!(tracker.status().problem, None); + } + assert_eq!(world.requests(), 5); + + world.history.fail_mastery_with(None); + world.history.set_mastery(SELF_PUUID, &[(222, 1)]); + tracker.refresh(&mut |_| {}).unwrap(); + assert_eq!(tracker.mastery(SELF_PUUID).unwrap(), map(&[(222, 1)])); +} + +#[test] +fn a_first_failed_fetch_leaves_the_points_unknown() { + let world = World::two_accounts(); + world + .history + .fail_mastery_with(Some(SourceError::InvalidKey)); + let tracker = world.tracker(); + + world.round(&tracker); + + assert_eq!(world.requests(), 1); + assert_eq!(tracker.mastery(SELF_PUUID).unwrap(), None); + assert_eq!(tracker.status().problem, None); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 1); +} + +#[test] +fn a_failed_sync_requests_no_points() { + let world = World::two_accounts(); + let tracker = world.tracker(); + world + .history + .fail_with(Some(SourceError::Network("x".into()))); + + world.round(&tracker); + + assert_eq!(world.requests(), 0); + assert_eq!(tracker.mastery(SELF_PUUID).unwrap(), None); +} + +#[test] +fn an_account_without_a_stored_match_makes_no_request() { + let world = World::new( + FakeHistory::new(recorded_account(), payloads(&own_matches())) + .with_account(other_account(), vec![]) + .with_mastery(OTHER_PUUID, &[(103, 900)]), + ); + let tracker = world.tracker(); + world.client.sign_in("Autre", "FIX"); + + world.round(&tracker); + + assert_eq!(tracker.match_count(OTHER_PUUID).unwrap(), 0); + assert_eq!(world.requests(), 0, "no Match, no platform"); + assert_eq!(tracker.mastery(OTHER_PUUID).unwrap(), None); +} + +#[test] +fn rounds_that_do_not_talk_to_riot_request_no_points() { + let world = World::two_accounts(); + let tracker = world.tracker(); + world.round(&tracker); + assert_eq!(world.requests(), 1); + + for phase in ["ChampSelect", "InProgress", "None", "None"] { + world.client.set_phase(phase, false); + world.round(&tracker); + } + let _ = tracker.status(); + let _ = tracker.mastery(SELF_PUUID); + + assert_eq!(world.requests(), 1, "no polling, nothing on a read"); + + tracker.refresh(&mut |_| {}).unwrap(); + assert_eq!(world.requests(), 2, "a refresh is one such moment"); +} + +#[test] +fn a_match_fetched_by_its_game_id_is_followed_by_one_request() { + let world = World::two_accounts(); + let tracker = world.tracker(); + world.round(&tracker); + world.client.set_game_id(Some(common::recorded_game_id())); + world.client.set_phase("InProgress", true); + world.round(&tracker); + world.client.set_phase("EndOfGame", true); + + // Riot does not have the Match yet: the try asks for it, but not for the points. + world.round(&tracker); + assert_eq!(world.requests(), 1); + + let id = format!("EUW1_{}", common::recorded_game_id()); + world.history.add_unlisted(payload( + &id, + 1800, + 222, + "Jinx", + 1, + true, + at(date(2026, 4, 5), 1), + )); + world.history.set_mastery(SELF_PUUID, &[(222, 154_900)]); + tracker.follow_client(NOW + 60_000, None, &mut |_| {}); + + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + assert_eq!(world.requests(), 2); + assert_eq!(tracker.mastery(SELF_PUUID).unwrap(), map(&[(222, 154_900)])); +}