From c44cf52a6a80388419ef66c6adf45110a285c887 Mon Sep 17 00:00:00 2001 From: Nessar Date: Mon, 16 Nov 2026 19:06:52 +0100 Subject: [PATCH] Add core: Match import, statistics and game client following Core half of tickets #4 to #12, behind one public interface tested with fake sources and a real SQLite database: - import of Arena Match history from the Riot API, idempotent and resumable, with a sync mark written only when a sync completes - Season table, champion catalog, Challenge summary, champion rows, chart series, Season and Format scopes - game client port and adapter: signed-in Account, end of an Arena game fetched by its id, Official Progress cross-check - update problems reported for banners while stored data stays readable The app crate is adapted in the next commit. Co-Authored-By: Claude Fable 5.2 --- Cargo.lock | 173 +++++ crates/core/Cargo.toml | 11 + crates/core/src/champions.rs | 246 +++++++ crates/core/src/client.rs | 78 ++ crates/core/src/config.rs | 166 +++++ crates/core/src/date.rs | 97 +++ crates/core/src/default_seasons.toml | 18 + crates/core/src/error.rs | 71 ++ crates/core/src/follow.rs | 509 +++++++++++++ crates/core/src/league_client.rs | 558 ++++++++++++++ crates/core/src/lib.rs | 40 +- crates/core/src/model.rs | 90 +++ crates/core/src/riot.rs | 258 +++++++ crates/core/src/seasons.rs | 135 ++++ crates/core/src/statistics.rs | 380 ++++++++++ crates/core/src/tracker.rs | 492 +++++++++++++ crates/core/tests/champions.rs | 248 +++++++ crates/core/tests/common/mod.rs | 671 +++++++++++++++++ crates/core/tests/follow.rs | 1025 ++++++++++++++++++++++++++ crates/core/tests/import.rs | 624 ++++++++++++++++ crates/core/tests/statistics.rs | 595 +++++++++++++++ 21 files changed, 6472 insertions(+), 13 deletions(-) create mode 100644 crates/core/src/champions.rs create mode 100644 crates/core/src/client.rs create mode 100644 crates/core/src/config.rs create mode 100644 crates/core/src/date.rs create mode 100644 crates/core/src/default_seasons.toml create mode 100644 crates/core/src/error.rs create mode 100644 crates/core/src/follow.rs create mode 100644 crates/core/src/league_client.rs create mode 100644 crates/core/src/model.rs create mode 100644 crates/core/src/riot.rs create mode 100644 crates/core/src/seasons.rs create mode 100644 crates/core/src/statistics.rs create mode 100644 crates/core/src/tracker.rs create mode 100644 crates/core/tests/champions.rs create mode 100644 crates/core/tests/common/mod.rs create mode 100644 crates/core/tests/follow.rs create mode 100644 crates/core/tests/import.rs create mode 100644 crates/core/tests/statistics.rs diff --git a/Cargo.lock b/Cargo.lock index 5c01f86..d2a94c7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -213,6 +213,17 @@ dependencies = [ [[package]] name = "arena-tracker-core" version = "0.1.0" +dependencies = [ + "base64 0.23.1", + "rusqlite", + "rustls", + "serde", + "serde_json", + "tempfile", + "toml 1.2.1+spec-1.1.0", + "tungstenite", + "ureq", +] [[package]] name = "arg_enum_proc_macro" @@ -1167,6 +1178,12 @@ dependencies = [ "linktime-proc-macro", ] +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + [[package]] name = "data-url" version = "0.3.2" @@ -1533,6 +1550,18 @@ dependencies = [ "zune-inflate", ] +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + [[package]] name = "fastrand" version = "2.5.0" @@ -2709,6 +2738,15 @@ dependencies = [ "foldhash", ] +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown 0.17.1", +] + [[package]] name = "heapless" version = "0.9.3" @@ -3416,6 +3454,17 @@ dependencies = [ "libc", ] +[[package]] +name = "libsqlite3-sys" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b06e69070b7e12262b0cd90832f0a7396f142a2b330181255562decf9f0c6215" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -5292,6 +5341,30 @@ dependencies = [ "memchr", ] +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "rusqlite" +version = "0.43.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f172c4812a19b26d1c23cdb0070e69db335503dfa378b910eb857386e5b8beba" +dependencies = [ + "bitflags 2.13.2", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + [[package]] name = "rust-embed" version = "8.14.0" @@ -5423,6 +5496,7 @@ version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ + "log", "once_cell", "ring", "rustls-pki-types", @@ -5751,6 +5825,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + [[package]] name = "sha1_smol" version = "1.0.1" @@ -5954,6 +6039,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cd504cecbfe7eef649988840f9a6cb768d11085efec138f8e99f160632d867" +dependencies = [ + "cc", + "rsqlite-vfs", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -6581,6 +6676,25 @@ dependencies = [ "core_maths", ] +[[package]] +name = "tungstenite" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48ac77174b19c110a50ab2128b24215ac9cb40e0e12e093fb602d175c569d22" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.10.4", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror 2.0.21", + "webpki-roots 0.26.11", +] + [[package]] name = "typenum" version = "1.20.1" @@ -6676,6 +6790,35 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" +[[package]] +name = "ureq" +version = "3.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ac5cecf619ca81f66a96482db09687c9f7465af65f4300a8c30cca05bd5a59d" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots 1.0.12", +] + +[[package]] +name = "ureq-proto" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622dce33c252115466d83f63e9744a18f12b4406aae51a01c15ad8fcf1185eb3" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -6748,6 +6891,12 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.1.0" @@ -6787,6 +6936,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -7052,6 +7207,24 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "weezl" version = "0.1.12" diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 92e5eb9..e4d53e4 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -5,3 +5,14 @@ rust-version.workspace = true version.workspace = true [dependencies] +base64 = { version = "0.23.1", default-features = false, features = ["std"] } +rusqlite = { version = "0.43.0", features = ["bundled"] } +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] } +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.154" +toml = "1.2.1" +tungstenite = { version = "0.30.0", default-features = false, features = ["handshake", "rustls-tls-webpki-roots"] } +ureq = "3.5.2" + +[dev-dependencies] +tempfile = "3.27.0" diff --git a/crates/core/src/champions.rs b/crates/core/src/champions.rs new file mode 100644 index 0000000..c42e99d --- /dev/null +++ b/crates/core/src/champions.rs @@ -0,0 +1,246 @@ +use std::collections::BTreeMap; +use std::path::PathBuf; + +use rusqlite::params; +use serde::Deserialize; +use ureq::Agent; + +use crate::error::{Error, SourceError}; +use crate::riot::{agent, encode, get}; +use crate::tracker::Tracker; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Champion { + pub id: u32, + /// Data Dragon id, e.g. "MasterYi"; also the portrait's file name. + pub key: String, + /// French display name, e.g. "Maître Yi". + pub name: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ChampionCatalog { + pub version: String, + pub champions: Vec, +} + +/// Port: champion reference data (Riot's public game data). Real adapter: `DataDragon`. +pub trait ChampionSource: Send + Sync { + fn latest_version(&self) -> Result; + fn catalog(&self, version: &str) -> Result; + /// PNG bytes. + fn portrait(&self, version: &str, key: &str) -> Result, SourceError>; +} + +const HOST: &str = "https://ddragon.leagueoflegends.com"; + +/// Data Dragon, Riot's public static game data (no API key, no rate limit). +pub struct DataDragon { + agent: Agent, +} + +impl DataDragon { + pub fn new() -> DataDragon { + DataDragon { agent: agent() } + } +} + +impl Default for DataDragon { + fn default() -> Self { + DataDragon::new() + } +} + +impl ChampionSource for DataDragon { + fn latest_version(&self) -> Result { + let url = format!("{HOST}/api/versions.json"); + decode_latest_version(&get(&self.agent, &url, None, |b| b.read_to_string())?) + } + + fn catalog(&self, version: &str) -> Result { + let url = format!("{HOST}/cdn/{}/data/fr_FR/champion.json", encode(version)); + decode_catalog( + version, + &get(&self.agent, &url, None, |b| b.read_to_string())?, + ) + } + + fn portrait(&self, version: &str, key: &str) -> Result, SourceError> { + let url = format!( + "{HOST}/cdn/{}/img/champion/{}.png", + encode(version), + encode(key) + ); + get(&self.agent, &url, None, |b| b.read_to_vec()) + } +} + +fn decode_latest_version(body: &str) -> Result { + let versions: Vec = serde_json::from_str(body) + .map_err(|e| SourceError::Other(format!("Versions illisibles : {e}")))?; + versions + .into_iter() + .next() + .ok_or_else(|| SourceError::Other("Aucune version de jeu publiée.".into())) +} + +#[derive(Deserialize)] +struct CatalogFile { + data: BTreeMap, +} + +#[derive(Deserialize)] +struct CatalogEntry { + id: String, + /// The numeric champion id, as a string. + key: String, + name: String, +} + +fn decode_catalog(version: &str, body: &str) -> Result { + let file: CatalogFile = serde_json::from_str(body) + .map_err(|e| SourceError::Other(format!("Champions illisibles : {e}")))?; + let mut champions = file + .data + .into_values() + .map(|entry| { + let id = entry.key.parse().map_err(|_| { + SourceError::Other(format!("Identifiant de champion invalide : {}", entry.key)) + })?; + Ok(Champion { + id, + key: entry.id, + name: entry.name, + }) + }) + .collect::, SourceError>>()?; + champions.sort_by_key(|c| c.id); + Ok(ChampionCatalog { + version: version.into(), + champions, + }) +} + +impl Tracker { + /// Champion reference data comes from `source`; portraits are kept in `portraits_dir`. + pub fn with_champions( + mut self, + source: Box, + portraits_dir: PathBuf, + ) -> Tracker { + self.champions = Some((source, portraits_dir)); + self + } + + /// Refreshes the cached champion catalog when the game version changed, then downloads + /// the portraits missing from the portraits dir. A failed portrait is skipped; a failed + /// version or catalog call is returned and leaves the cached catalog untouched. + pub fn refresh_champions(&self) -> Result<(), Error> { + let Some((source, portraits_dir)) = &self.champions else { + return Ok(()); + }; + let version = source.latest_version()?; + if self.cached_version()?.as_deref() != Some(version.as_str()) { + let catalog = source.catalog(&version)?; + self.store_catalog(&version, &catalog.champions)?; + } + + std::fs::create_dir_all(portraits_dir) + .map_err(|e| Error::Storage(format!("{} : {e}", portraits_dir.display())))?; + for champion in self.cached_champions()? { + let path = portraits_dir.join(format!("{}.png", champion.key)); + // The key becomes a file name: only trust plain names. + if path.exists() || !champion.key.chars().all(|c| c.is_ascii_alphanumeric()) { + continue; + } + if let Ok(png) = source.portrait(&version, &champion.key) { + // Written under another name first so a cut download is never taken for a portrait. + let partial = path.with_extension("part"); + if std::fs::write(&partial, png).is_ok() { + let _ = std::fs::rename(&partial, &path); + } + } + } + Ok(()) + } + + pub(crate) fn cached_champions(&self) -> Result, Error> { + let db = self.db(); + let mut stmt = db.prepare("SELECT id, key, name FROM champions")?; + let champions = stmt + .query_map([], |row| { + Ok(Champion { + id: row.get(0)?, + key: row.get(1)?, + name: row.get(2)?, + }) + })? + .collect::>()?; + Ok(champions) + } + + fn cached_version(&self) -> Result, Error> { + let db = self.db(); + let mut stmt = db.prepare("SELECT value FROM meta WHERE name = 'champion_version'")?; + let versions = stmt + .query_map([], |row| row.get(0))? + .collect::, _>>()?; + Ok(versions.into_iter().next()) + } + + fn store_catalog(&self, version: &str, champions: &[Champion]) -> Result<(), Error> { + let db = self.db(); + let tx = db.unchecked_transaction()?; + tx.execute("DELETE FROM champions", [])?; + for c in champions { + tx.execute( + "INSERT OR REPLACE INTO champions (id, key, name) VALUES (?1, ?2, ?3)", + params![c.id, c.key, c.name], + )?; + } + tx.execute( + "INSERT OR REPLACE INTO meta (name, value) VALUES ('champion_version', ?1)", + [version], + )?; + tx.commit()?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn decodes_the_latest_game_version() { + let body = include_str!("../tests/fixtures/ddragon/versions.json"); + assert_eq!(decode_latest_version(body).unwrap(), "16.22.1"); + assert!(decode_latest_version("[]").is_err()); + } + + #[test] + fn decodes_the_champion_catalog() { + let body = include_str!("../tests/fixtures/ddragon/champion.json"); + let catalog = decode_catalog("16.22.1", body).unwrap(); + + assert_eq!(catalog.version, "16.22.1"); + assert_eq!(catalog.champions.len(), 173); + let champion = |id| catalog.champions.iter().find(|c| c.id == id).unwrap(); + assert_eq!( + champion(11), + &Champion { + id: 11, + key: "MasterYi".into(), + name: "Maître Yi".into() + } + ); + assert_eq!(champion(62).key, "MonkeyKing"); + assert_eq!(champion(62).name, "Wukong"); + } + + #[test] + fn rejects_a_non_numeric_champion_key() { + let body = r#"{"data":{"X":{"id":"X","key":"abc","name":"X"}}}"#; + assert!(decode_catalog("1", body).is_err()); + } +} diff --git a/crates/core/src/client.rs b/crates/core/src/client.rs new file mode 100644 index 0000000..d4feb08 --- /dev/null +++ b/crates/core/src/client.rs @@ -0,0 +1,78 @@ +use std::time::Duration; + +/// Port: the local League client. Strictly read-only. Real adapter: `LeagueClient`. +pub trait GameClientSource: Send + Sync { + /// Riot ID (game name, tag line) of the Account signed in to the client. + fn signed_in(&self) -> Result<(String, String), ClientError>; + fn gameflow(&self) -> Result; + /// Value of the Champs Completed counter of the progression track with this exact name; + /// `None` when the client has no such track. + fn official_progress(&self, track_name: &str) -> Result, ClientError>; + /// Blocks until the client reports a change or `timeout` elapses. + fn wait_for_change(&self, timeout: Duration); +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ClientError { + /// Not running, not reachable, or nobody signed in yet. + Absent, + Other(String), +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum GamePhase { + #[default] + Idle, + ChampSelect, + InGame, + Ended, +} + +impl GamePhase { + /// From the client's gameflow phase name; unknown names are `Idle`. + pub fn from_client(phase: &str) -> GamePhase { + match phase { + "ChampSelect" => GamePhase::ChampSelect, + "GameStart" | "InProgress" | "Reconnect" => GamePhase::InGame, + "WaitingForStats" | "PreEndOfGame" | "EndOfGame" => GamePhase::Ended, + _ => GamePhase::Idle, + } + } +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Gameflow { + pub phase: GamePhase, + /// The current game's mode is Arena (CHERRY); false when there is no game. + pub arena: bool, + /// The client's id of the current game; `None` when there is no game. + pub game_id: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn client_phases_map_to_game_phases() { + for (name, phase) in [ + ("ChampSelect", GamePhase::ChampSelect), + ("GameStart", GamePhase::InGame), + ("InProgress", GamePhase::InGame), + ("Reconnect", GamePhase::InGame), + ("WaitingForStats", GamePhase::Ended), + ("PreEndOfGame", GamePhase::Ended), + ("EndOfGame", GamePhase::Ended), + ("None", GamePhase::Idle), + ("Lobby", GamePhase::Idle), + ("Matchmaking", GamePhase::Idle), + ("CheckedIntoTournament", GamePhase::Idle), + ("ReadyCheck", GamePhase::Idle), + ("FailedToLaunch", GamePhase::Idle), + ("TerminatedInError", GamePhase::Idle), + ("SomethingNew", GamePhase::Idle), + ] { + assert_eq!(GamePhase::from_client(name), phase, "{name}"); + } + } +} diff --git a/crates/core/src/config.rs b/crates/core/src/config.rs new file mode 100644 index 0000000..273f4f2 --- /dev/null +++ b/crates/core/src/config.rs @@ -0,0 +1,166 @@ +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +use crate::error::Error; + +/// User settings from a TOML file. Deliberately has no `Debug`: it holds the API key. +#[derive(Deserialize, Serialize)] +pub struct Config { + #[serde(default)] + pub riot_api_key: String, + #[serde(default)] + pub riot_id: String, + #[serde(default = "default_region")] + pub region: String, +} + +fn default_region() -> String { + "europe".into() +} + +impl Config { + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path) + .map_err(|e| Error::Config(format!("{} : {e}", path.display())))?; + // Only the message: toml's Display quotes the offending line, which may be the key. + toml::from_str(&text) + .map_err(|e| Error::Config(format!("{} : {}", path.display(), e.message()))) + } + + /// Like `load`, but a missing file gives an empty configuration. + pub fn load_or_default(path: &Path) -> Result { + if path.exists() { + return Config::load(path); + } + Ok(Config { + riot_api_key: String::new(), + riot_id: String::new(), + region: default_region(), + }) + } + + /// Writes the file, creating its folder. It is the only place the key is ever stored. + pub fn save(&self, path: &Path) -> Result<(), Error> { + let io_error = |e: std::io::Error| Error::Config(format!("{} : {e}", path.display())); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(io_error)?; + } + let text = toml::to_string(self) + .map_err(|e| Error::Config(format!("{} : {e}", path.display())))?; + // Written aside first so a crash cannot leave a half-written key file. + let partial = path.with_extension("part"); + std::fs::write(&partial, text).map_err(io_error)?; + std::fs::rename(&partial, path).map_err(io_error) + } +} + +/// Per-user data directory (`%APPDATA%\arena-tracker`); `None` when APPDATA is unset. +pub fn data_dir() -> Option { + std::env::var_os("APPDATA").map(|dir| PathBuf::from(dir).join("arena-tracker")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn load(text: &str) -> Result { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + std::fs::write(&path, text).unwrap(); + Config::load(&path) + } + + #[test] + fn region_defaults_to_europe() { + let config = load("riot_api_key = \"k\"\nriot_id = \"Joueur#EUW\"\n").unwrap(); + assert_eq!(config.riot_id, "Joueur#EUW"); + assert_eq!(config.region, "europe"); + } + + #[test] + fn region_can_be_set() { + let config = + load("riot_api_key = \"k\"\nriot_id = \"J#NA\"\nregion = \"americas\"\n").unwrap(); + assert_eq!(config.region, "americas"); + } + + #[test] + fn a_partial_file_gets_empty_values_and_the_default_region() { + let config = load("riot_id = \"Joueur#EUW\"\n").unwrap(); + assert_eq!( + (config.riot_api_key.as_str(), config.region.as_str()), + ("", "europe") + ); + let config = load("").unwrap(); + assert_eq!( + (config.riot_api_key.as_str(), config.riot_id.as_str()), + ("", "") + ); + } + + #[test] + fn a_missing_file_gives_an_empty_configuration() { + let dir = tempfile::tempdir().unwrap(); + let config = Config::load_or_default(&dir.path().join("config.toml")).unwrap(); + assert_eq!( + ( + config.riot_api_key.as_str(), + config.riot_id.as_str(), + config.region.as_str() + ), + ("", "", "europe") + ); + assert!(!dir.path().join("config.toml").exists()); + } + + #[test] + fn saved_settings_load_back() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("nested").join("config.toml"); + let config = Config { + riot_api_key: "RGAPI-secret".into(), + riot_id: "Joueur#EUW".into(), + region: "americas".into(), + }; + + config.save(&path).unwrap(); + let loaded = Config::load_or_default(&path).unwrap(); + + assert_eq!(loaded.riot_api_key, "RGAPI-secret"); + assert_eq!( + (loaded.riot_id.as_str(), loaded.region.as_str()), + ("Joueur#EUW", "americas") + ); + } + + #[test] + fn a_failed_save_does_not_echo_the_key() { + let dir = tempfile::tempdir().unwrap(); + let blocker = dir.path().join("file"); + std::fs::write(&blocker, "").unwrap(); + let config = Config { + riot_api_key: "RGAPI-secret".into(), + riot_id: String::new(), + region: "europe".into(), + }; + + let Err(err) = config.save(&blocker.join("config.toml")) else { + panic!("saving under a file must fail"); + }; + + assert!(!format!("{err} {err:?}").contains("RGAPI-secret")); + } + + #[test] + fn invalid_files_are_config_errors_that_do_not_echo_the_key() { + let Err(Error::Config(msg)) = load("riot_api_key = RGAPI-secret\n") else { + panic!("expected a Config error"); + }; + assert!(!msg.contains("RGAPI-secret")); + assert!(matches!( + Config::load(Path::new("/nonexistent/config.toml")), + Err(Error::Config(_)) + )); + } +} diff --git a/crates/core/src/date.rs b/crates/core/src/date.rs new file mode 100644 index 0000000..e44bbdd --- /dev/null +++ b/crates/core/src/date.rs @@ -0,0 +1,97 @@ +use std::fmt; + +const MS_PER_DAY: i64 = 86_400_000; + +/// Calendar date (UTC). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Date { + pub year: i32, + pub month: u8, + pub day: u8, +} + +impl Date { + /// The UTC day containing that instant. + pub fn from_ms(epoch_ms: i64) -> Date { + let (year, month, day) = civil_from_days(epoch_ms.div_euclid(MS_PER_DAY)); + Date { year, month, day } + } + + /// 00:00 UTC of that day. + pub fn start_ms(&self) -> i64 { + days_from_civil(self.year, self.month, self.day) * MS_PER_DAY + } +} + +impl fmt::Display for Date { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:02}/{:02}/{:04}", self.day, self.month, self.year) + } +} + +// Howard Hinnant's civil-calendar algorithms (days since 1970-01-01). +fn days_from_civil(year: i32, month: u8, day: u8) -> i64 { + let (month, day) = (i64::from(month), i64::from(day)); + let y = i64::from(year) - i64::from(month <= 2); + let era = y.div_euclid(400); + let year_of_era = y.rem_euclid(400); + let day_of_year = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1; + let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; + era * 146_097 + day_of_era - 719_468 +} + +fn civil_from_days(days: i64) -> (i32, u8, u8) { + let z = days + 719_468; + let era = z.div_euclid(146_097); + let day_of_era = z.rem_euclid(146_097); + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let mp = (5 * day_of_year + 2) / 153; + let day = day_of_year - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = year_of_era + era * 400 + i64::from(month <= 2); + (year as i32, month as u8, day as u8) +} + +#[cfg(test)] +mod tests { + use super::*; + + const KNOWN: [(Date, i64); 7] = [ + (date(1970, 1, 1), 0), + (date(1969, 12, 31), -86_400_000), + (date(1999, 12, 31), 946_598_400_000), + (date(2000, 2, 29), 951_782_400_000), // leap day of a year divisible by 400 + (date(2024, 2, 29), 1_709_164_800_000), + (date(2025, 3, 5), 1_741_132_800_000), + (date(2100, 3, 1), 4_107_542_400_000), // 2100 is not a leap year + ]; + + const fn date(year: i32, month: u8, day: u8) -> Date { + Date { year, month, day } + } + + #[test] + fn dates_convert_to_and_from_epoch_milliseconds() { + for (date, ms) in KNOWN { + assert_eq!(date.start_ms(), ms, "{date}"); + assert_eq!(Date::from_ms(ms), date); + assert_eq!(Date::from_ms(ms + MS_PER_DAY - 1), date); + } + assert_eq!(Date::from_ms(1_741_132_800_000 - 1), date(2025, 3, 4)); + } + + #[test] + fn every_day_round_trips() { + for days in -800_000..800_000i64 { + let (y, m, d) = civil_from_days(days); + assert_eq!(days_from_civil(y, m, d), days); + } + } + + #[test] + fn dates_display_in_french_style() { + assert_eq!(date(2025, 3, 5).to_string(), "05/03/2025"); + } +} diff --git a/crates/core/src/default_seasons.toml b/crates/core/src/default_seasons.toml new file mode 100644 index 0000000..c5b2e96 --- /dev/null +++ b/crates/core/src/default_seasons.toml @@ -0,0 +1,18 @@ +# Vous pouvez modifier ces Saisons ou en ajouter (une entrée [[season]] par Saison). +# Une Saison commence à 00:00 UTC à la date indiquée et dure jusqu'au début de la suivante. +# official_track (facultatif) : nom de la piste de progression du client du jeu pour cette Saison. + +[[season]] +name = "Saison 2025" +start = 2025-03-05 +official_track = "Cherry 2025 Champs Completed Track" + +[[season]] +name = "Saison 1 2026" +start = 2026-01-08 +official_track = "2026 Season 1 Champs Completed Track" + +[[season]] +name = "Saison 2 2026" +start = 2026-04-29 +official_track = "2026 Season 2 Champs Completed Track" diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs new file mode 100644 index 0000000..ae7c175 --- /dev/null +++ b/crates/core/src/error.rs @@ -0,0 +1,71 @@ +use std::fmt; +use std::time::Duration; + +#[derive(Clone, Debug, PartialEq)] +pub enum SourceError { + /// No API key configured yet (as opposed to one Riot rejected). + MissingKey, + InvalidKey, + RateLimited { + retry_after: Duration, + }, + Network(String), + NotFound, + Other(String), +} + +impl fmt::Display for SourceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + SourceError::MissingKey => write!(f, "Aucune clé API Riot n'est configurée."), + SourceError::InvalidKey => write!(f, "Clé API Riot refusée ou expirée."), + SourceError::RateLimited { retry_after } => write!( + f, + "Limite de requêtes Riot atteinte (nouvel essai dans {} s).", + retry_after.as_secs() + ), + SourceError::Network(msg) => write!(f, "Erreur réseau : {msg}"), + SourceError::NotFound => write!(f, "Introuvable chez Riot."), + SourceError::Other(msg) => write!(f, "Erreur Riot : {msg}"), + } + } +} + +impl std::error::Error for SourceError {} + +#[derive(Debug)] +pub enum Error { + Source(SourceError), + Storage(String), + InvalidRiotId(String), + Config(String), + UnknownSeason(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Source(e) => e.fmt(f), + Error::Storage(msg) => write!(f, "Erreur de stockage : {msg}"), + Error::InvalidRiotId(id) => { + write!(f, "Riot ID invalide : « {id} » (attendu : Nom#TAG).") + } + Error::Config(msg) => write!(f, "Configuration invalide : {msg}"), + Error::UnknownSeason(name) => write!(f, "Saison inconnue : « {name} »."), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(e: SourceError) -> Self { + Error::Source(e) + } +} + +impl From for Error { + fn from(e: rusqlite::Error) -> Self { + Error::Storage(e.to_string()) + } +} diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs new file mode 100644 index 0000000..6ad80d7 --- /dev/null +++ b/crates/core/src/follow.rs @@ -0,0 +1,509 @@ +//! Keeping the active Account up to date by following the game client. +use std::sync::{MutexGuard, PoisonError}; +use std::thread; +use std::time::Duration; + +use rusqlite::OptionalExtension; + +use crate::client::{GameClientSource, GamePhase, Gameflow}; +use crate::error::{Error, SourceError}; +use crate::model::{Account, SyncProgress, SyncReport}; +use crate::seasons::Season; +use crate::statistics::{Scope, SeasonScope}; +use crate::tracker::{Fetched, Tracker, account_from_row}; + +/// Tries at the Match of an Arena game that just ended, one per `RETRY_EVERY_MS` (about 30 +/// minutes: Riot publishes it only when the whole game is over, which a player eliminated early +/// does not wait for). +pub const MATCH_RETRIES: usize = 90; +pub const RETRY_EVERY_MS: i64 = 20_000; +/// Rounds try a failed adoption again at most this often (an expired key fails every time). +const ADOPT_RETRY_MS: i64 = 60_000; +const WAIT_WHILE_PENDING: Duration = Duration::from_millis(RETRY_EVERY_MS as u64); +const WAIT_OTHERWISE: Duration = Duration::from_secs(60); + +/// Why the last update did not (fully) happen. +#[derive(Debug, Clone, PartialEq)] +pub enum UpdateProblem { + MissingKey, + InvalidKey, + Network, + RateLimited, + /// Client absent and no Account known yet. + NoAccount, + /// A finished Arena game is not available from the Riot API yet. + MatchPending, + Other(String), +} + +impl UpdateProblem { + /// The French banner text. + pub fn message(&self) -> String { + match self { + UpdateProblem::MissingKey => { + "Aucune clé API Riot n'est configurée : ajoutez-la dans les Paramètres.".into() + } + UpdateProblem::InvalidKey => { + "La clé API Riot est refusée (invalide ou expirée) : renouvelez-la dans les Paramètres." + .into() + } + UpdateProblem::Network => { + "L'API Riot est injoignable : vérifiez votre connexion.".into() + } + UpdateProblem::RateLimited => { + "L'API Riot limite les requêtes : la mise à jour reprendra plus tard.".into() + } + UpdateProblem::NoAccount => { + "Aucun Compte connu : lancez le client de League of Legends et connectez-vous." + .into() + } + UpdateProblem::MatchPending => { + "La dernière Partie n'est pas encore disponible chez Riot : actualisez plus tard pour l'importer." + .into() + } + UpdateProblem::Other(reason) => format!("Mise à jour impossible : {reason}"), + } + } +} + +impl From<&Error> for UpdateProblem { + fn from(error: &Error) -> Self { + match error { + Error::Source(SourceError::MissingKey) => UpdateProblem::MissingKey, + Error::Source(SourceError::InvalidKey) => UpdateProblem::InvalidKey, + Error::Source(SourceError::Network(_)) => UpdateProblem::Network, + Error::Source(SourceError::RateLimited { .. }) => UpdateProblem::RateLimited, + other => UpdateProblem::Other(other.to_string()), + } + } +} + +/// The game's own count compared with the app's, for the current Season. +#[derive(Debug, Clone, Default, PartialEq)] +pub enum ProgressCheck { + #[default] + Absent, + Agrees(u32), + Differs { + app: usize, + official: u32, + }, +} + +/// What the interface needs to know besides statistics. +#[derive(Debug, Clone, PartialEq)] +pub struct Status { + /// As of the last `follow_client` round. + pub client_running: bool, + /// The signed-in Account while the client runs, otherwise the last active one. + pub updating: Option, + /// Outcome of the most recent update attempt; `None` after a success. + pub problem: Option, + pub official_progress: ProgressCheck, +} + +/// The Match of a finished Arena game, not stored yet. +struct Pending { + /// The client's id of that game, when it gave one. + game_id: Option, + tries: usize, + next_try_ms: i64, +} + +#[derive(Default)] +pub(crate) struct Follow { + /// The Riot ID read from the client by the last round; `None` while it is absent. + signed_in: Option, + /// The Riot ID of the last adoption, `None` when it failed. + adopted: Option, + /// Set when a round's adoption failed: rounds do not try again before. + adopt_retry_after_ms: Option, + gameflow: Gameflow, + pending: Vec, + /// The Riot ID the app last gave to fall back on when there is nothing else. + fallback: Option, + updating: Option, + problem: Option, + /// The client's reading for the current Season: (Season name, counter value). + official: Option<(String, u32)>, + official_progress: ProgressCheck, +} + +fn riot_id(account: &Account) -> String { + format!("{}#{}", account.game_name, account.tag_line) +} + +fn same_riot_id(a: &str, b: &str) -> bool { + a.to_lowercase() == b.to_lowercase() +} + +impl Tracker { + /// Without a client, it is always absent. + pub fn with_client(mut self, client: Box) -> Tracker { + self.client = Some(client); + self + } + + pub(crate) fn follow(&self) -> MutexGuard<'_, Follow> { + self.follow.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// A successful update clears the problem, except that the Match of a finished game stays + /// missing until one is added. + pub(crate) fn clear_problem(&self, added: usize) { + let mut follow = self.follow(); + if added > 0 || follow.problem != Some(UpdateProblem::MatchPending) { + follow.problem = None; + } + } + + /// Cheap: never touches the client or the network. + pub fn status(&self) -> Status { + let follow = self.follow(); + Status { + client_running: follow.signed_in.is_some(), + updating: follow.updating.clone(), + problem: follow.problem.clone(), + official_progress: follow.official_progress.clone(), + } + } + + /// The Account shown at launch before any round ran. + pub fn last_active_account(&self) -> Result, Error> { + Ok(self + .db() + .query_row( + "SELECT a.puuid, a.game_name, a.tag_line + FROM meta m JOIN accounts a ON a.puuid = m.value + WHERE m.name = 'last_active_puuid'", + [], + account_from_row, + ) + .optional()?) + } + + /// One round of following the game client: reads it once, adopts the signed-in Account (or, + /// without a client, the last known one) until that succeeds, then tries the Matches of + /// finished Arena games that are due. Failures never propagate: they end up in + /// `status().problem`. Returns true when something visible may have changed. + pub fn follow_client( + &self, + now_ms: i64, + fallback_riot_id: Option<&str>, + on_progress: &mut dyn FnMut(SyncProgress), + ) -> bool { + let before = self.status(); + let mut added = 0; + let (signed_in, gameflow) = match &self.client { + Some(client) => match client.signed_in() { + Ok((name, tag)) => (Some(format!("{name}#{tag}")), client.gameflow().ok()), + Err(_) => (None, None), + }, + None => (None, None), + }; + let adopt = { + let mut follow = self.follow(); + if let Some(id) = fallback_riot_id.map(str::trim).filter(|id| !id.is_empty()) { + follow.fallback = Some(id.into()); + } + let lower = |id: &Option| id.as_deref().map(str::to_lowercase); + if lower(&follow.signed_in) != lower(&signed_in) { + follow.adopt_retry_after_ms = None; + } + follow.signed_in = signed_in.clone(); + let due = follow.adopt_retry_after_ms.is_none_or(|t| now_ms >= t); + due && match &signed_in { + Some(_) => lower(&follow.adopted) != lower(&signed_in), + // No client and no Account yet: catch up on Matches played while the app was closed. + None => follow.updating.is_none(), + } + }; + if adopt { + match signed_in.clone().or_else(|| self.known_riot_id()) { + Some(id) => match self.adopt(&id, on_progress) { + Ok(report) => added += report.added, + Err(_) => self.follow().adopt_retry_after_ms = Some(now_ms + ADOPT_RETRY_MS), + }, + None => self.follow().problem = Some(UpdateProblem::NoAccount), + } + } + + if let Some(gameflow) = gameflow { + let mut follow = self.follow(); + let previous = std::mem::replace(&mut follow.gameflow, gameflow); + let ended = previous.phase == GamePhase::InGame + && previous.arena + && follow.gameflow.phase != GamePhase::InGame; + let known = previous.game_id.is_some() + && follow.pending.iter().any(|p| p.game_id == previous.game_id); + if ended && !known { + follow.pending.push(Pending { + game_id: previous.game_id, + tries: 0, + next_try_ms: now_ms, + }); + } + } + let account = self.follow().updating.clone(); + let mut due: Vec> = (self.follow().pending.iter()) + .filter(|p| p.next_try_ms <= now_ms) + .map(|p| p.game_id) + .collect(); + // The games without an id all wait for the same sync: one try for them all. + due.sort_unstable(); + due.dedup(); + for game_id in due { + let (found, over) = match &account { + Some(account) => self.look_for_match(account, game_id, on_progress), + None => (0, false), + }; + added += found; + let mut follow = self.follow(); + let mut expired = false; + follow.pending.retain_mut(|p| { + if p.game_id != game_id || p.next_try_ms > now_ms { + return true; + } + p.tries += 1; + p.next_try_ms = now_ms + RETRY_EVERY_MS; + expired |= !over && p.tries >= MATCH_RETRIES; + !over && p.tries < MATCH_RETRIES + }); + if expired && follow.problem.is_none() { + follow.problem = Some(UpdateProblem::MatchPending); + } + } + + let official = match (&self.client, &signed_in, self.current_season(now_ms)) { + ( + Some(client), + Some(signed_in), + Some(Season { + name, + official_track: Some(track), + .. + }), + ) if self + .follow() + .updating + .as_ref() + .is_some_and(|a| same_riot_id(&riot_id(a), signed_in)) => + { + client + .official_progress(&track) + .ok() + .flatten() + .map(|value| (name, value)) + } + _ => None, + }; + self.follow().official = official; + self.update_progress_check(); + + self.status() != before || added > 0 + } + + /// Blocks until a client event or a timeout, shorter while a Match is pending: the rounds + /// events cause try it only once its time has come. + pub fn wait_for_client(&self) { + let timeout = if self.follow().pending.is_empty() { + WAIT_OTHERWISE + } else { + WAIT_WHILE_PENDING + }; + match &self.client { + Some(client) => client.wait_for_change(timeout), + None => thread::sleep(timeout), + } + } + + /// The refresh button: adopts the Account signed in to the client, else syncs the one being + /// kept up to date, else adopts the last known one. + pub fn refresh( + &self, + on_progress: &mut dyn FnMut(SyncProgress), + ) -> Result { + let (signed_in, updating) = { + let follow = self.follow(); + (follow.signed_in.clone(), follow.updating.clone()) + }; + let result = match (signed_in, updating) { + (Some(id), _) => self.adopt(&id, on_progress), + (None, Some(account)) => self.update(&riot_id(&account), on_progress), + (None, None) => match self.known_riot_id() { + Some(id) => self.adopt(&id, on_progress), + None => Err(self.record(UpdateProblem::NoAccount)), + }, + }; + self.update_progress_check(); + result + } + + /// Without a client: the last active Account, else the configured Riot ID. + fn known_riot_id(&self) -> Option { + let last = self.last_active_account().ok().flatten(); + last.map(|a| riot_id(&a)) + .or_else(|| self.follow().fallback.clone()) + } + + fn record(&self, problem: UpdateProblem) -> UpdateProblem { + self.follow().problem = Some(problem.clone()); + problem + } + + /// A sync whose failure is recorded as the current problem (a success clears it). One that + /// adds a Match ends the waits for the games the client gave no id for. + fn update( + &self, + riot_id: &str, + on_progress: &mut dyn FnMut(SyncProgress), + ) -> Result { + match self.sync(riot_id, on_progress) { + Ok(report) => { + if report.added > 0 { + self.follow().pending.retain(|p| p.game_id.is_some()); + } + Ok(report) + } + Err(e) => Err(self.record(UpdateProblem::from(&e))), + } + } + + /// Syncs the Account with this Riot ID and makes it the active one. When that fails, the + /// active one is the stored Account with that Riot ID, if any: never the previous Account. + fn adopt( + &self, + riot_id: &str, + on_progress: &mut dyn FnMut(SyncProgress), + ) -> Result { + let result = self.update(riot_id, on_progress); + let account = match &result { + Ok(report) => Some(report.account.clone()), + Err(_) => self.accounts().ok().and_then(|all| { + all.into_iter() + .find(|a| same_riot_id(&self::riot_id(a), riot_id)) + }), + }; + if let Some(account) = &account + && let Err(e) = self.remember_active(account) + { + self.record(UpdateProblem::from(&e)); + } + let mut follow = self.follow(); + follow.updating = account; + follow.adopted = result.is_ok().then(|| riot_id.into()); + follow.adopt_retry_after_ms = follow.adopt_retry_after_ms.filter(|_| result.is_err()); + result + } + + /// One try at the Match of a finished Arena game: fetched by its id when the client gave it + /// and a stored Match gives the platform, else looked for by a normal sync. Returns the + /// number of Matches added and whether the wait for this one is over. + fn look_for_match( + &self, + account: &Account, + game_id: Option, + on_progress: &mut dyn FnMut(SyncProgress), + ) -> (usize, bool) { + let platform = self.platform_of(&account.puuid).ok().flatten(); + let Some(match_id) = game_id.zip(platform).map(|(id, p)| format!("{p}_{id}")) else { + // Not over: `update` ends the waits without an id, a fetch by id ends the others. + let added = self.update(&riot_id(account), on_progress); + return (added.map_or(0, |report| report.added), false); + }; + match self.fetch_and_store(&account.puuid, &match_id) { + Ok(fetched) => { + let added = usize::from(fetched == Fetched::Added); + self.clear_problem(added); + (added, fetched != Fetched::NotFound) + } + Err(e) => { + self.record(UpdateProblem::from(&e)); + (0, false) + } + } + } + + fn remember_active(&self, account: &Account) -> Result<(), Error> { + self.db().execute( + "INSERT OR REPLACE INTO meta (name, value) VALUES ('last_active_puuid', ?1)", + [&account.puuid], + )?; + Ok(()) + } + + /// Compares the client's reading with the Challenge of the active Account. + fn update_progress_check(&self) { + let (official, account) = { + let follow = self.follow(); + (follow.official.clone(), follow.updating.clone()) + }; + let check = match (official, account) { + (Some((season, official)), Some(account)) => { + let scope = Scope { + season: SeasonScope::Season(season), + format: None, + }; + match self.statistics(&account.puuid, &scope) { + Ok(stats) => { + let app = stats.challenge.map_or(0, |c| c.completed); + if app == official as usize { + ProgressCheck::Agrees(official) + } else { + ProgressCheck::Differs { app, official } + } + } + Err(_) => ProgressCheck::Absent, + } + } + _ => ProgressCheck::Absent, + }; + self.follow().official_progress = check; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + use std::time::Duration; + + #[test] + fn every_problem_has_its_own_message() { + let messages: HashSet = [ + UpdateProblem::MissingKey, + UpdateProblem::InvalidKey, + UpdateProblem::Network, + UpdateProblem::RateLimited, + UpdateProblem::NoAccount, + UpdateProblem::MatchPending, + UpdateProblem::Other("panne".into()), + ] + .iter() + .map(UpdateProblem::message) + .collect(); + assert_eq!(messages.len(), 7); + assert!(messages.iter().all(|m| !m.is_empty())); + } + + #[test] + fn errors_map_to_problems() { + let source = |e| UpdateProblem::from(&Error::Source(e)); + assert_eq!(source(SourceError::MissingKey), UpdateProblem::MissingKey); + assert_eq!(source(SourceError::InvalidKey), UpdateProblem::InvalidKey); + assert_eq!( + source(SourceError::Network("x".into())), + UpdateProblem::Network + ); + let limited = SourceError::RateLimited { + retry_after: Duration::ZERO, + }; + assert_eq!(source(limited), UpdateProblem::RateLimited); + assert!(matches!( + source(SourceError::NotFound), + UpdateProblem::Other(_) + )); + let storage = UpdateProblem::from(&Error::Storage("disque plein".into())); + assert!(matches!(storage, UpdateProblem::Other(m) if m.contains("disque plein"))); + } +} diff --git a/crates/core/src/league_client.rs b/crates/core/src/league_client.rs new file mode 100644 index 0000000..1dedc2e --- /dev/null +++ b/crates/core/src/league_client.rs @@ -0,0 +1,558 @@ +use std::collections::HashMap; +use std::io::ErrorKind; +use std::net::{SocketAddr, TcpStream}; +use std::path::PathBuf; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::time::{Duration, Instant}; +use std::{env, fs, thread}; + +use base64::prelude::{BASE64_STANDARD, Engine}; +use rustls::pki_types::CertificateDer; +use rustls::{ClientConfig, RootCertStore}; +use serde_json::Value; +use tungstenite::client::IntoClientRequest; +use tungstenite::http::HeaderValue; +use tungstenite::stream::MaybeTlsStream; +use tungstenite::{Connector, Message, WebSocket, client_tls_with_config}; +use ureq::Agent; +use ureq::tls::{Certificate, RootCerts, TlsConfig}; + +use crate::client::{ClientError, GameClientSource, GamePhase, Gameflow}; +use crate::riot::encode; + +/// Riot's published root certificate: the client's certificate is signed by it, and it is +/// the only root this adapter trusts. +const RIOT_ROOT: &str = include_str!("riotgames.pem"); +const SETTINGS: &str = + "Riot Games/Metadata/league_of_legends.live/league_of_legends.live.product_settings.yaml"; +const DEFAULT_INSTALL_DIR: &str = r"C:\Riot Games\League of Legends"; +const TIMEOUT: Duration = Duration::from_secs(5); +const TOPICS: [&str; 3] = [ + "OnJsonApiEvent_lol-gameflow_v1_session", + "OnJsonApiEvent_lol-summoner_v1_current-summoner", + "OnJsonApiEvent_lol-champ-select_v1_session", +]; + +/// The local League client's API (unofficial, read-only). Deliberately no `Debug`: it handles +/// the lockfile password. +pub struct LeagueClient { + install_dir: PathBuf, + agent: Agent, + /// Track name -> (group id, id of the group's first counter), so the big progression + /// configuration is downloaded once per track. + tracks: Mutex)>>, + events: Mutex>, +} + +struct Events(WebSocket>); + +impl Events { + /// Set on the stream the TLS layer reads from: on Windows a timeout is per handle, so a + /// clone of the `TcpStream` would not do. + fn set_read_timeout(&self, timeout: Duration) -> std::io::Result<()> { + match self.0.get_ref() { + MaybeTlsStream::Rustls(stream) => stream.get_ref().set_read_timeout(Some(timeout)), + _ => Err(ErrorKind::Unsupported.into()), + } + } +} + +impl LeagueClient { + pub fn new() -> LeagueClient { + let from_settings = env::var_os("PROGRAMDATA") + .and_then(|dir| fs::read_to_string(PathBuf::from(dir).join(SETTINGS)).ok()) + .and_then(|yaml| install_dir_from_settings(&yaml)); + LeagueClient::in_dir(from_settings.unwrap_or_else(|| DEFAULT_INSTALL_DIR.into())) + } + + fn in_dir(install_dir: PathBuf) -> LeagueClient { + let agent = Agent::config_builder() + .http_status_as_error(false) + .proxy(None) // the client is on this machine + .tls_config( + TlsConfig::builder() + .root_certs(RootCerts::new_with_certs(&[root_cert()])) + .build(), + ) + .timeout_global(Some(TIMEOUT)) + .build() + .into(); + LeagueClient { + install_dir, + agent, + tracks: Mutex::default(), + events: Mutex::default(), + } + } + + /// Read on every call: the port and password change each time the client restarts. + fn lockfile(&self) -> Result<(u16, String), ClientError> { + fs::read_to_string(self.install_dir.join("lockfile")) + .ok() + .and_then(|content| parse_lockfile(&content)) + .ok_or(ClientError::Absent) + } + + /// Status and body of a GET; the client is the only thing this ever talks to. + fn get(&self, path: &str) -> Result<(u16, String), ClientError> { + let (port, password) = self.lockfile()?; + let mut response = self + .agent + .get(&format!("https://127.0.0.1:{port}{path}")) + .header("Authorization", authorization(&password)) + .call() + .map_err(transport_error)?; + let body = response + .body_mut() + .read_to_string() + .map_err(transport_error)?; + Ok((response.status().as_u16(), body)) + } + + fn get_ok(&self, path: &str) -> Result { + match self.get(path)? { + (200, body) => Ok(body), + (status, _) => Err(ClientError::Other(format!("HTTP {status}"))), + } + } + + fn connect(&self) -> Option { + let (port, password) = self.lockfile().ok()?; + let tcp = + TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), TIMEOUT).ok()?; + // They bound the TLS and WebSocket handshakes. + tcp.set_read_timeout(Some(TIMEOUT)).ok()?; + tcp.set_write_timeout(Some(TIMEOUT)).ok()?; + let mut request = format!("wss://127.0.0.1:{port}/") + .into_client_request() + .ok()?; + let auth = HeaderValue::from_str(&authorization(&password)).ok()?; + request.headers_mut().insert("Authorization", auth); + let tls = Connector::Rustls(Arc::new(tls_config().ok()?)); + let (mut socket, _) = client_tls_with_config(request, tcp, None, Some(tls)).ok()?; + for topic in TOPICS { + socket + .send(Message::text(format!(r#"[5, "{topic}"]"#))) + .ok()?; + } + Some(Events(socket)) + } +} + +impl Default for LeagueClient { + fn default() -> Self { + LeagueClient::new() + } +} + +impl GameClientSource for LeagueClient { + fn signed_in(&self) -> Result<(String, String), ClientError> { + match self.get("/lol-summoner/v1/current-summoner")? { + (200, body) => decode_signed_in(&body), + _ => Err(ClientError::Absent), + } + } + + fn gameflow(&self) -> Result { + let (status, body) = self.get("/lol-gameflow/v1/session")?; + decode_gameflow(status, &body) + } + + fn official_progress(&self, track_name: &str) -> Result, ClientError> { + let known = lock(&self.tracks).get(track_name).cloned(); + let (group_id, counter_id) = match known { + Some(track) => track, + None => { + let body = self.get_ok("/lol-progression/v1/groups/configuration")?; + let Some(track) = find_track(&body, track_name)? else { + return Ok(None); + }; + lock(&self.tracks).insert(track_name.into(), track.clone()); + track + } + }; + let path = format!( + "/lol-progression/v1/groups/{}/instanceData", + encode(&group_id) + ); + // A refused group id may be stale after a patch: look the track up again next time. + let body = self.get_ok(&path).inspect_err(|_| { + lock(&self.tracks).remove(track_name); + })?; + decode_counter(&body, counter_id.as_deref()) + } + + fn wait_for_change(&self, timeout: Duration) { + let started = Instant::now(); + let mut events = lock(&self.events); + if events.is_none() { + *events = self.connect(); + } + let Some(connection) = events.as_mut() else { + thread::sleep(timeout.min(TIMEOUT)); + return; + }; + // Right after subscribing, the client sends one empty text frame per subscription + // (observed on patch 16.22): they and pings are not changes. + loop { + let left = timeout + .saturating_sub(started.elapsed()) + .max(Duration::from_millis(1)); + let read = connection + .set_read_timeout(left) + .map_err(tungstenite::Error::Io) + .and_then(|()| connection.0.read()); + match read { + Ok(Message::Text(text)) if !text.is_empty() => return, + Ok(Message::Close(_)) => *events = None, + Ok(_) => continue, + Err(tungstenite::Error::Io(e)) + if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} + Err(_) => *events = None, + } + return; + } + } +} + +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) +} + +fn root_cert() -> Certificate<'static> { + Certificate::from_pem(RIOT_ROOT.as_bytes()).expect("riotgames.pem holds a certificate") +} + +/// For the WebSocket: the pinned root only, and `ring` chosen explicitly so that no process-wide +/// crypto provider is needed. +fn tls_config() -> Result { + let mut roots = RootCertStore::empty(); + roots.add(CertificateDer::from(root_cert().der().to_vec()))?; + Ok( + ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions()? + .with_root_certificates(roots) + .with_no_client_auth(), + ) +} + +/// A rejected certificate is worth telling apart from a client that is simply not there. +fn transport_error(e: ureq::Error) -> ClientError { + match e { + ureq::Error::Tls(_) | ureq::Error::Rustls(_) => { + ClientError::Other(format!("Connexion TLS au client refusée : {e}")) + } + _ => ClientError::Absent, + } +} + +fn authorization(password: &str) -> String { + format!( + "Basic {}", + BASE64_STANDARD.encode(format!("riot:{password}")) + ) +} + +/// (port, password) from `LeagueClient::::https`. +fn parse_lockfile(content: &str) -> Option<(u16, String)> { + let parts: Vec<&str> = content.trim().split(':').collect(); + let [_, _, port, password, "https"] = parts[..] else { + return None; + }; + (!password.is_empty()).then_some((port.parse().ok()?, password.into())) +} + +/// The value of the `product_install_full_path` line of the product settings. +fn install_dir_from_settings(yaml: &str) -> Option { + let line = yaml + .lines() + .find_map(|l| l.trim().strip_prefix("product_install_full_path:"))?; + let path = line.trim().trim_matches('"'); + (!path.is_empty()).then(|| path.into()) +} + +fn parse(body: &str) -> Result { + serde_json::from_str(body) + .map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}"))) +} + +fn decode_signed_in(body: &str) -> Result<(String, String), ClientError> { + let summoner = parse(body)?; + let field = |name: &str| summoner[name].as_str().filter(|s| !s.is_empty()); + match (field("gameName"), field("tagLine")) { + (Some(name), Some(tag)) => Ok((name.into(), tag.into())), + _ => Err(ClientError::Absent), + } +} + +/// No session (404) means no game. The other fields are read leniently: the API is +/// unofficial and changes with patches. +fn decode_gameflow(status: u16, body: &str) -> Result { + match status { + 404 => Ok(Gameflow::default()), + 200 => { + let session = parse(body)?; + let arena = ["/gameData/queue/gameMode", "/map/gameMode"] + .iter() + .any(|path| session.pointer(path).and_then(Value::as_str) == Some("CHERRY")); + Ok(Gameflow { + phase: GamePhase::from_client(session["phase"].as_str().unwrap_or_default()), + arena, + game_id: session + .pointer("/gameData/gameId") + .and_then(Value::as_u64) + .filter(|&id| id != 0), + }) + } + _ => Err(ClientError::Other(format!("HTTP {status}"))), + } +} + +/// (group id, id of the group's first counter) of the group with exactly this name. +fn find_track( + body: &str, + track_name: &str, +) -> Result)>, ClientError> { + let groups = parse(body)?; + let group = groups + .as_array() + .into_iter() + .flatten() + .find(|g| g["name"] == track_name); + Ok(group.and_then(|g| { + let counter = g.pointer("/counters/0/id").and_then(Value::as_str); + Some((g["id"].as_str()?.into(), counter.map(String::from))) + })) +} + +/// The value of the counter with this id, else of the first counter. +fn decode_counter(body: &str, counter_id: Option<&str>) -> Result, ClientError> { + let data = parse(body)?; + let counters = data["counters"].as_array().map_or(&[][..], Vec::as_slice); + let counter = counter_id + .and_then(|id| counters.iter().find(|c| c["counterId"] == id)) + .or(counters.first()); + Ok(counter + .and_then(|c| c["counterValue"].as_u64()) + .and_then(|v| u32::try_from(v).ok())) +} + +#[cfg(test)] +mod tests { + use super::*; + + const SUMMONER: &str = include_str!("../tests/fixtures/client/current_summoner.json"); + const NO_SESSION: &str = include_str!("../tests/fixtures/client/gameflow_session_absent.json"); + const GROUPS: &str = + include_str!("../tests/fixtures/client/progression_groups_configuration.json"); + const INSTANCE: &str = include_str!("../tests/fixtures/client/progression_instance_data.json"); + const SEASON_2: &str = "2026 Season 2 Champs Completed Track"; + + const ARENA_GAME: &str = include_str!("../tests/fixtures/client/gameflow_session_in_game.json"); + + #[test] + fn reads_the_port_and_password_of_a_lockfile() { + let sample = "LeagueClient:4242:51234:fake-password_1:https"; + assert_eq!( + parse_lockfile(sample), + Some((51234, "fake-password_1".into())) + ); + assert_eq!( + parse_lockfile(&format!("{sample}\r\n")), + Some((51234, "fake-password_1".into())) + ); + } + + #[test] + fn a_malformed_lockfile_is_ignored() { + for bad in [ + "", + "LeagueClient", + "LeagueClient:4242:51234:fake-password", + "LeagueClient:4242:notaport:fake-password:https", + "LeagueClient:4242:99999:fake-password:https", + "LeagueClient:4242:51234::https", + "LeagueClient:4242:51234:fake-password:http", + "LeagueClient:4242:51234:fake:password:https", + ] { + assert_eq!(parse_lockfile(bad), None, "{bad:?}"); + } + } + + #[test] + fn reads_the_install_directory_from_the_product_settings() { + let yaml = "auto_patching_enabled_by_player: false\n\ + product_install_full_path: \"C:/Riot Games/League of Legends\"\n\ + settings:\n locale: \"fr_FR\"\n"; + assert_eq!( + install_dir_from_settings(yaml), + Some(PathBuf::from("C:/Riot Games/League of Legends")) + ); + assert_eq!(install_dir_from_settings("settings:\n locale: x\n"), None); + assert_eq!( + install_dir_from_settings("product_install_full_path: \"\""), + None + ); + } + + #[test] + fn basic_authorization_uses_the_riot_user() { + // base64("riot:fake-password") + assert_eq!( + authorization("fake-password"), + "Basic cmlvdDpmYWtlLXBhc3N3b3Jk" + ); + } + + #[test] + fn the_embedded_root_certificate_builds_a_tls_config() { + assert!(tls_config().is_ok()); + } + + #[test] + fn reads_the_signed_in_riot_id() { + assert_eq!( + decode_signed_in(SUMMONER), + Ok(("Joueur".into(), "EUW".into())) + ); + } + + #[test] + fn nobody_signed_in_yet_is_absent() { + for body in [ + r#"{"gameName": "Joueur"}"#, + r#"{"gameName": "", "tagLine": "EUW"}"#, + r#"{"gameName": "Joueur", "tagLine": ""}"#, + r#"{"gameName": null, "tagLine": null}"#, + "{}", + ] { + assert_eq!(decode_signed_in(body), Err(ClientError::Absent), "{body}"); + } + assert!(matches!( + decode_signed_in(""), + Err(ClientError::Other(_)) + )); + } + + #[test] + fn no_gameflow_session_means_idle() { + assert_eq!( + decode_gameflow(404, NO_SESSION), + Ok(Gameflow { + phase: GamePhase::Idle, + arena: false, + game_id: None + }) + ); + } + + #[test] + fn an_arena_game_in_progress_is_in_game_and_arena() { + assert_eq!( + decode_gameflow(200, ARENA_GAME), + Ok(Gameflow { + phase: GamePhase::InGame, + arena: true, + game_id: Some(9000000099) + }) + ); + let classic = r#"{"phase": "InProgress", "gameData": {"queue": {"gameMode": "CLASSIC"}}}"#; + assert_eq!( + decode_gameflow(200, classic), + Ok(Gameflow { + phase: GamePhase::InGame, + arena: false, + game_id: None + }) + ); + } + + #[test] + fn unknown_and_missing_gameflow_fields_are_not_errors() { + let extra = r#"{"phase": "ChampSelect", "somethingNew": {"a": [1, 2]}, "map": null, + "gameData": {"queue": null}}"#; + assert_eq!( + decode_gameflow(200, extra), + Ok(Gameflow { + phase: GamePhase::ChampSelect, + arena: false, + game_id: None + }) + ); + assert_eq!(decode_gameflow(200, "{}"), decode_gameflow(404, "")); + // The map alone says Arena when the queue is missing. + let map_only = r#"{"phase": "EndOfGame", "map": {"gameMode": "CHERRY"}}"#; + assert_eq!( + decode_gameflow(200, map_only), + Ok(Gameflow { + phase: GamePhase::Ended, + arena: true, + game_id: None + }) + ); + // An id of 0 means no game; one that is not a number is ignored. + for id in ["0", "\"x\"", "null", "-1"] { + let body = format!(r#"{{"phase": "InProgress", "gameData": {{"gameId": {id}}}}}"#); + assert_eq!(decode_gameflow(200, &body).unwrap().game_id, None, "{id}"); + } + assert_eq!( + decode_gameflow(503, ""), + Err(ClientError::Other("HTTP 503".into())) + ); + } + + #[test] + fn finds_the_champs_completed_tracks_by_exact_name() { + for (name, group, counter) in [ + ( + SEASON_2, + "01030e0d-e3e3-4034-93dc-44a88bcb8401", + "d64a3f04-2ba0-475a-9a33-782cb12e6467", + ), + ( + "2026 Season 1 Champs Completed Track", + "7d0ef399-dd59-4005-bf1d-e0b98cda8acb", + "be96f5dc-d65c-4ea4-9a23-0b2c1bb6880f", + ), + ( + "Cherry 2025 Champs Completed Track", + "e5d45c5c-a035-4e0a-9c9d-c02a3604a3b9", + "ae1d0604-8841-4640-987e-29696c18caca", + ), + ] { + assert_eq!( + find_track(GROUPS, name), + Ok(Some((group.into(), Some(counter.into())))), + "{name}" + ); + } + for unknown in ["2026 Season 3 Champs Completed Track", "2026 Season 2", ""] { + assert_eq!(find_track(GROUPS, unknown), Ok(None), "{unknown:?}"); + } + assert_eq!(find_track("[]", SEASON_2), Ok(None)); + } + + #[test] + fn reads_the_counter_of_the_track() { + let counter = "d64a3f04-2ba0-475a-9a33-782cb12e6467"; + assert_eq!(decode_counter(INSTANCE, Some(counter)), Ok(Some(52))); + // Without a usable counter id, the first counter is read. + assert_eq!(decode_counter(INSTANCE, None), Ok(Some(52))); + assert_eq!(decode_counter(INSTANCE, Some("other")), Ok(Some(52))); + assert_eq!(decode_counter(r#"{"counters": []}"#, None), Ok(None)); + assert_eq!(decode_counter("{}", Some(counter)), Ok(None)); + } + + #[test] + fn without_a_lockfile_the_client_is_absent() { + let dir = tempfile::tempdir().unwrap(); + let client = LeagueClient::in_dir(dir.path().into()); + assert_eq!(client.signed_in(), Err(ClientError::Absent)); + assert_eq!(client.gameflow(), Err(ClientError::Absent)); + assert_eq!(client.official_progress(SEASON_2), Err(ClientError::Absent)); + let started = Instant::now(); + client.wait_for_change(Duration::from_millis(50)); + assert!(started.elapsed() >= Duration::from_millis(50)); + assert!(started.elapsed() < TIMEOUT); + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 0ccb96f..47f33d3 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1,14 +1,28 @@ -/// Text shown at startup while no Match has been imported yet. -pub fn startup_message() -> &'static str { - "Aucune Partie importée pour l'instant." -} +mod champions; +mod client; +mod config; +mod date; +mod error; +mod follow; +mod league_client; +mod model; +mod riot; +mod seasons; +mod statistics; +mod tracker; -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn startup_message_announces_no_imported_match() { - assert_eq!(startup_message(), "Aucune Partie importée pour l'instant."); - } -} +pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon}; +pub use client::{ClientError, GameClientSource, GamePhase, Gameflow}; +pub use config::{Config, data_dir}; +pub use date::Date; +pub use error::{Error, SourceError}; +pub use follow::{MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem}; +pub use league_client::LeagueClient; +pub use model::{Account, Format, Match, SyncProgress, SyncReport}; +pub use riot::RiotApi; +pub use seasons::{Season, default_seasons, load_seasons}; +pub use statistics::{ + ChallengeSummary, ChampionRow, ChampionState, Charts, Column, Scope, SeasonScope, StateFilter, + Statistics, sort_rows, +}; +pub use tracker::{MatchHistorySource, Tracker}; diff --git a/crates/core/src/model.rs b/crates/core/src/model.rs new file mode 100644 index 0000000..6f0dceb --- /dev/null +++ b/crates/core/src/model.rs @@ -0,0 +1,90 @@ +use serde::Deserialize; + +/// One Arena variant, derived from the game queue. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Format { + Arena3x6, + BraveryArena, + Arena16, + Other(u32), +} + +impl Format { + /// `None` for queues that are not real Matches (1704 is the PBE test queue). + pub fn from_queue(queue_id: u32) -> Option { + match queue_id { + 1750 => Some(Format::Arena3x6), + 1740 => Some(Format::BraveryArena), + 1700 | 1710 => Some(Format::Arena16), + 1704 => None, + other => Some(Format::Other(other)), + } + } + + pub fn name(&self) -> String { + match self { + Format::Arena3x6 => "Arena 3x6".into(), + Format::BraveryArena => "Bravery Arena".into(), + Format::Arena16 => "Arena 16 joueurs".into(), + Format::Other(queue) => format!("Arena (file {queue})"), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Account { + pub puuid: String, + pub game_name: String, + pub tag_line: String, +} + +/// A stored Match as the user sees it. +#[derive(Clone, Debug, PartialEq)] +pub struct Match { + pub match_id: String, + pub format: Format, + pub champion_id: u32, + pub champion_name: String, + pub placement: u8, + pub win: bool, + pub started_at_ms: i64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SyncProgress { + pub fetched: usize, + pub to_fetch: usize, +} + +#[derive(Clone, Debug)] +pub struct SyncReport { + pub account: Account, + /// Matches newly stored by this sync. + pub added: usize, + /// All Matches stored for the Account once the sync is done. + pub stored: usize, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn queues_map_to_formats() { + assert_eq!(Format::from_queue(1750), Some(Format::Arena3x6)); + assert_eq!(Format::from_queue(1740), Some(Format::BraveryArena)); + assert_eq!(Format::from_queue(1700), Some(Format::Arena16)); + assert_eq!(Format::from_queue(1710), Some(Format::Arena16)); + assert_eq!(Format::from_queue(1704), None); + assert_eq!(Format::from_queue(1800), Some(Format::Other(1800))); + } + + #[test] + fn formats_have_french_facing_names() { + assert_eq!(Format::Arena3x6.name(), "Arena 3x6"); + assert_eq!(Format::BraveryArena.name(), "Bravery Arena"); + assert_eq!(Format::Arena16.name(), "Arena 16 joueurs"); + assert_eq!(Format::Other(1800).name(), "Arena (file 1800)"); + } +} diff --git a/crates/core/src/riot.rs b/crates/core/src/riot.rs new file mode 100644 index 0000000..9b22058 --- /dev/null +++ b/crates/core/src/riot.rs @@ -0,0 +1,258 @@ +use std::collections::VecDeque; +use std::sync::{Mutex, PoisonError}; +use std::thread; +use std::time::{Duration, Instant}; + +use ureq::{Agent, Body}; + +use crate::error::SourceError; +use crate::model::Account; +use crate::tracker::MatchHistorySource; + +/// Personal-key limits: (requests, window). +const LIMITS: [(usize, Duration); 2] = [ + (20, Duration::from_secs(1)), + (100, Duration::from_secs(120)), +]; +const DEFAULT_RETRY_AFTER: Duration = Duration::from_secs(10); + +/// Riot web API adapter. Deliberately has no `Debug`: it holds the API key. +pub struct RiotApi { + key: Mutex, + host: String, + agent: Agent, + /// Send times of recent requests, oldest first. + sent: Mutex>, +} + +impl RiotApi { + /// `region` is the routing value, e.g. "europe". + pub fn new(api_key: String, region: &str) -> RiotApi { + RiotApi { + key: Mutex::new(api_key), + host: format!("https://{region}.api.riotgames.com"), + agent: agent(), + sent: Mutex::new(VecDeque::new()), + } + } + + /// Replaces the key used by all later requests. + pub fn set_key(&self, api_key: String) { + *self.key.lock().unwrap_or_else(PoisonError::into_inner) = api_key; + } + + fn get(&self, path_and_query: &str) -> Result { + let key = self + .key + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone(); + if key.is_empty() { + return Err(SourceError::MissingKey); + } + let wait = reserve_slot( + &mut self.sent.lock().unwrap_or_else(PoisonError::into_inner), + Instant::now(), + ); + thread::sleep(wait); + let url = format!("{}{path_and_query}", self.host); + get(&self.agent, &url, Some(&key), |body| body.read_to_string()) + } +} + +/// The HTTP client shared by the adapters. +pub(crate) fn agent() -> Agent { + Agent::config_builder() + .http_status_as_error(false) + .user_agent("arena-tracker") // the default UA is blocked by Cloudflare on some clients + .timeout_global(Some(Duration::from_secs(30))) + .build() + .into() +} + +/// GETs `url` (sending the Riot token when given) and reads a successful body with `read`; +/// other statuses become `SourceError`s. +pub(crate) fn get( + agent: &Agent, + url: &str, + riot_token: Option<&str>, + read: impl FnOnce(&mut Body) -> Result, +) -> Result { + let mut request = agent.get(url); + if let Some(token) = riot_token { + request = request.header("X-Riot-Token", token); + } + let mut response = request + .call() + .map_err(|e| SourceError::Network(e.to_string()))?; + match response.status().as_u16() { + 200..=299 => read(response.body_mut()).map_err(|e| SourceError::Network(e.to_string())), + 401 | 403 => Err(SourceError::InvalidKey), + 404 => Err(SourceError::NotFound), + 429 => Err(SourceError::RateLimited { + retry_after: response + .headers() + .get("retry-after") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.trim().parse().ok()) + .map_or(DEFAULT_RETRY_AFTER, Duration::from_secs), + }), + status => Err(SourceError::Other(format!("HTTP {status}"))), + } +} + +impl MatchHistorySource for RiotApi { + fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result { + let path = format!( + "/riot/account/v1/accounts/by-riot-id/{}/{}", + encode(game_name), + encode(tag_line) + ); + decode_account(&self.get(&path)?) + } + + fn match_ids( + &self, + puuid: &str, + queue_id: u32, + start: usize, + count: usize, + start_time_s: Option, + ) -> Result, SourceError> { + let mut path = format!( + "/lol/match/v5/matches/by-puuid/{}/ids?queue={queue_id}&start={start}&count={count}", + encode(puuid) + ); + if let Some(t) = start_time_s { + path.push_str(&format!("&startTime={t}")); + } + decode_ids(&self.get(&path)?) + } + + fn fetch_match(&self, match_id: &str) -> Result { + self.get(&format!("/lol/match/v5/matches/{}", encode(match_id))) + } +} + +fn decode_account(body: &str) -> Result { + serde_json::from_str(body).map_err(|e| SourceError::Other(format!("Compte illisible : {e}"))) +} + +fn decode_ids(body: &str) -> Result, SourceError> { + serde_json::from_str(body) + .map_err(|e| SourceError::Other(format!("Liste de Parties illisible : {e}"))) +} + +/// Percent-encodes everything but RFC 3986 unreserved characters. +pub(crate) fn encode(segment: &str) -> String { + let mut out = String::new(); + for byte in segment.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + out.push(byte as char) + } + _ => out.push_str(&format!("%{byte:02X}")), + } + } + out +} + +/// Books the next request in the sliding windows and returns how long to wait before sending it. +fn reserve_slot(sent: &mut VecDeque, now: Instant) -> Duration { + let longest = LIMITS[1].1; + while sent + .front() + .is_some_and(|&t| now.saturating_duration_since(t) >= longest) + { + sent.pop_front(); + } + // A window of `max` requests is full when `max` requests are booked inside it; the new + // one may go once the oldest of them leaves. + let wait = LIMITS + .iter() + .filter(|&&(max, _)| sent.len() >= max) + .map(|&(max, window)| (sent[sent.len() - max] + window).saturating_duration_since(now)) + .max() + .unwrap_or_default(); + sent.push_back(now + wait); + wait +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn without_a_key_no_request_is_sent() { + let api = RiotApi::new(String::new(), "europe"); + assert_eq!( + api.resolve_account("Joueur", "EUW"), + Err(SourceError::MissingKey) + ); + assert_eq!( + api.match_ids("p", 1700, 0, 100, None), + Err(SourceError::MissingKey) + ); + assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey)); + } + + #[test] + fn the_key_can_be_replaced_without_rebuilding_the_adapter() { + let api = RiotApi::new(String::new(), "europe"); + api.set_key("RGAPI-new".into()); + assert_eq!(*api.key.lock().unwrap(), "RGAPI-new"); + api.set_key(String::new()); + assert_eq!(api.fetch_match("EUW1_1"), Err(SourceError::MissingKey)); + } + + #[test] + fn decodes_the_account_response() { + let account = decode_account(include_str!("../tests/fixtures/riot/account.json")).unwrap(); + assert_eq!( + account, + Account { + puuid: "fixture-puuid-self".into(), + game_name: "Joueur".into(), + tag_line: "EUW".into(), + } + ); + } + + #[test] + fn decodes_a_match_id_list() { + assert_eq!( + decode_ids(r#"["EUW1_1","EUW1_2"]"#).unwrap(), + ["EUW1_1", "EUW1_2"] + ); + assert!(decode_ids("{}").is_err()); + } + + #[test] + fn path_segments_are_percent_encoded() { + assert_eq!(encode("Joueur"), "Joueur"); + assert_eq!(encode("Été #1/é"), "%C3%89t%C3%A9%20%231%2F%C3%A9"); + } + + #[test] + fn throttle_spaces_requests_under_both_limits() { + let t0 = Instant::now(); + let mut sent = VecDeque::new(); + for _ in 0..20 { + assert_eq!(reserve_slot(&mut sent, t0), Duration::ZERO); + } + // 21st request waits for the 1 s window. + assert_eq!(reserve_slot(&mut sent, t0), Duration::from_secs(1)); + + // 100 requests fit in 120 s: spread over time so only the long window is full. + let mut sent = VecDeque::new(); + for i in 0..100u64 { + let now = t0 + Duration::from_secs(i); + assert_eq!(reserve_slot(&mut sent, now), Duration::ZERO); + } + let now = t0 + Duration::from_secs(100); + assert_eq!(reserve_slot(&mut sent, now), Duration::from_secs(20)); + // Once the oldest request left the window, no wait is needed. + let later = t0 + Duration::from_secs(121); + assert_eq!(reserve_slot(&mut sent, later), Duration::ZERO); + } +} diff --git a/crates/core/src/seasons.rs b/crates/core/src/seasons.rs new file mode 100644 index 0000000..7de4d8a --- /dev/null +++ b/crates/core/src/seasons.rs @@ -0,0 +1,135 @@ +use std::ops::Range; +use std::path::Path; + +use serde::Deserialize; + +use crate::date::Date; +use crate::error::Error; + +const DEFAULT_TABLE: &str = include_str!("default_seasons.toml"); + +#[derive(Clone, Debug, PartialEq)] +pub struct Season { + pub name: String, + pub start: Date, + /// Name of the game client's progression track holding this Season's Official Progress. + pub official_track: Option, +} + +#[derive(Deserialize)] +struct Table { + season: Vec, +} + +#[derive(Deserialize)] +struct Entry { + name: String, + start: toml::value::Datetime, + official_track: Option, +} + +/// The table shipped with the app, oldest first. +pub fn default_seasons() -> Vec { + parse(DEFAULT_TABLE).expect("the shipped Season table is valid") +} + +/// Reads the user's Season table at `path`, first writing the shipped one if the file does +/// not exist so the user can edit it. Returns the Seasons sorted by start. +pub fn load_seasons(path: &Path) -> Result, Error> { + let io_error = |e: std::io::Error| Error::Config(format!("{} : {e}", path.display())); + if !path.exists() { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(io_error)?; + } + std::fs::write(path, DEFAULT_TABLE).map_err(io_error)?; + } + let text = std::fs::read_to_string(path).map_err(io_error)?; + parse(&text).map_err(|e| Error::Config(format!("{} : {e}", path.display()))) +} + +fn parse(text: &str) -> Result, String> { + let table: Table = toml::from_str(text).map_err(|e| e.to_string())?; + let mut seasons = Vec::new(); + for entry in table.season { + let start = match entry.start { + toml::value::Datetime { + date: Some(d), + time: None, + offset: None, + } => Date { + year: i32::from(d.year), + month: d.month, + day: d.day, + }, + _ => { + return Err(format!( + "« {} » : `start` doit être une date (AAAA-MM-JJ)", + entry.name + )); + } + }; + seasons.push(Season { + name: entry.name, + start, + official_track: entry.official_track, + }); + } + seasons.sort_by_key(|s| s.start); + Ok(seasons) +} + +/// The period of a Season in epoch ms: from its start up to the next Season's start +/// (exclusive); the last one is open-ended. `seasons` must be sorted by start. +pub(crate) fn period(seasons: &[Season], name: &str) -> Option> { + let i = seasons.iter().position(|s| s.name == name)?; + let end = seasons + .get(i + 1) + .map_or(i64::MAX, |next| next.start.start_ms()); + Some(seasons[i].start.start_ms()..end) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_shipped_table_lists_the_known_seasons() { + let seasons: Vec<_> = default_seasons() + .into_iter() + .map(|s| (s.name, s.start.to_string())) + .collect(); + assert_eq!( + seasons, + [ + ("Saison 2025".into(), "05/03/2025".into()), + ("Saison 1 2026".into(), "08/01/2026".into()), + ("Saison 2 2026".into(), "29/04/2026".into()), + ] + ); + } + + #[test] + fn the_shipped_table_carries_the_official_track_names() { + let tracks: Vec<_> = default_seasons() + .into_iter() + .map(|s| s.official_track) + .collect(); + assert_eq!( + tracks, + [ + Some("Cherry 2025 Champs Completed Track".into()), + Some("2026 Season 1 Champs Completed Track".into()), + Some("2026 Season 2 Champs Completed Track".into()), + ] + ); + } + + #[test] + fn periods_run_to_the_next_start_and_the_last_is_open() { + let seasons = default_seasons(); + let first = period(&seasons, "Saison 2025").unwrap(); + assert_eq!(first.end, seasons[1].start.start_ms()); + assert_eq!(period(&seasons, "Saison 2 2026").unwrap().end, i64::MAX); + assert!(period(&seasons, "Inconnue").is_none()); + } +} diff --git a/crates/core/src/statistics.rs b/crates/core/src/statistics.rs new file mode 100644 index 0000000..caeea62 --- /dev/null +++ b/crates/core/src/statistics.rs @@ -0,0 +1,380 @@ +//! Challenge figures and champion statistics, computed on demand from stored Matches. +use std::cmp::Ordering; +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ops::Range; +use std::path::PathBuf; + +use crate::champions::Champion; +use crate::date::Date; +use crate::error::Error; +use crate::model::{Format, Match}; +use crate::seasons::{Season, period}; +use crate::tracker::Tracker; + +#[derive(Clone, Debug, PartialEq)] +pub enum SeasonScope { + /// By Season name. + Season(String), + AllSeasons, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Scope { + pub season: SeasonScope, + /// `None` = all Formats. Filters statistics only, never the Challenge. + pub format: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Statistics { + /// `None` in the all-Seasons view. + pub challenge: Option, + /// One per champion in the game, ordered by champion name. + pub rows: Vec, + pub charts: Charts, + /// Distinct Formats among all stored Matches of the Account, for the filter. + pub formats: Vec, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ChallengeSummary { + pub completed: usize, + pub total: usize, + /// All Attempts, including those on champions not yet Completed. + pub attempts: usize, + /// Over Completed champions only. + pub average_attempts: Option, + pub first_tries: usize, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChampionState { + Completed, + InProgress, + NeverPlayed, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct ChampionRow { + pub champion: Champion, + /// Only when the file exists in the portraits dir. + pub portrait: Option, + // In scope (Season and Format filter): + pub matches: usize, + pub best_placement: Option, + pub top1: usize, + pub wins: usize, + pub average_placement: Option, + pub last_match_ms: Option, + /// Season scope only, and not affected by the Format filter. + pub attempts: Option, + /// Season scope: always `Some`, not affected by the Format filter. All Seasons: + /// `Some(NeverPlayed)` for a champion with no stored Match, otherwise `None`. + pub state: Option, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Charts { + /// In scope: one entry per Placement from 1 to the highest seen, zero counts included. + pub placements: Vec<(u8, usize)>, + /// Season scope: the cumulative Completed count on each day a champion became Completed. + pub completed_over_time: Vec<(Date, usize)>, + /// Season scope: Completed champions that took 1, 2, 3, 4 and 5-or-more Attempts. + pub attempts_to_complete: [usize; 5], +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Column { + Champion, + Matches, + BestPlacement, + Top1, + Wins, + AveragePlacement, + Attempts, + LastMatch, + State, +} + +/// Sorts rows by a column. Rows with no value in it go last whatever the direction; ties +/// are broken by champion name. +pub fn sort_rows(rows: &mut [ChampionRow], column: Column, descending: bool) { + rows.sort_by(|a, b| { + let by_name = || { + collate(&a.champion.name) + .cmp(&collate(&b.champion.name)) + .then(a.champion.id.cmp(&b.champion.id)) + }; + if column == Column::Champion { + return if descending { + by_name().reverse() + } else { + by_name() + }; + } + match (value(a, column), value(b, column)) { + (Some(x), Some(y)) if descending => y.total_cmp(&x), + (Some(x), Some(y)) => x.total_cmp(&y), + (Some(_), None) => Ordering::Less, + (None, Some(_)) => Ordering::Greater, + (None, None) => Ordering::Equal, + } + .then_with(by_name) + }); +} + +fn value(row: &ChampionRow, column: Column) -> Option { + match column { + Column::Champion => None, + Column::Matches => Some(row.matches as f64), + Column::BestPlacement => row.best_placement.map(f64::from), + Column::Top1 => Some(row.top1 as f64), + Column::Wins => Some(row.wins as f64), + Column::AveragePlacement => row.average_placement, + Column::Attempts => row.attempts.map(|n| n as f64), + Column::LastMatch => row.last_match_ms.map(|ms| ms as f64), + Column::State => row.state.map(|state| match state { + ChampionState::Completed => 0.0, + ChampionState::InProgress => 1.0, + ChampionState::NeverPlayed => 2.0, + }), + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StateFilter { + All, + Completed, + /// In progress or never played. + Remaining, + NeverPlayed, +} + +impl StateFilter { + /// A row with no state is only kept by `All`. + pub fn keeps(&self, row: &ChampionRow) -> bool { + match self { + StateFilter::All => true, + StateFilter::Completed => row.state == Some(ChampionState::Completed), + StateFilter::Remaining => matches!( + row.state, + Some(ChampionState::InProgress | ChampionState::NeverPlayed) + ), + StateFilter::NeverPlayed => row.state == Some(ChampionState::NeverPlayed), + } + } +} + +/// Alphabetical order for French names: case and accents do not count. +fn collate(name: &str) -> String { + name.to_lowercase() + .chars() + .map(|c| match c { + 'à' | 'â' | 'ä' => 'a', + 'é' | 'è' | 'ê' | 'ë' => 'e', + 'î' | 'ï' => 'i', + 'ô' | 'ö' => 'o', + 'ù' | 'û' | 'ü' => 'u', + 'ç' => 'c', + other => other, + }) + .collect() +} + +#[derive(Default)] +struct Progress { + attempts: usize, + completed_at_ms: Option, +} + +/// Attempts per champion from Matches in chronological order: a champion's Matches count +/// up to and including its first top 1. +fn progress_by_champion(matches: &[&Match]) -> HashMap { + let mut progress: HashMap = HashMap::new(); + for m in matches { + let p = progress.entry(m.champion_id).or_default(); + if p.completed_at_ms.is_none() { + p.attempts += 1; + if m.placement == 1 { + p.completed_at_ms = Some(m.started_at_ms); + } + } + } + progress +} + +/// `matches` are all the Account's stored Matches, oldest first. `period` is the Season's +/// period (`None` = all Seasons). The Challenge only ever looks at the Season, never at `format`. +pub(crate) fn compute( + catalog: Vec, + matches: &[Match], + period: Option>, + format: Option, +) -> Statistics { + // A champion played but missing from the catalog still counts. + let mut champions = catalog; + let mut known: HashSet = champions.iter().map(|c| c.id).collect(); + for m in matches { + if known.insert(m.champion_id) { + champions.push(Champion { + id: m.champion_id, + key: m.champion_name.clone(), + name: m.champion_name.clone(), + }); + } + } + champions.sort_by_cached_key(|c| (collate(&c.name), c.id)); + + let in_period: Vec<&Match> = matches + .iter() + .filter(|m| period.as_ref().is_none_or(|p| p.contains(&m.started_at_ms))) + .collect(); + let in_scope: Vec<&Match> = in_period + .iter() + .copied() + .filter(|m| format.is_none_or(|f| m.format == f)) + .collect(); + let mut by_champion: HashMap> = HashMap::new(); + for m in &in_scope { + by_champion.entry(m.champion_id).or_default().push(m); + } + let progress = period.is_some().then(|| progress_by_champion(&in_period)); + let ever_played: HashSet = matches.iter().map(|m| m.champion_id).collect(); + + let rows: Vec = champions + .into_iter() + .map(|champion| { + let mine = by_champion.get(&champion.id).map_or(&[][..], Vec::as_slice); + let (attempts, state) = match &progress { + Some(progress) => { + let p = progress.get(&champion.id); + let state = match p { + Some(Progress { + completed_at_ms: Some(_), + .. + }) => ChampionState::Completed, + Some(_) => ChampionState::InProgress, + None => ChampionState::NeverPlayed, + }; + (Some(p.map_or(0, |p| p.attempts)), Some(state)) + } + None => ( + None, + (!ever_played.contains(&champion.id)).then_some(ChampionState::NeverPlayed), + ), + }; + ChampionRow { + portrait: None, + matches: mine.len(), + best_placement: mine.iter().map(|m| m.placement).min(), + top1: mine.iter().filter(|m| m.placement == 1).count(), + wins: mine.iter().filter(|m| m.win).count(), + average_placement: (!mine.is_empty()).then(|| { + mine.iter().map(|m| f64::from(m.placement)).sum::() / mine.len() as f64 + }), + last_match_ms: mine.iter().map(|m| m.started_at_ms).max(), + attempts, + state, + champion, + } + }) + .collect(); + + let highest = in_scope.iter().map(|m| m.placement).max().unwrap_or(0); + let placements = (1..=highest) + .map(|p| (p, in_scope.iter().filter(|m| m.placement == p).count())) + .collect(); + + let mut challenge = None; + let mut completed_over_time = Vec::new(); + let mut attempts_to_complete = [0; 5]; + if let Some(progress) = &progress { + let completed: Vec<(usize, i64)> = progress + .values() + .filter_map(|p| Some((p.attempts, p.completed_at_ms?))) + .collect(); + challenge = Some(ChallengeSummary { + completed: completed.len(), + total: rows.len(), + attempts: progress.values().map(|p| p.attempts).sum(), + average_attempts: (!completed.is_empty()).then(|| { + completed.iter().map(|(n, _)| n).sum::() as f64 / completed.len() as f64 + }), + first_tries: completed.iter().filter(|(n, _)| *n == 1).count(), + }); + let mut per_day: BTreeMap = BTreeMap::new(); + for &(attempts, ms) in &completed { + *per_day.entry(Date::from_ms(ms)).or_default() += 1; + attempts_to_complete[attempts.min(5) - 1] += 1; + } + let mut cumulative = 0; + completed_over_time = per_day + .into_iter() + .map(|(day, n)| { + cumulative += n; + (day, cumulative) + }) + .collect(); + } + + let mut formats: Vec = matches.iter().map(|m| m.format).collect(); + formats.sort(); + formats.dedup(); + + Statistics { + challenge, + rows, + charts: Charts { + placements, + completed_over_time, + attempts_to_complete, + }, + formats, + } +} + +impl Tracker { + /// Replaces the Season table; Matches are assigned to Seasons on demand, so already + /// stored Matches move accordingly. + pub fn with_seasons(mut self, mut seasons: Vec) -> Tracker { + seasons.sort_by_key(|s| s.start); + self.seasons = seasons; + self + } + + /// Oldest first. + pub fn seasons(&self) -> Vec { + self.seasons.clone() + } + + /// The Season containing `now_ms`. + pub fn current_season(&self, now_ms: i64) -> Option { + self.seasons + .iter() + .rev() + .find(|s| s.start.start_ms() <= now_ms) + .cloned() + } + + pub fn statistics(&self, puuid: &str, scope: &Scope) -> Result { + let season_period = match &scope.season { + SeasonScope::AllSeasons => None, + SeasonScope::Season(name) => Some( + period(&self.seasons, name).ok_or_else(|| Error::UnknownSeason(name.clone()))?, + ), + }; + let mut stats = compute( + self.cached_champions()?, + &self.matches(puuid)?, + season_period, + scope.format, + ); + if let Some((_, dir)) = &self.champions { + for row in &mut stats.rows { + let path = dir.join(format!("{}.png", row.champion.key)); + row.portrait = path.is_file().then_some(path); + } + } + Ok(stats) + } +} diff --git a/crates/core/src/tracker.rs b/crates/core/src/tracker.rs new file mode 100644 index 0000000..5334f78 --- /dev/null +++ b/crates/core/src/tracker.rs @@ -0,0 +1,492 @@ +use std::collections::HashSet; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::thread; + +use rusqlite::{Connection, OptionalExtension, Row, params}; +use serde::Deserialize; + +use crate::champions::ChampionSource; +use crate::client::GameClientSource; +use crate::error::{Error, SourceError}; +use crate::follow::Follow; +use crate::model::{Account, Format, Match, SyncProgress, SyncReport}; +use crate::seasons::{Season, default_seasons}; + +/// Port: where Match history comes from. Real adapter: `RiotApi`. +pub trait MatchHistorySource: Send + Sync { + fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result; + /// One page of Match ids for one queue, newest first. `start_time_s`: only Matches + /// started at or after this epoch second. + fn match_ids( + &self, + puuid: &str, + queue_id: u32, + start: usize, + count: usize, + start_time_s: Option, + ) -> Result, SourceError>; + /// The raw Match payload (JSON text) exactly as the API returned it. + fn fetch_match(&self, match_id: &str) -> Result; +} + +impl MatchHistorySource for Arc { + fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result { + (**self).resolve_account(game_name, tag_line) + } + + fn match_ids( + &self, + puuid: &str, + queue_id: u32, + start: usize, + count: usize, + start_time_s: Option, + ) -> Result, SourceError> { + (**self).match_ids(puuid, queue_id, start, count, start_time_s) + } + + fn fetch_match(&self, match_id: &str) -> Result { + (**self).fetch_match(match_id) + } +} + +const SCHEMA: &str = " +PRAGMA journal_mode = WAL; +CREATE TABLE IF NOT EXISTS accounts ( + puuid TEXT PRIMARY KEY, + game_name TEXT NOT NULL, + tag_line TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS matches ( + puuid TEXT NOT NULL, + match_id TEXT NOT NULL, + queue_id INTEGER NOT NULL, + champion_id INTEGER NOT NULL, + champion_name TEXT NOT NULL, + placement INTEGER NOT NULL, + win INTEGER NOT NULL, + started_at_ms INTEGER NOT NULL, + raw TEXT NOT NULL, + PRIMARY KEY (puuid, match_id) +); +CREATE TABLE IF NOT EXISTS champions ( + id INTEGER PRIMARY KEY, + key TEXT NOT NULL, + name TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS meta ( + name TEXT PRIMARY KEY, + value TEXT NOT NULL +);"; + +/// Arena queues Riot lists Matches under (the PBE queue 1704 is left out on purpose). +const QUEUES: [u32; 4] = [1700, 1710, 1740, 1750]; +const PAGE_SIZE: usize = 100; +const RATE_LIMIT_RETRIES: usize = 5; +/// A Match is published when the whole game ends, so one that started before the newest +/// stored Match (a player eliminated early who queued again) can show up later. +const OVERLAP_S: i64 = 48 * 3600; + +pub struct Tracker { + db: Mutex, + history: Box, + pub(crate) seasons: Vec, + pub(crate) champions: Option<(Box, PathBuf)>, + pub(crate) client: Option>, + pub(crate) follow: Mutex, + /// Held for a whole `sync`: a second one waits for the first instead of importing in parallel. + sync_lock: Mutex<()>, +} + +impl Tracker { + pub fn open(db_path: &Path, history: Box) -> Result { + let db = Connection::open(db_path)?; + db.execute_batch(SCHEMA)?; + Ok(Tracker { + db: Mutex::new(db), + history, + seasons: default_seasons(), + champions: None, + client: None, + follow: Mutex::default(), + sync_lock: Mutex::new(()), + }) + } + + /// Imports every Arena Match the source holds for the Account with this Riot ID + /// (`GameName#TAG`, split on the last `#`). + pub fn sync( + &self, + riot_id: &str, + on_progress: &mut dyn FnMut(SyncProgress), + ) -> Result { + let _serial = self + .sync_lock + .lock() + .unwrap_or_else(PoisonError::into_inner); + let (game_name, tag_line) = riot_id + .trim() + .rsplit_once('#') + .filter(|(name, tag)| !name.is_empty() && !tag.is_empty()) + .ok_or_else(|| Error::InvalidRiotId(riot_id.into()))?; + let account = with_retry(|| self.history.resolve_account(game_name, tag_line))?; + // shortcut: Riot API puuids are scoped to the API key's application, so the same Riot ID under another key becomes a second Account; merging them safely needs proof of identity. + self.db().execute( + "INSERT INTO accounts (puuid, game_name, tag_line) VALUES (?1, ?2, ?3) + ON CONFLICT (puuid) DO UPDATE SET game_name = excluded.game_name, tag_line = excluded.tag_line", + params![account.puuid, account.game_name, account.tag_line], + )?; + + // Only the Matches since the last complete sync can be missing. The mark moves when a + // sync completes, never as Matches get stored, so a cut sync lists the same ones again. + let since_s = self + .synced_until_ms(&account.puuid)? + .map(|ms| ms / 1000 - OVERLAP_S); + let mut known = self.match_ids_stored(&account.puuid)?; + let mut to_fetch = self.list_match_ids(&account.puuid, since_s)?; + to_fetch.retain(|id| known.insert(id.clone())); + + let total = to_fetch.len(); + on_progress(SyncProgress { + fetched: 0, + to_fetch: total, + }); + let mut added = 0; + for (i, match_id) in to_fetch.iter().enumerate() { + // Stored at once, so an interrupted import loses nothing. + if self.fetch_and_store(&account.puuid, match_id)? == Fetched::Added { + added += 1; + } + on_progress(SyncProgress { + fetched: i + 1, + to_fetch: total, + }); + } + + if let Some(newest_ms) = self.latest_start_ms(&account.puuid)? { + self.db().execute( + "INSERT OR REPLACE INTO meta (name, value) VALUES (?1, ?2)", + params![synced_until_key(&account.puuid), newest_ms.to_string()], + )?; + } + let stored = self.match_count(&account.puuid)?; + self.clear_problem(added); + Ok(SyncReport { + account, + added, + stored, + }) + } + + /// Fetches one Match by id and stores it. A Match Riot does not have or that cannot be + /// read is skipped rather than failing the caller: one bad id must not block the rest. + pub(crate) fn fetch_and_store(&self, puuid: &str, match_id: &str) -> Result { + let raw = match with_retry(|| self.history.fetch_match(match_id)) { + Ok(raw) => raw, + Err(SourceError::NotFound) => return Ok(Fetched::NotFound), + Err(e) => return Err(e.into()), + }; + let Ok(Some((m, queue_id))) = decode_match(&raw, puuid) else { + return Ok(Fetched::Ignored); + }; + let inserted = insert_match(&self.db(), puuid, &m, queue_id, &raw)?; + Ok(if inserted { + Fetched::Added + } else { + Fetched::Known + }) + } + + pub fn accounts(&self) -> Result, Error> { + let db = self.db(); + let mut stmt = db.prepare( + "SELECT puuid, game_name, tag_line FROM accounts ORDER BY game_name, tag_line", + )?; + let accounts = stmt + .query_map([], account_from_row)? + .collect::>()?; + Ok(accounts) + } + + /// Stored Matches of the Account, oldest first. + pub fn matches(&self, puuid: &str) -> Result, Error> { + let db = self.db(); + let mut stmt = db.prepare( + "SELECT match_id, queue_id, champion_id, champion_name, placement, win, started_at_ms + FROM matches WHERE puuid = ?1 ORDER BY started_at_ms, match_id", + )?; + let matches = stmt + .query_map([puuid], |row| { + let queue_id: u32 = row.get(1)?; + Ok(Match { + match_id: row.get(0)?, + format: Format::from_queue(queue_id).unwrap_or(Format::Other(queue_id)), + champion_id: row.get(2)?, + champion_name: row.get(3)?, + placement: row.get(4)?, + win: row.get(5)?, + started_at_ms: row.get(6)?, + }) + })? + .collect::>()?; + Ok(matches) + } + + pub fn match_count(&self, puuid: &str) -> Result { + Ok(self.db().query_row( + "SELECT COUNT(*) FROM matches WHERE puuid = ?1", + [puuid], + |row| row.get::<_, i64>(0), + )? as usize) + } + + /// The lock is only ever held around one short DB operation, never across a source call. + pub(crate) fn db(&self) -> MutexGuard<'_, Connection> { + self.db.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn synced_until_ms(&self, puuid: &str) -> Result, Error> { + let mark: Option = self + .db() + .query_row( + "SELECT value FROM meta WHERE name = ?1", + [synced_until_key(puuid)], + |row| row.get(0), + ) + .optional()?; + Ok(mark.and_then(|ms| ms.parse().ok())) + } + + /// 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 + .db() + .query_row( + "SELECT match_id FROM matches WHERE puuid = ?1 ORDER BY started_at_ms DESC LIMIT 1", + [puuid], + |row| row.get(0), + ) + .optional()?; + Ok(id.and_then(|id| id.split_once('_').map(|(platform, _)| platform.into()))) + } + + fn latest_start_ms(&self, puuid: &str) -> Result, Error> { + Ok(self.db().query_row( + "SELECT MAX(started_at_ms) FROM matches WHERE puuid = ?1", + [puuid], + |row| row.get(0), + )?) + } + + fn match_ids_stored(&self, puuid: &str) -> Result, Error> { + let db = self.db(); + let mut stmt = db.prepare("SELECT match_id FROM matches WHERE puuid = ?1")?; + let ids = stmt + .query_map([puuid], |row| row.get(0))? + .collect::>()?; + Ok(ids) + } + + fn list_match_ids(&self, puuid: &str, since_s: Option) -> Result, Error> { + let mut ids = Vec::new(); + for queue_id in QUEUES { + let mut start = 0; + loop { + let page = with_retry(|| { + self.history + .match_ids(puuid, queue_id, start, PAGE_SIZE, since_s) + })?; + let full_page = page.len() == PAGE_SIZE; + ids.extend(page); + if !full_page { + break; + } + start += PAGE_SIZE; + } + } + Ok(ids) + } +} + +pub(crate) fn account_from_row(row: &Row) -> rusqlite::Result { + Ok(Account { + puuid: row.get(0)?, + game_name: row.get(1)?, + tag_line: row.get(2)?, + }) +} + +fn synced_until_key(puuid: &str) -> String { + format!("synced_until_ms:{puuid}") +} + +/// What became of one Match fetched by id. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Fetched { + Added, + /// Already stored. + Known, + /// Not an Arena Match of this Account, or unreadable. + Ignored, + /// Riot does not have it (yet). + NotFound, +} + +/// Waits out `RateLimited` and retries the same call, giving up after a few attempts. +fn with_retry(mut call: impl FnMut() -> Result) -> Result { + for _ in 0..RATE_LIMIT_RETRIES { + match call() { + Err(SourceError::RateLimited { retry_after }) => thread::sleep(retry_after), + result => return result, + } + } + call() +} + +/// Returns whether the Match was new. +fn insert_match( + db: &Connection, + puuid: &str, + m: &Match, + queue_id: u32, + raw: &str, +) -> rusqlite::Result { + let inserted = db.execute( + "INSERT OR IGNORE INTO matches + (puuid, match_id, queue_id, champion_id, champion_name, placement, win, started_at_ms, raw) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", + params![ + puuid, + m.match_id, + queue_id, + m.champion_id, + m.champion_name, + m.placement, + m.win, + m.started_at_ms, + raw + ], + )?; + Ok(inserted == 1) +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Payload { + metadata: PayloadMetadata, + info: PayloadInfo, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct PayloadMetadata { + match_id: String, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct PayloadInfo { + queue_id: u32, + game_mode: String, + game_start_timestamp: i64, + /// Read one by one: only the Account's own entry has to be complete. + participants: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Participant { + champion_id: u32, + champion_name: String, + placement: u8, + win: bool, +} + +/// The Match (with its raw queue id) the Account played in a Riot match-v5 payload, or +/// `None` when the payload is not an Arena Match of this Account. +fn decode_match(raw: &str, puuid: &str) -> Result, serde_json::Error> { + let payload: Payload = serde_json::from_str(raw)?; + let info = payload.info; + if info.game_mode != "CHERRY" { + return Ok(None); + } + let Some(format) = Format::from_queue(info.queue_id) else { + return Ok(None); + }; + let Some(me) = info.participants.into_iter().find(|p| p["puuid"] == puuid) else { + return Ok(None); + }; + let me: Participant = serde_json::from_value(me)?; + let m = Match { + match_id: payload.metadata.match_id, + format, + champion_id: me.champion_id, + champion_name: me.champion_name, + placement: me.placement, + win: me.win, + started_at_ms: info.game_start_timestamp, + }; + Ok(Some((m, info.queue_id))) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + const FIXTURE: &str = include_str!("../tests/fixtures/riot/match_1740_EUW1_9000000005.json"); + + #[test] + fn decodes_the_accounts_participant() { + let (m, queue_id) = decode_match(FIXTURE, "fixture-puuid-self") + .unwrap() + .unwrap(); + assert_eq!(queue_id, 1740); + assert_eq!( + m, + Match { + match_id: "EUW1_9000000005".into(), + format: Format::BraveryArena, + champion_id: 19, + champion_name: "Warwick".into(), + placement: 5, + win: false, + started_at_ms: 1794424080842, + } + ); + } + + #[test] + fn ignores_payloads_without_the_account() { + assert!(decode_match(FIXTURE, "someone-else").unwrap().is_none()); + } + + #[test] + fn raw_payload_is_stored_unmodified_and_only_once() { + let db = Connection::open_in_memory().unwrap(); + db.execute_batch(SCHEMA).unwrap(); + let (m, queue_id) = decode_match(FIXTURE, "fixture-puuid-self") + .unwrap() + .unwrap(); + assert!(insert_match(&db, "p", &m, queue_id, FIXTURE).unwrap()); + assert!(!insert_match(&db, "p", &m, queue_id, FIXTURE).unwrap()); + let raw: String = db + .query_row("SELECT raw FROM matches", [], |row| row.get(0)) + .unwrap(); + assert_eq!(raw, FIXTURE); + } + + #[test] + fn rate_limit_is_retried_a_few_times_then_reported() { + let mut calls = 0; + let result: Result<(), _> = with_retry(|| { + calls += 1; + Err(SourceError::RateLimited { + retry_after: Duration::ZERO, + }) + }); + assert!(matches!(result, Err(SourceError::RateLimited { .. }))); + assert_eq!(calls, RATE_LIMIT_RETRIES + 1); + } +} diff --git a/crates/core/tests/champions.rs b/crates/core/tests/champions.rs new file mode 100644 index 0000000..460790e --- /dev/null +++ b/crates/core/tests/champions.rs @@ -0,0 +1,248 @@ +mod common; + +use std::sync::atomic::Ordering; + +use arena_tracker_core::{ + ChampionState, Error, Scope, SeasonScope, Statistics, Tracker, default_seasons, load_seasons, +}; +use common::{ + CATALOG, FakeChampions, FakeHistory, SELF_PUUID, jan_2026, open_tracker, played_match, + recorded_account, +}; + +fn statistics(tracker: &Tracker) -> Statistics { + let scope = Scope { + season: SeasonScope::Season(common::S1.into()), + format: None, + }; + tracker.statistics(SELF_PUUID, &scope).unwrap() +} + +fn row_names(stats: &Statistics) -> Vec<&str> { + stats + .rows + .iter() + .map(|r| r.champion.name.as_str()) + .collect() +} + +/// A tracker on the same database file as `open_tracker`, whose history is empty. +fn reopen(dir: &std::path::Path, champions: FakeChampions) -> Tracker { + Tracker::open( + &dir.join("arena.db"), + Box::new(FakeHistory::new(recorded_account(), vec![])), + ) + .unwrap() + .with_seasons(common::seasons()) + .with_champions(Box::new(champions), dir.join("portraits")) +} + +#[test] +fn the_catalog_is_fetched_once_while_the_game_version_is_unchanged() { + let dir = tempfile::tempdir().unwrap(); + let first = FakeChampions::new("1.0", &CATALOG); + let first_calls = first.catalog_counter(); + let tracker = reopen(dir.path(), first); + + tracker.refresh_champions().unwrap(); + tracker.refresh_champions().unwrap(); + + assert_eq!(first_calls.load(Ordering::SeqCst), 1); + assert_eq!(statistics(&tracker).challenge.unwrap().total, 6); + drop(tracker); + + let same_version = FakeChampions::new("1.0", &CATALOG); + let same_calls = same_version.catalog_counter(); + reopen(dir.path(), same_version) + .refresh_champions() + .unwrap(); + assert_eq!(same_calls.load(Ordering::SeqCst), 0); + + let mut grown = CATALOG.to_vec(); + grown.push((777, "Newcomer", "Nouveau")); + let new_version = FakeChampions::new("2.0", &grown); + let new_calls = new_version.catalog_counter(); + let tracker = reopen(dir.path(), new_version); + tracker.refresh_champions().unwrap(); + assert_eq!(new_calls.load(Ordering::SeqCst), 1); + assert_eq!(statistics(&tracker).challenge.unwrap().total, 7); +} + +#[test] +fn a_failing_source_leaves_the_cached_catalog_usable() { + let dir = tempfile::tempdir().unwrap(); + reopen(dir.path(), FakeChampions::new("1.0", &CATALOG)) + .refresh_champions() + .unwrap(); + + let offline = reopen(dir.path(), FakeChampions::new("2.0", &CATALOG).failing()); + + assert!(matches!(offline.refresh_champions(), Err(Error::Source(_)))); + assert_eq!(statistics(&offline).challenge.unwrap().total, 6); +} + +#[test] +fn without_any_catalog_the_page_shows_the_champions_played() { + let dir = tempfile::tempdir().unwrap(); + let tracker = open_tracker(dir.path(), &[played_match(1, 3, jan_2026(2, 0))]).with_champions( + Box::new(FakeChampions::new("1.0", &CATALOG).failing()), + dir.path().join("portraits"), + ); + assert!(tracker.refresh_champions().is_err()); + tracker.sync(common::RIOT_ID, &mut |_| {}).unwrap(); + + let stats = statistics(&tracker); + + assert_eq!(row_names(&stats), ["Annie"]); + assert_eq!(stats.challenge.unwrap().total, 1); +} + +#[test] +fn a_champion_played_but_absent_from_the_catalog_still_gets_a_row() { + let dir = tempfile::tempdir().unwrap(); + let tracker = open_tracker(dir.path(), &[played_match(1, 3, jan_2026(2, 0))]).with_champions( + Box::new(FakeChampions::new("1.0", &CATALOG[1..])), + dir.path().join("portraits"), + ); + tracker.refresh_champions().unwrap(); + tracker.sync(common::RIOT_ID, &mut |_| {}).unwrap(); + + let stats = statistics(&tracker); + + assert_eq!(stats.rows.len(), 6); + let annie = stats.rows.iter().find(|r| r.champion.id == 1).unwrap(); + assert_eq!( + (annie.champion.key.as_str(), annie.champion.name.as_str()), + ("Annie", "Annie") + ); + assert_eq!(annie.state, Some(ChampionState::InProgress)); + assert_eq!(stats.challenge.unwrap().total, 6); +} + +#[test] +fn rows_are_ordered_by_champion_name_in_french_order() { + let dir = tempfile::tempdir().unwrap(); + let champions = [ + (1, "Zoe", "Zoé"), + (2, "Zed", "Zed"), + (11, "MasterYi", "Maître Yi"), + (3, "Nami", "Nami"), + ]; + let tracker = reopen(dir.path(), FakeChampions::new("1.0", &champions)); + tracker.refresh_champions().unwrap(); + + assert_eq!( + row_names(&statistics(&tracker)), + ["Maître Yi", "Nami", "Zed", "Zoé"] + ); +} + +#[test] +fn portraits_are_downloaded_and_exposed_and_a_failed_one_is_left_out() { + let dir = tempfile::tempdir().unwrap(); + let tracker = reopen( + dir.path(), + FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"), + ); + + assert!( + statistics(&tracker) + .rows + .iter() + .all(|r| r.portrait.is_none()) + ); + tracker.refresh_champions().unwrap(); + + let stats = statistics(&tracker); + let portraits = dir.path().join("portraits"); + for row in &stats.rows { + if row.champion.key == "Jinx" { + assert_eq!(row.portrait, None); + } else { + let path = portraits.join(format!("{}.png", row.champion.key)); + assert_eq!(row.portrait.as_ref(), Some(&path)); + assert_eq!( + std::fs::read(&path).unwrap(), + format!("png of {}", row.champion.key).into_bytes() + ); + } + } + assert!(!portraits.join("Jinx.part").exists()); +} + +#[test] +fn refreshing_without_a_champion_source_does_nothing() { + let dir = tempfile::tempdir().unwrap(); + let tracker = open_tracker(dir.path(), &[]); + + tracker.refresh_champions().unwrap(); + + assert!(!dir.path().join("portraits").exists()); +} + +#[test] +fn load_seasons_writes_the_shipped_table_when_the_file_is_missing() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("sub").join("seasons.toml"); + + let seasons = load_seasons(&path).unwrap(); + + assert_eq!(seasons, default_seasons()); + assert!( + std::fs::read_to_string(&path) + .unwrap() + .contains("[[season]]") + ); + assert_eq!(load_seasons(&path).unwrap(), seasons); +} + +#[test] +fn load_seasons_reads_the_edited_file_sorted_by_start() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("seasons.toml"); + std::fs::write( + &path, + "[[season]]\nname = \"Plus tard\"\nstart = 2027-02-01\nofficial_track = \"Piste X\"\n\n[[season]]\nname = \"Avant\"\nstart = 2026-12-31\n", + ) + .unwrap(); + + let seasons = load_seasons(&path).unwrap(); + + let summary: Vec<_> = seasons + .iter() + .map(|s| (s.name.as_str(), s.start.to_string())) + .collect(); + assert_eq!( + summary, + [ + ("Avant", "31/12/2026".to_string()), + ("Plus tard", "01/02/2027".to_string()) + ] + ); + let tracks: Vec<_> = seasons + .iter() + .map(|s| s.official_track.as_deref()) + .collect(); + assert_eq!(tracks, [None, Some("Piste X")]); +} + +#[test] +fn load_seasons_rejects_invalid_files() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("seasons.toml"); + for bad in [ + "pas du toml", + "", + "[[season]]\nname = \"X\"\nstart = 2026-01-01T10:00:00\n", + "[[season]]\nname = \"X\"\nstart = 2026-01-01T10:00:00Z\n", + "[[season]]\nname = \"X\"\nstart = \"2026-01-01\"\n", + "[[season]]\nname = \"X\"\n", + "[[season]]\nstart = 2026-01-01\n", + ] { + std::fs::write(&path, bad).unwrap(); + assert!( + matches!(load_seasons(&path), Err(Error::Config(_))), + "{bad:?}" + ); + } +} diff --git a/crates/core/tests/common/mod.rs b/crates/core/tests/common/mod.rs new file mode 100644 index 0000000..3c9ccf5 --- /dev/null +++ b/crates/core/tests/common/mod.rs @@ -0,0 +1,671 @@ +//! Test doubles and payload builders shared by the integration tests. +// Each test binary uses its own subset of these helpers. +#![allow(dead_code)] + +use std::collections::HashMap; +use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{Receiver, Sender}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use arena_tracker_core::{ + Account, Champion, ChampionCatalog, ChampionSource, ClientError, Date, GameClientSource, + GamePhase, Gameflow, MatchHistorySource, Season, SourceError, Tracker, +}; +use serde_json::Value; + +pub const SELF_PUUID: &str = "fixture-puuid-self"; + +const BASE: &str = include_str!("../fixtures/riot/match_1750_EUW1_9000000006.json"); + +/// The six recorded Riot payloads. +pub fn recorded_matches() -> Vec { + [ + include_str!("../fixtures/riot/match_1700_EUW1_9000000001.json"), + include_str!("../fixtures/riot/match_1700_EUW1_9000000002.json"), + include_str!("../fixtures/riot/match_1740_EUW1_9000000004.json"), + include_str!("../fixtures/riot/match_1740_EUW1_9000000005.json"), + include_str!("../fixtures/riot/match_1750_EUW1_9000000003.json"), + include_str!("../fixtures/riot/match_1750_EUW1_9000000006.json"), + ] + .map(String::from) + .to_vec() +} + +pub fn recorded_account() -> Account { + serde_json::from_str(include_str!("../fixtures/riot/account.json")).unwrap() +} + +/// A payload cloned from a recorded one, with the self participant patched. +pub fn payload( + match_id: &str, + queue_id: u32, + champion_id: u32, + champion_name: &str, + placement: u8, + win: bool, + started_at_ms: i64, +) -> String { + let mut v: Value = serde_json::from_str(BASE).unwrap(); + v["metadata"]["matchId"] = match_id.into(); + v["info"]["queueId"] = queue_id.into(); + v["info"]["gameStartTimestamp"] = started_at_ms.into(); + let me = v["info"]["participants"] + .as_array_mut() + .unwrap() + .iter_mut() + .find(|p| p["puuid"] == SELF_PUUID) + .unwrap(); + me["championId"] = champion_id.into(); + me["championName"] = champion_name.into(); + me["placement"] = placement.into(); + me["win"] = win.into(); + v.to_string() +} + +pub fn with_game_mode(payload: &str, game_mode: &str) -> String { + let mut v: Value = serde_json::from_str(payload).unwrap(); + v["info"]["gameMode"] = game_mode.into(); + v.to_string() +} + +/// The payload with these fields missing from every participant but the Account. +pub fn without_fields_for_others(payload: &str, fields: &[&str]) -> String { + let mut v: Value = serde_json::from_str(payload).unwrap(); + for p in v["info"]["participants"].as_array_mut().unwrap() { + if p["puuid"] != SELF_PUUID { + for field in fields { + p.as_object_mut().unwrap().remove(*field); + } + } + } + v.to_string() +} + +pub fn played_by(payload: &str, puuid: &str) -> String { + payload.replace(SELF_PUUID, puuid) +} + +fn queue_and_start(raw: &str) -> (u32, i64) { + let v: Value = serde_json::from_str(raw).unwrap(); + ( + v["info"]["queueId"].as_u64().unwrap() as u32, + v["info"]["gameStartTimestamp"].as_i64().unwrap(), + ) +} + +fn match_id(raw: &str) -> String { + let v: Value = serde_json::from_str(raw).unwrap(); + v["metadata"]["matchId"].as_str().unwrap().to_string() +} + +struct Listing { + owner: String, + /// The queue the id is listed under. + queue_id: u32, + match_id: String, + started_ms: i64, + /// `None`: Riot lists the id but answers "not found" when asked for it. + raw: Option, + /// Unlisted Matches can only be fetched by their id. + listed: bool, +} + +impl Listing { + fn of(owner: &str, raw: String) -> Listing { + let (queue_id, started_ms) = queue_and_start(&raw); + Listing { + owner: owner.into(), + queue_id, + match_id: match_id(&raw), + started_ms, + raw: Some(raw), + listed: true, + } + } +} + +/// In-memory Match history that behaves like Riot's (newest first, paged, filtered by queue). +pub struct FakeHistory { + accounts: Vec, + listings: Mutex>, + /// Every call fails with this until it is cleared. + failure: Mutex>, + fail_after: Option, + rate_limit_once: AtomicBool, + /// Lists in the order the Matches were added instead of newest first. + as_given: bool, + /// Called at the start of every fetch: announces it, then waits to be released. + gate: Option<(Sender<()>, Mutex>)>, + fetches: Arc, + listed: Arc, + calls: Arc, +} + +impl FakeHistory { + pub fn new(account: Account, payloads: Vec) -> FakeHistory { + FakeHistory { + accounts: Vec::new(), + listings: Mutex::default(), + failure: Mutex::default(), + fail_after: None, + rate_limit_once: AtomicBool::new(false), + as_given: false, + gate: None, + fetches: Arc::default(), + listed: Arc::default(), + calls: Arc::default(), + } + .with_account(account, payloads) + } + + /// Another Account Riot can resolve; its payloads must have been built for its puuid. + pub fn with_account(mut self, account: Account, payloads: Vec) -> FakeHistory { + for raw in payloads { + self.add_for(&account.puuid, raw); + } + self.accounts.push(account); + self + } + + /// Lists a payload under a queue other than its own: a sync only asks for Arena queues. + pub fn listed_under(self, queue_id: u32, payload: String) -> FakeHistory { + let owner = self.accounts[0].puuid.clone(); + self.listings.lock().unwrap().push(Listing { + queue_id, + ..Listing::of(&owner, payload) + }); + self + } + + /// A Match that appears for the first Account (e.g. one that has just been played). + pub fn add(&self, payload: String) { + self.add_for(&self.accounts[0].puuid, payload); + } + + pub fn add_for(&self, puuid: &str, raw: String) { + self.listings.lock().unwrap().push(Listing::of(puuid, raw)); + } + + /// A Match Riot has but does not list, like one of a queue the app does not know. + pub fn add_unlisted(&self, payload: String) { + let owner = self.accounts[0].puuid.clone(); + self.listings.lock().unwrap().push(Listing { + listed: false, + ..Listing::of(&owner, payload) + }); + } + + /// An id Riot lists (Arena 3x6) but cannot deliver. + pub fn add_missing(&self, match_id: &str, started_ms: i64) { + self.add_broken(match_id, started_ms, None); + } + + /// An id Riot lists (Arena 3x6) whose payload is not a readable Match. + pub fn add_unreadable(&self, match_id: &str, started_ms: i64, text: &str) { + self.add_broken(match_id, started_ms, Some(text.into())); + } + + fn add_broken(&self, match_id: &str, started_ms: i64, raw: Option) { + let owner = self.accounts[0].puuid.clone(); + self.listings.lock().unwrap().push(Listing { + owner, + queue_id: 1750, + match_id: match_id.into(), + started_ms, + raw, + listed: true, + }); + } + + /// Lists Matches in the order they were added, however old they are. + pub fn delivered_as_given(mut self) -> FakeHistory { + self.as_given = true; + self + } + + /// Every call fails with this error until `None` is set. + pub fn fail_with(&self, error: Option) { + *self.failure.lock().unwrap() = error; + } + + /// Every fetch after the first `n` fails with a network error. + pub fn failing_after(mut self, n: usize) -> FakeHistory { + self.fail_after = Some(n); + self + } + + /// The first fetch answers "rate limited" once. + pub fn rate_limited_once(mut self) -> FakeHistory { + self.rate_limit_once = AtomicBool::new(true); + self + } + + /// Each fetch sends on `entered`, then blocks until `release` delivers. + pub fn gated(mut self, entered: Sender<()>, release: Receiver<()>) -> FakeHistory { + self.gate = Some((entered, Mutex::new(release))); + self + } + + /// Payloads delivered by `fetch_match`, still readable after the fake is boxed. + pub fn fetch_counter(&self) -> Arc { + self.fetches.clone() + } + + /// Match ids returned by `match_ids`. + pub fn listed_counter(&self) -> Arc { + self.listed.clone() + } + + /// Calls of any kind made to the source. + pub fn call_counter(&self) -> Arc { + self.calls.clone() + } + + fn enter(&self) -> Result<(), SourceError> { + self.calls.fetch_add(1, Ordering::SeqCst); + match &*self.failure.lock().unwrap() { + Some(error) => Err(error.clone()), + None => Ok(()), + } + } +} + +impl MatchHistorySource for FakeHistory { + fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result { + self.enter()?; + // Riot IDs are case-insensitive for Riot, too. + self.accounts + .iter() + .find(|a| { + a.game_name.eq_ignore_ascii_case(game_name) + && a.tag_line.eq_ignore_ascii_case(tag_line) + }) + .cloned() + .ok_or(SourceError::NotFound) + } + + fn match_ids( + &self, + puuid: &str, + queue_id: u32, + start: usize, + count: usize, + start_time_s: Option, + ) -> Result, SourceError> { + self.enter()?; + let mut found: Vec<_> = self + .listings + .lock() + .unwrap() + .iter() + .filter(|l| l.listed && l.owner == puuid && l.queue_id == queue_id) + .filter(|l| start_time_s.is_none_or(|t| l.started_ms / 1000 >= t)) + .map(|l| (l.started_ms, l.match_id.clone())) + .collect(); + if !self.as_given { + found.sort_by_key(|(started_ms, _)| std::cmp::Reverse(*started_ms)); + } + let page: Vec = found + .into_iter() + .skip(start) + .take(count) + .map(|(_, id)| id) + .collect(); + self.listed.fetch_add(page.len(), Ordering::SeqCst); + Ok(page) + } + + fn fetch_match(&self, id: &str) -> Result { + self.enter()?; + if let Some((entered, release)) = &self.gate { + entered.send(()).unwrap(); + release.lock().unwrap().recv().unwrap(); + } + if self.rate_limit_once.swap(false, Ordering::SeqCst) { + return Err(SourceError::RateLimited { + retry_after: Duration::ZERO, + }); + } + if self + .fail_after + .is_some_and(|n| self.fetches.load(Ordering::SeqCst) >= n) + { + return Err(SourceError::Network("connexion perdue".into())); + } + let raw = self + .listings + .lock() + .unwrap() + .iter() + .find(|l| l.match_id == id) + .and_then(|l| l.raw.clone()) + .ok_or(SourceError::NotFound)?; + self.fetches.fetch_add(1, Ordering::SeqCst); + Ok(raw) + } +} + +/// Champion reference data served from memory. +pub struct FakeChampions { + version: String, + champions: Vec, + failing: bool, + no_portrait: Vec, + catalog_calls: Arc, +} + +impl FakeChampions { + /// `champions`: (id, key, display name). + pub fn new(version: &str, champions: &[(u32, &str, &str)]) -> FakeChampions { + FakeChampions { + version: version.into(), + champions: champions + .iter() + .map(|&(id, key, name)| Champion { + id, + key: key.into(), + name: name.into(), + }) + .collect(), + failing: false, + no_portrait: Vec::new(), + catalog_calls: Arc::default(), + } + } + + /// Every call fails with a network error. + pub fn failing(mut self) -> FakeChampions { + self.failing = true; + self + } + + /// The portrait download of this champion key fails. + pub fn without_portrait(mut self, key: &str) -> FakeChampions { + self.no_portrait.push(key.into()); + self + } + + pub fn catalog_counter(&self) -> Arc { + self.catalog_calls.clone() + } + + fn check(&self) -> Result<(), SourceError> { + if self.failing { + Err(SourceError::Network("hors ligne".into())) + } else { + Ok(()) + } + } +} + +impl ChampionSource for FakeChampions { + fn latest_version(&self) -> Result { + self.check()?; + Ok(self.version.clone()) + } + + fn catalog(&self, version: &str) -> Result { + self.catalog_calls.fetch_add(1, Ordering::SeqCst); + self.check()?; + Ok(ChampionCatalog { + version: version.into(), + champions: self.champions.clone(), + }) + } + + fn portrait(&self, _version: &str, key: &str) -> Result, SourceError> { + self.check()?; + if self.no_portrait.iter().any(|k| k == key) { + return Err(SourceError::NotFound); + } + Ok(format!("png of {key}").into_bytes()) + } +} + +// Statistics scenarios: a small catalog, two Seasons and Matches described by champion and Placement. + +pub const RIOT_ID: &str = "Joueur#EUW"; +pub const HOUR_MS: i64 = 3_600_000; +pub const S1: &str = "Saison A"; +pub const S2: &str = "Saison B"; +/// The name of the progression track recorded from the real client for the Season 2 2026. +pub const S2_TRACK: &str = "2026 Season 2 Champs Completed Track"; + +/// (id, key, French name) +pub const CATALOG: [(u32, &str, &str); 6] = [ + (1, "Annie", "Annie"), + (8, "Vladimir", "Vladimir"), + (11, "MasterYi", "Maître Yi"), + (19, "Warwick", "Warwick"), + (103, "Ahri", "Ahri"), + (222, "Jinx", "Jinx"), +]; + +pub fn date(year: i32, month: u8, day: u8) -> Date { + Date { year, month, day } +} + +/// `hours` after 00:00 UTC of `date`. +pub fn at(date: Date, hours: i64) -> i64 { + date.start_ms() + hours * HOUR_MS +} + +/// `hours` after 00:00 UTC on a day of January 2026 (inside S1). +pub fn jan_2026(day: u8, hours: i64) -> i64 { + at(date(2026, 1, day), hours) +} + +/// S1 starts on 2026-01-01 and S2 on 2026-04-01; only S2 has an official track. +pub fn seasons() -> Vec { + vec![ + Season { + name: S1.into(), + start: date(2026, 1, 1), + official_track: None, + }, + Season { + name: S2.into(), + start: date(2026, 4, 1), + official_track: Some(S2_TRACK.into()), + }, + ] +} + +#[derive(Clone)] +pub struct PlayedMatch { + pub champion: u32, + pub placement: u8, + pub queue_id: u32, + pub started_at_ms: i64, +} + +/// An Arena 3x6 Match. +pub fn played_match(champion: u32, placement: u8, started_at_ms: i64) -> PlayedMatch { + PlayedMatch { + champion, + placement, + queue_id: 1750, + started_at_ms, + } +} + +impl PlayedMatch { + pub fn in_format(mut self, queue_id: u32) -> PlayedMatch { + self.queue_id = queue_id; + self + } +} + +/// One Match per Placement, an hour apart from `from_ms`. +pub fn run(champion: u32, placements: &[u8], from_ms: i64) -> Vec { + (0..) + .zip(placements) + .map(|(i, &p)| played_match(champion, p, from_ms + i * HOUR_MS)) + .collect() +} + +/// The payloads of the Matches, as the Riot API would serve them (win = top 3). +pub fn payloads(matches: &[PlayedMatch]) -> Vec { + (0..) + .zip(matches) + .map(|(i, m)| { + let key = CATALOG + .iter() + .find(|(id, _, _)| *id == m.champion) + .map_or("Unknown", |(_, key, _)| key); + payload( + &format!("EUW1_{i}"), + m.queue_id, + m.champion, + key, + m.placement, + m.placement <= 3, + m.started_at_ms, + ) + }) + .collect() +} + +pub fn open_tracker(dir: &Path, matches: &[PlayedMatch]) -> Tracker { + Tracker::open( + &dir.join("arena.db"), + Box::new(FakeHistory::new(recorded_account(), payloads(matches))), + ) + .unwrap() + .with_seasons(seasons()) +} + +/// A tracker with the six-champion catalog cached and the Matches imported. +pub fn imported_tracker(dir: &Path, matches: &[PlayedMatch]) -> Tracker { + let tracker = open_tracker(dir, matches).with_champions( + Box::new(FakeChampions::new("1.0", &CATALOG)), + dir.join("portraits"), + ); + tracker.refresh_champions().unwrap(); + tracker.sync(RIOT_ID, &mut |_| {}).unwrap(); + tracker +} + +/// The id of the Arena game in the recorded in-game session of the client. +pub fn recorded_game_id() -> u64 { + let session: Value = serde_json::from_str(include_str!( + "../fixtures/client/gameflow_session_in_game.json" + )) + .unwrap(); + session["gameData"]["gameId"].as_u64().unwrap() +} + +/// The game client, driven by the test between rounds. +#[derive(Clone, Default)] +pub struct FakeClient { + state: Arc>, +} + +#[derive(Default)] +struct ClientState { + signed_in: Option<(String, String)>, + gameflow: Gameflow, + tracks: HashMap, + waits: Vec, +} + +impl FakeClient { + /// A client that is not running. + pub fn absent() -> FakeClient { + FakeClient::default() + } + + /// Signed in as the recorded Account, with what the real client answered. + pub fn recorded() -> FakeClient { + let client = FakeClient::default(); + let summoner: Value = + serde_json::from_str(include_str!("../fixtures/client/current_summoner.json")).unwrap(); + client.sign_in( + summoner["gameName"].as_str().unwrap(), + summoner["tagLine"].as_str().unwrap(), + ); + let phase: String = + serde_json::from_str(include_str!("../fixtures/client/gameflow_phase_none.json")) + .unwrap(); + client.set_phase(&phase, false); + let groups: Vec = serde_json::from_str(include_str!( + "../fixtures/client/progression_groups_configuration.json" + )) + .unwrap(); + let instance: Value = serde_json::from_str(include_str!( + "../fixtures/client/progression_instance_data.json" + )) + .unwrap(); + let group = groups + .iter() + .find(|g| g["id"] == instance["groupId"]) + .unwrap(); + client.set_track( + group["name"].as_str().unwrap(), + instance["counters"][0]["counterValue"].as_u64().unwrap() as u32, + ); + client + } + + pub fn sign_in(&self, game_name: &str, tag_line: &str) { + self.state.lock().unwrap().signed_in = Some((game_name.into(), tag_line.into())); + } + + /// The client closes. + pub fn sign_out(&self) { + self.state.lock().unwrap().signed_in = None; + } + + /// `phase` is the client's own name for it, e.g. "InProgress". + pub fn set_phase(&self, phase: &str, arena: bool) { + let mut state = self.state.lock().unwrap(); + state.gameflow = Gameflow { + phase: GamePhase::from_client(phase), + arena, + ..state.gameflow.clone() + }; + } + + /// The client's id of the game being played (kept across phases until changed). + pub fn set_game_id(&self, game_id: Option) { + self.state.lock().unwrap().gameflow.game_id = game_id; + } + + pub fn set_track(&self, name: &str, value: u32) { + self.state.lock().unwrap().tracks.insert(name.into(), value); + } + + pub fn remove_track(&self, name: &str) { + self.state.lock().unwrap().tracks.remove(name); + } + + /// The timeouts the tracker asked to wait for. + pub fn waits(&self) -> Vec { + self.state.lock().unwrap().waits.clone() + } +} + +impl GameClientSource for FakeClient { + fn signed_in(&self) -> Result<(String, String), ClientError> { + let state = self.state.lock().unwrap(); + state.signed_in.clone().ok_or(ClientError::Absent) + } + + fn gameflow(&self) -> Result { + let state = self.state.lock().unwrap(); + state.signed_in.as_ref().ok_or(ClientError::Absent)?; + Ok(state.gameflow.clone()) + } + + fn official_progress(&self, track_name: &str) -> Result, ClientError> { + let state = self.state.lock().unwrap(); + state.signed_in.as_ref().ok_or(ClientError::Absent)?; + Ok(state.tracks.get(track_name).copied()) + } + + fn wait_for_change(&self, timeout: Duration) { + self.state.lock().unwrap().waits.push(timeout); + } +} diff --git a/crates/core/tests/follow.rs b/crates/core/tests/follow.rs new file mode 100644 index 0000000..882172a --- /dev/null +++ b/crates/core/tests/follow.rs @@ -0,0 +1,1025 @@ +mod common; + +use std::cell::Cell; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, mpsc}; +use std::thread; +use std::time::{Duration, Instant}; + +use arena_tracker_core::{ + Account, Format, MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Scope, SeasonScope, SourceError, + Tracker, UpdateProblem, +}; +use common::{ + FakeClient, FakeHistory, PlayedMatch, S2, S2_TRACK, SELF_PUUID, at, date, payload, payloads, + played_by, played_match, recorded_account, run, seasons, +}; + +const OTHER_PUUID: &str = "fixture-puuid-other"; + +/// A moment inside the second test Season. +fn now() -> i64 { + at(date(2026, 4, 10), 12) +} + +fn other_account() -> Account { + Account { + puuid: OTHER_PUUID.into(), + game_name: "Autre".into(), + tag_line: "FIX".into(), + } +} + +/// One Arena 3x6 Match of the recorded Account, placed first with Jinx. +fn new_match(id: &str, hours: i64) -> String { + payload(id, 1750, 222, "Jinx", 1, true, at(date(2026, 4, 5), hours)) +} + +struct World { + dir: tempfile::TempDir, + history: Arc, + client: FakeClient, + calls: Arc, +} + +impl World { + /// The recorded Account has played `matches`; the client runs and is signed in as them. + fn new(matches: &[PlayedMatch]) -> World { + World::with_history(FakeHistory::new(recorded_account(), payloads(matches))) + } + + fn with_history(history: FakeHistory) -> World { + let calls = history.call_counter(); + World { + dir: tempfile::tempdir().unwrap(), + history: Arc::new(history), + client: FakeClient::recorded(), + calls, + } + } + + fn tracker(&self) -> Tracker { + self.open().with_client(Box::new(self.client.clone())) + } + + fn open(&self) -> Tracker { + Tracker::open( + &self.dir.path().join("arena.db"), + Box::new(self.history.clone()), + ) + .unwrap() + .with_seasons(seasons()) + } + + fn source_calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } +} + +thread_local! { + /// The time of the latest round (each test runs on its own thread). + static CLOCK: Cell = Cell::new(now()); +} + +/// A round `ms` after the previous one. +fn round_after(tracker: &Tracker, ms: i64) -> bool { + let now_ms = CLOCK.with(|clock| clock.replace(clock.get() + ms) + ms); + tracker.follow_client(now_ms, None, &mut |_| {}) +} + +/// A round one retry interval after the previous one. +fn round(tracker: &Tracker) -> bool { + round_after(tracker, RETRY_EVERY_MS) +} + +fn completed(tracker: &Tracker, puuid: &str) -> usize { + let scope = Scope { + season: SeasonScope::Season(S2.into()), + format: None, + }; + let stats = tracker.statistics(puuid, &scope).unwrap(); + stats.challenge.unwrap().completed +} + +/// A Match won with each of `n` different champions. +fn top1_matches(n: u32) -> Vec { + (0..n) + .map(|i| played_match(1000 + i, 1, at(date(2026, 4, 2), i64::from(i)))) + .collect() +} + +fn s2_matches() -> Vec { + run(11, &[4, 1], at(date(2026, 4, 2), 0)) +} + +#[test] +fn the_first_round_syncs_the_signed_in_account_and_makes_it_active() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + assert_eq!(tracker.status().updating, None); + assert!(!tracker.status().client_running); + + assert!(round(&tracker)); + + let status = tracker.status(); + assert!(status.client_running); + assert_eq!(status.updating, Some(recorded_account())); + assert_eq!(status.problem, None); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + + // Nothing changed: no visible change and no call to Riot, even if the client spells the + // Riot ID differently. + world.client.sign_in("joueur", "euw"); + let calls = world.source_calls(); + assert!(!round(&tracker)); + assert_eq!(world.source_calls(), calls); +} + +/// The recorded Account and another one, who has one Match. +fn two_accounts() -> FakeHistory { + let theirs = payload( + "EUW1_theirs", + 1750, + 222, + "Jinx", + 3, + true, + at(date(2026, 4, 3), 0), + ); + FakeHistory::new(recorded_account(), payloads(&s2_matches())) + .with_account(other_account(), vec![played_by(&theirs, OTHER_PUUID)]) +} + +#[test] +fn signing_in_to_another_account_switches_the_active_account() { + let world = World::with_history(two_accounts()); + let tracker = world.tracker(); + round(&tracker); + assert_eq!(tracker.status().updating, Some(recorded_account())); + + world.client.sign_in("Autre", "FIX"); + assert!(round(&tracker)); + + assert_eq!(tracker.status().updating, Some(other_account())); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + assert_eq!(tracker.match_count(OTHER_PUUID).unwrap(), 1); + assert_eq!(completed(&tracker, SELF_PUUID), 1); + assert_eq!(completed(&tracker, OTHER_PUUID), 0); + + world.client.sign_in("Joueur", "EUW"); + round(&tracker); + assert_eq!(tracker.status().updating, Some(recorded_account())); +} + +#[test] +fn without_the_client_the_first_round_catches_up_on_the_last_active_account() { + let world = World::new(&s2_matches()); + round(&world.tracker()); + world.client.sign_out(); + world.history.add(new_match("EUW1_while_closed", 3)); + + let tracker = world.tracker(); + assert_eq!( + tracker.last_active_account().unwrap(), + Some(recorded_account()) + ); + assert!(round(&tracker)); + + let status = tracker.status(); + assert!(!status.client_running); + assert_eq!(status.updating, Some(recorded_account())); + assert_eq!(status.problem, None); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); +} + +#[test] +fn without_the_client_nor_any_known_account_there_is_nothing_to_update() { + let world = World::new(&s2_matches()); + world.client.sign_out(); + let tracker = world.tracker(); + + assert!(round(&tracker)); + + let status = tracker.status(); + assert_eq!( + (status.updating, status.problem), + (None, Some(UpdateProblem::NoAccount)) + ); + assert_eq!(world.source_calls(), 0); + // An empty Riot ID from the settings is no Riot ID. + tracker.follow_client(now(), Some(" "), &mut |_| {}); + assert_eq!(tracker.status().problem, Some(UpdateProblem::NoAccount)); +} + +#[test] +fn the_configured_riot_id_is_the_fallback_when_nothing_else_is_known() { + let world = World::new(&s2_matches()); + world.client.sign_out(); + let tracker = world.tracker(); + + assert!(tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {})); + + let status = tracker.status(); + assert_eq!( + (status.updating, status.problem), + (Some(recorded_account()), None) + ); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + assert_eq!( + world.open().last_active_account().unwrap(), + Some(recorded_account()) + ); +} + +#[test] +fn rounds_work_without_any_client() { + let world = World::new(&s2_matches()); + let tracker = world.open(); + + tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {}); + + assert!(!tracker.status().client_running); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); +} + +#[test] +fn when_the_client_stops_the_active_account_and_its_data_stay() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + world.client.sign_out(); + let calls = world.source_calls(); + + assert!(round(&tracker)); + + let status = tracker.status(); + assert!(!status.client_running); + assert_eq!(status.updating, Some(recorded_account())); + assert_eq!(status.official_progress, ProgressCheck::Absent); + assert_eq!(world.source_calls(), calls); + assert_eq!(completed(&tracker, SELF_PUUID), 1); +} + +#[test] +fn an_unknown_riot_id_in_the_client_is_a_problem_not_a_crash() { + let world = World::new(&s2_matches()); + world.client.sign_in("Inconnu", "XX"); + let tracker = world.tracker(); + + round(&tracker); + + assert!(matches!( + tracker.status().problem, + Some(UpdateProblem::Other(_)) + )); + assert_eq!(tracker.status().updating, None); +} + +#[test] +fn the_match_of_an_arena_game_that_just_ended_is_stored() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + let calls = world.source_calls(); + + world.client.set_phase("ChampSelect", false); + round(&tracker); + world.client.set_phase("InProgress", true); + assert!(!round(&tracker)); + assert_eq!( + world.source_calls(), + calls, + "nothing to fetch while the game runs" + ); + + world.history.add(new_match("EUW1_just_played", 1)); + world.client.set_phase("EndOfGame", true); + assert!(round(&tracker)); + + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); + assert_eq!(tracker.status().problem, None); + let calls = world.source_calls(); + world.client.set_phase("None", false); + assert!(!round(&tracker)); + assert_eq!(world.source_calls(), calls, "a stored Match ends the wait"); + let report = tracker.refresh(&mut |_| {}).unwrap(); + assert_eq!((report.added, report.stored), (0, 3)); +} + +#[test] +fn a_match_that_shows_up_late_is_still_stored_without_leaving_a_problem() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + world.client.set_phase("Reconnect", true); + round(&tracker); + world.client.set_phase("WaitingForStats", true); + round(&tracker); + round(&tracker); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + + world.history.add(new_match("EUW1_late", 1)); + round(&tracker); + tracker.wait_for_client(); + + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); + assert_eq!(tracker.status().problem, None); + assert_eq!(world.client.waits(), [Duration::from_secs(60)]); +} + +#[test] +fn while_a_match_is_pending_client_events_still_end_the_wait() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + world.client.set_phase("InProgress", true); + round(&tracker); + world.client.set_phase("EndOfGame", true); + round(&tracker); + + let started = Instant::now(); + tracker.wait_for_client(); + + assert!(started.elapsed() < Duration::from_secs(1), "no sleep"); + assert_eq!(world.client.waits(), [Duration::from_secs(20)]); +} + +#[test] +fn a_burst_of_client_events_makes_one_request_per_retry_interval() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + play_arena_game(&world, &tracker); + let calls = world.source_calls(); + + round(&tracker); + for _ in 0..5 { + round_after(&tracker, 0); + } + assert_eq!(world.source_calls(), calls + 1); + round_after(&tracker, RETRY_EVERY_MS - 1); + assert_eq!(world.source_calls(), calls + 1); + round_after(&tracker, 1); + + assert_eq!(world.source_calls(), calls + 2); +} + +/// The Match of a game the client gave this id, as Riot has it. +fn match_of_game(game_id: u64) -> String { + let id = format!("EUW1_{game_id}"); + payload(&id, 1750, 103, "Ahri", 2, true, at(date(2026, 4, 5), 2)) +} + +/// Eliminated early from the recorded game A, the player queues again and game B ends before +/// A's lobby has finished: no Match is published yet. +fn two_games_in_a_row(world: &World, tracker: &Tracker) -> u64 { + round(tracker); + play_arena_game(world, tracker); + round(tracker); + let game_b = common::recorded_game_id() + 1; + world.client.set_game_id(Some(game_b)); + world.client.set_phase("InProgress", true); + round(tracker); + world.client.set_phase("EndOfGame", true); + game_b +} + +#[test] +fn the_matches_of_two_games_ended_in_a_row_are_both_stored() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + let game_b = two_games_in_a_row(&world, &tracker); + + world.history.add_unlisted(match_of_game(game_b)); + round(&tracker); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); + world.history.add_unlisted(finished_match(1750)); + round(&tracker); + + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 4); + assert_eq!(tracker.status().problem, None); + let calls = world.source_calls(); + round(&tracker); + assert_eq!(world.source_calls(), calls, "nothing left to wait for"); +} + +#[test] +fn the_first_of_two_games_is_pending_after_its_own_tries_once_the_second_is_stored() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + let game_b = two_games_in_a_row(&world, &tracker); + world.history.add_unlisted(match_of_game(game_b)); + + // Game A was tried twice already. + for _ in 2..MATCH_RETRIES - 1 { + round(&tracker); + assert_eq!(tracker.status().problem, None); + } + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); + round(&tracker); + + assert_eq!(tracker.status().problem, Some(UpdateProblem::MatchPending)); +} + +#[test] +fn a_match_that_never_shows_up_is_reported_pending_until_a_refresh_finds_it() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + world.client.set_phase("InProgress", true); + round(&tracker); + world.client.set_phase("EndOfGame", true); + + for _ in 1..MATCH_RETRIES { + round(&tracker); + assert_eq!(tracker.status().problem, None); + } + assert!(round(&tracker)); + + assert_eq!(tracker.status().problem, Some(UpdateProblem::MatchPending)); + tracker.wait_for_client(); + assert_eq!(world.client.waits(), [Duration::from_secs(60)]); + let calls = world.source_calls(); + assert!(!round(&tracker)); + assert_eq!(world.source_calls(), calls, "the round gave up"); + + world.history.add(new_match("EUW1_finally", 1)); + let report = tracker.refresh(&mut |_| {}).unwrap(); + + assert_eq!(report.added, 1); + assert_eq!(tracker.status().problem, None); +} + +#[test] +fn a_game_that_is_not_arena_triggers_nothing() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + let calls = world.source_calls(); + + world.client.set_phase("InProgress", false); + round(&tracker); + world.client.set_phase("EndOfGame", false); + + assert!(!round(&tracker)); + assert_eq!(world.source_calls(), calls); + assert_eq!(tracker.status().problem, None); + tracker.wait_for_client(); + assert_eq!(world.client.waits(), [Duration::from_secs(60)]); +} + +fn failures() -> [(SourceError, UpdateProblem); 4] { + [ + (SourceError::MissingKey, UpdateProblem::MissingKey), + (SourceError::InvalidKey, UpdateProblem::InvalidKey), + (SourceError::Network("coupé".into()), UpdateProblem::Network), + ( + SourceError::RateLimited { + retry_after: Duration::ZERO, + }, + UpdateProblem::RateLimited, + ), + ] +} + +#[test] +fn failures_during_a_round_are_recorded_and_stored_data_stays_readable() { + for (error, problem) in failures() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + world.client.set_phase("InProgress", true); + round(&tracker); + world.history.fail_with(Some(error)); + world.client.set_phase("EndOfGame", true); + + assert!(round(&tracker), "{problem:?}"); + + assert_eq!(tracker.status().problem, Some(problem)); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + assert_eq!(completed(&tracker, SELF_PUUID), 1); + + world.history.fail_with(None); + round(&tracker); + assert_eq!(tracker.status().problem, None); + } +} + +#[test] +fn failures_during_a_refresh_are_returned_and_recorded() { + for (error, problem) in failures() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + world.history.fail_with(Some(error)); + + let failed = tracker.refresh(&mut |_| {}); + + assert_eq!(failed.unwrap_err(), problem); + assert_eq!(tracker.status().problem, Some(problem)); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + assert_eq!(completed(&tracker, SELF_PUUID), 1); + + world.history.fail_with(None); + assert!(tracker.refresh(&mut |_| {}).is_ok()); + assert_eq!(tracker.status().problem, None); + } +} + +#[test] +fn a_first_sync_that_failed_is_tried_again_a_minute_later() { + let world = World::new(&s2_matches()); + world.history.fail_with(Some(SourceError::InvalidKey)); + let tracker = world.tracker(); + + round(&tracker); + assert_eq!(tracker.status().problem, Some(UpdateProblem::InvalidKey)); + assert_eq!(tracker.status().updating, None); + + world.history.fail_with(None); + assert!(round_after(&tracker, 60_000)); + + assert_eq!(tracker.status().problem, None); + assert_eq!(tracker.status().updating, Some(recorded_account())); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); +} + +#[test] +fn refreshing_with_no_account_known_is_a_problem() { + let world = World::new(&s2_matches()); + let tracker = world.open(); + + assert_eq!( + tracker.refresh(&mut |_| {}).unwrap_err(), + UpdateProblem::NoAccount + ); + assert_eq!(tracker.status().problem, Some(UpdateProblem::NoAccount)); +} + +#[test] +fn refreshing_at_launch_updates_the_last_active_account() { + let world = World::new(&s2_matches()); + round(&world.tracker()); + world.history.add(new_match("EUW1_next", 1)); + + let tracker = world.open(); + let report = tracker.refresh(&mut |_| {}).unwrap(); + + assert_eq!((report.added, report.stored), (1, 3)); + assert_eq!(tracker.status().updating, Some(recorded_account())); +} + +#[test] +fn official_progress_agrees_when_the_counts_are_equal() { + let world = World::new(&top1_matches(52)); + let tracker = world.tracker(); + + round(&tracker); + + // 52 is what the real client reported. + assert_eq!( + tracker.status().official_progress, + ProgressCheck::Agrees(52) + ); +} + +#[test] +fn official_progress_differs_with_both_numbers_and_follows_later_syncs() { + let world = World::new(&top1_matches(50)); + let tracker = world.tracker(); + + round(&tracker); + let differs = ProgressCheck::Differs { + app: 50, + official: 52, + }; + assert_eq!(tracker.status().official_progress, differs); + + world + .history + .add(new_match("EUW1_a", 1).replace("\"championId\":222", "\"championId\":2001")); + world + .history + .add(new_match("EUW1_b", 2).replace("\"championId\":222", "\"championId\":2002")); + tracker.refresh(&mut |_| {}).unwrap(); + assert_eq!( + tracker.status().official_progress, + ProgressCheck::Agrees(52) + ); +} + +#[test] +fn official_progress_is_absent_without_a_reading() { + let world = World::new(&top1_matches(52)); + let tracker = world.tracker(); + round(&tracker); + assert_ne!(tracker.status().official_progress, ProgressCheck::Absent); + + world.client.remove_track(S2_TRACK); + round(&tracker); + assert_eq!(tracker.status().official_progress, ProgressCheck::Absent); + + world.client.set_track(S2_TRACK, 52); + round(&tracker); + assert_eq!( + tracker.status().official_progress, + ProgressCheck::Agrees(52) + ); + + world.client.sign_out(); + round(&tracker); + assert_eq!(tracker.status().official_progress, ProgressCheck::Absent); +} + +#[test] +fn official_progress_is_absent_when_the_season_has_no_track_or_there_is_no_season() { + let world = World::new(&top1_matches(52)); + let tracker = world.tracker(); + + tracker.follow_client(at(date(2026, 1, 15), 0), None, &mut |_| {}); + assert_eq!(tracker.status().official_progress, ProgressCheck::Absent); + + tracker.follow_client(at(date(2025, 6, 1), 0), None, &mut |_| {}); + assert_eq!(tracker.status().official_progress, ProgressCheck::Absent); + + tracker.follow_client(now(), None, &mut |_| {}); + assert_eq!( + tracker.status().official_progress, + ProgressCheck::Agrees(52) + ); +} + +/// The Match of the game the recorded client session is playing, as Riot has it. +fn finished_match(queue_id: u32) -> String { + let id = format!("EUW1_{}", common::recorded_game_id()); + payload(&id, queue_id, 222, "Jinx", 1, true, at(date(2026, 4, 5), 1)) +} + +/// Plays an Arena game up to its end: the next round sees it ended. +fn play_arena_game(world: &World, tracker: &Tracker) { + world.client.set_game_id(Some(common::recorded_game_id())); + world.client.set_phase("InProgress", true); + round(tracker); + world.client.set_phase("EndOfGame", true); +} + +#[test] +fn a_finished_game_is_fetched_by_its_id_even_in_a_queue_nobody_lists() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + play_arena_game(&world, &tracker); + world.history.add_unlisted(finished_match(1800)); + let (calls, listed) = (world.source_calls(), world.history.listed_counter()); + let listed_before = listed.load(Ordering::SeqCst); + + assert!(round(&tracker)); + + assert_eq!(world.source_calls(), calls + 1, "one request, no listing"); + assert_eq!(listed.load(Ordering::SeqCst), listed_before); + let matches = tracker.matches(SELF_PUUID).unwrap(); + assert_eq!(matches.len(), 3); + assert_eq!(matches.last().unwrap().format, Format::Other(1800)); + assert_eq!(tracker.status().problem, None); + world.client.set_phase("None", false); + assert!(!round(&tracker)); + assert_eq!( + world.source_calls(), + calls + 1, + "a stored Match ends the wait" + ); +} + +#[test] +fn a_match_riot_publishes_late_is_stored_once_it_appears() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + play_arena_game(&world, &tracker); + + for _ in 0..5 { + let calls = world.source_calls(); + round(&tracker); + assert_eq!(world.source_calls(), calls + 1, "one request per round"); + assert_eq!(tracker.status().problem, None); + } + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + + world.history.add_unlisted(finished_match(1750)); + assert!(round(&tracker)); + + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); + assert_eq!(tracker.status().problem, None); +} + +#[test] +fn a_match_that_never_appears_is_pending_and_an_empty_refresh_keeps_it_so() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + play_arena_game(&world, &tracker); + let calls = world.source_calls(); + + for _ in 0..MATCH_RETRIES { + round(&tracker); + } + + assert_eq!(world.source_calls(), calls + MATCH_RETRIES); + assert_eq!(tracker.status().problem, Some(UpdateProblem::MatchPending)); + assert!(!round(&tracker)); + assert_eq!( + world.source_calls(), + calls + MATCH_RETRIES, + "the wait is over" + ); + + let report = tracker.refresh(&mut |_| {}).unwrap(); + assert_eq!(report.added, 0); + assert_eq!(tracker.status().problem, Some(UpdateProblem::MatchPending)); + + world.history.add(finished_match(1750)); + assert_eq!(tracker.refresh(&mut |_| {}).unwrap().added, 1); + assert_eq!(tracker.status().problem, None); +} + +#[test] +fn a_match_fetched_by_its_id_is_never_stored_twice() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + play_arena_game(&world, &tracker); + world.history.add(finished_match(1750)); + + round(&tracker); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); + let report = tracker.refresh(&mut |_| {}).unwrap(); + + assert_eq!((report.added, report.stored), (0, 3)); +} + +#[test] +fn a_finished_game_that_is_not_an_arena_match_ends_the_wait_without_storing_it() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + play_arena_game(&world, &tracker); + world.history.add_unlisted(finished_match(1704)); + + round(&tracker); + let calls = world.source_calls(); + round(&tracker); + + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + assert_eq!(world.source_calls(), calls, "nothing left to wait for"); +} + +#[test] +fn a_failed_fetch_by_id_is_recorded_and_tried_again() { + let world = World::new(&s2_matches()); + let tracker = world.tracker(); + round(&tracker); + play_arena_game(&world, &tracker); + world.history.add_unlisted(finished_match(1750)); + world + .history + .fail_with(Some(SourceError::Network("coupé".into()))); + + round(&tracker); + assert_eq!(tracker.status().problem, Some(UpdateProblem::Network)); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + + world.history.fail_with(None); + round(&tracker); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 3); + assert_eq!(tracker.status().problem, None); +} + +#[test] +fn without_a_stored_match_to_give_the_platform_a_normal_sync_looks_for_the_game() { + let world = World::new(&[]); + let tracker = world.tracker(); + round(&tracker); + play_arena_game(&world, &tracker); + world.history.add(finished_match(1750)); + + round(&tracker); + + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 1); +} + +#[test] +fn a_failed_first_sight_of_another_account_does_not_keep_the_previous_one() { + let world = World::with_history( + FakeHistory::new(recorded_account(), payloads(&s2_matches())) + .with_account(other_account(), vec![]), + ); + let tracker = world.tracker(); + round(&tracker); + assert_eq!(tracker.status().updating, Some(recorded_account())); + + // Never seen before, and Riot is down. + world + .history + .fail_with(Some(SourceError::Network("coupé".into()))); + world.client.sign_in("Autre", "FIX"); + round(&tracker); + assert_eq!(tracker.status().updating, None); + assert_eq!(tracker.status().problem, Some(UpdateProblem::Network)); + play_arena_game(&world, &tracker); + round(&tracker); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + + // Once seen, the stored Account stays shown while Riot is down. + world.history.fail_with(None); + world.client.set_phase("None", false); + world.client.sign_in("Autre", "FIX"); + round(&tracker); + assert_eq!(tracker.status().updating, Some(other_account())); + world.client.sign_in("Joueur", "EUW"); + round(&tracker); + world + .history + .fail_with(Some(SourceError::Network("coupé".into()))); + world.client.sign_in("Autre", "FIX"); + round(&tracker); + assert_eq!(tracker.status().updating, Some(other_account())); + assert_eq!(tracker.status().problem, Some(UpdateProblem::Network)); +} + +#[test] +fn signing_back_in_after_a_failed_switch_shows_that_account_again() { + let world = World::with_history(two_accounts()); + let tracker = world.tracker(); + round(&tracker); + world + .history + .fail_with(Some(SourceError::Network("coupé".into()))); + world.client.sign_in("Autre", "FIX"); + round(&tracker); + assert_eq!(tracker.status().updating, None); + + world.client.sign_in("Joueur", "EUW"); + round(&tracker); + + assert_eq!(tracker.status().updating, Some(recorded_account())); +} + +#[test] +fn a_failing_adoption_is_tried_again_once_a_minute_not_on_every_client_event() { + let world = World::new(&s2_matches()); + world.history.fail_with(Some(SourceError::InvalidKey)); + let tracker = world.tracker(); + + round(&tracker); + for _ in 0..9 { + round_after(&tracker, 0); + } + assert_eq!(world.source_calls(), 1); + // The refresh button is not held back. + let refreshed = tracker.refresh(&mut |_| {}); + assert_eq!(refreshed.unwrap_err(), UpdateProblem::InvalidKey); + assert_eq!(world.source_calls(), 2); + round_after(&tracker, 59_999); + assert_eq!(world.source_calls(), 2); + round_after(&tracker, 1); + + assert_eq!(world.source_calls(), 3); +} + +#[test] +fn a_refresh_after_a_failed_first_sight_adopts_the_signed_in_account() { + let world = World::with_history(two_accounts()); + let tracker = world.tracker(); + round(&tracker); + world.history.fail_with(Some(SourceError::InvalidKey)); + world.client.sign_in("Autre", "FIX"); + round(&tracker); + assert_eq!(tracker.status().updating, None); + + world.history.fail_with(None); + let report = tracker.refresh(&mut |_| {}).unwrap(); + + assert_eq!(report.account, other_account()); + assert_eq!(tracker.status().updating, Some(other_account())); + assert_eq!( + tracker.last_active_account().unwrap(), + Some(other_account()) + ); +} + +#[test] +fn a_refresh_after_a_failed_first_round_adopts_the_account_signed_in_to_the_client() { + let world = World::new(&s2_matches()); + world.history.fail_with(Some(SourceError::InvalidKey)); + let tracker = world.tracker(); + round(&tracker); + + world.history.fail_with(None); + let report = tracker.refresh(&mut |_| {}).unwrap(); + + assert_eq!((report.added, report.stored), (2, 2)); + assert_eq!(tracker.status().updating, Some(recorded_account())); + assert_eq!(tracker.status().problem, None); +} + +#[test] +fn a_refresh_during_the_first_import_of_a_new_account_keeps_that_account_active() { + let (entered_tx, entered) = mpsc::channel(); + let (release, release_rx) = mpsc::channel(); + let world = World::with_history(two_accounts().gated(entered_tx, release_rx)); + let tracker = world.tracker(); + // The two Matches of the recorded Account go through. + release.send(()).unwrap(); + release.send(()).unwrap(); + round(&tracker); + assert_eq!(entered.try_iter().count(), 2); + world.client.sign_in("Autre", "FIX"); + + thread::scope(|scope| { + let follower = scope.spawn(|| round(&tracker)); + // The import of the other Account now waits on Riot. + entered.recv().unwrap(); + let refresh = scope.spawn(|| tracker.refresh(&mut |_| {})); + thread::sleep(Duration::from_millis(200)); + release.send(()).unwrap(); + follower.join().unwrap(); + refresh.join().unwrap().unwrap(); + }); + + assert_eq!(tracker.status().updating, Some(other_account())); + assert_eq!( + tracker.last_active_account().unwrap(), + Some(other_account()) + ); +} + +#[test] +fn a_fallback_whose_first_sync_failed_is_tried_again_by_later_rounds() { + let world = World::new(&s2_matches()); + world.client.sign_out(); + world.history.fail_with(Some(SourceError::InvalidKey)); + let tracker = world.tracker(); + + tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {}); + assert_eq!(tracker.status().problem, Some(UpdateProblem::InvalidKey)); + assert_eq!(tracker.status().updating, None); + + world.history.fail_with(None); + assert!(round_after(&tracker, 60_000)); + + assert_eq!(tracker.status().updating, Some(recorded_account())); + assert_eq!(tracker.status().problem, None); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); +} + +#[test] +fn a_refresh_after_a_failed_first_round_uses_the_fallback() { + let world = World::new(&s2_matches()); + world.client.sign_out(); + world.history.fail_with(Some(SourceError::InvalidKey)); + let tracker = world.tracker(); + tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {}); + + world.history.fail_with(None); + let report = tracker.refresh(&mut |_| {}).unwrap(); + + assert_eq!((report.added, report.stored), (2, 2)); + assert_eq!(tracker.status().updating, Some(recorded_account())); + assert_eq!(tracker.status().problem, None); +} + +#[test] +fn a_fallback_given_after_a_round_without_any_account_is_used() { + let world = World::new(&s2_matches()); + world.client.sign_out(); + let tracker = world.tracker(); + round(&tracker); + assert_eq!(tracker.status().problem, Some(UpdateProblem::NoAccount)); + + tracker.follow_client(now(), Some("Joueur#EUW"), &mut |_| {}); + + assert_eq!(tracker.status().updating, Some(recorded_account())); + assert_eq!(tracker.status().problem, None); +} + +#[test] +fn banners_point_to_the_parametres_screen_and_never_to_a_missing_field() { + let text = |p: UpdateProblem| p.message(); + for problem in [UpdateProblem::MissingKey, UpdateProblem::InvalidKey] { + assert!(text(problem.clone()).contains("Paramètres"), "{problem:?}"); + } + let no_account = text(UpdateProblem::NoAccount); + assert!(no_account.contains("League of Legends"), "{no_account}"); + assert!(!no_account.contains("Riot ID"), "{no_account}"); + for problem in [ + UpdateProblem::MissingKey, + UpdateProblem::InvalidKey, + UpdateProblem::Network, + UpdateProblem::RateLimited, + UpdateProblem::NoAccount, + UpdateProblem::MatchPending, + UpdateProblem::Other("x".into()), + ] { + assert!(!text(problem).contains("réglages")); + } +} diff --git a/crates/core/tests/import.rs b/crates/core/tests/import.rs new file mode 100644 index 0000000..f95d215 --- /dev/null +++ b/crates/core/tests/import.rs @@ -0,0 +1,624 @@ +mod common; + +use std::path::Path; +use std::sync::atomic::Ordering; +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +use arena_tracker_core::{ + Account, Error, Format, Match, SourceError, SyncProgress, SyncReport, Tracker, +}; +use common::{ + FakeHistory, SELF_PUUID, payload, played_by, recorded_account, recorded_matches, with_game_mode, +}; +use serde_json::Value; + +const RIOT_ID: &str = "Joueur#EUW"; + +fn open(db: &Path, history: FakeHistory) -> Tracker { + Tracker::open(db, Box::new(history)).unwrap() +} + +fn sync(tracker: &Tracker) -> SyncReport { + tracker.sync(RIOT_ID, &mut |_| {}).unwrap() +} + +/// The expectation for a recorded payload, read from the payload itself. +fn expected(raw: &str) -> Match { + let v: Value = serde_json::from_str(raw).unwrap(); + let me = v["info"]["participants"] + .as_array() + .unwrap() + .iter() + .find(|p| p["puuid"] == SELF_PUUID) + .unwrap(); + let format = match v["info"]["queueId"].as_u64().unwrap() { + 1700 => Format::Arena16, + 1740 => Format::BraveryArena, + 1750 => Format::Arena3x6, + queue => panic!("unexpected queue {queue}"), + }; + Match { + match_id: v["metadata"]["matchId"].as_str().unwrap().into(), + format, + champion_id: me["championId"].as_u64().unwrap() as u32, + champion_name: me["championName"].as_str().unwrap().into(), + placement: me["placement"].as_u64().unwrap() as u8, + win: me["win"].as_bool().unwrap(), + started_at_ms: v["info"]["gameStartTimestamp"].as_i64().unwrap(), + } +} + +/// Five Arena 3x6 Matches, one every 1000 s starting at `from_s`. +fn five_matches(from_s: i64) -> Vec { + five_matches_every(from_s, 1000) +} + +/// Five Arena 3x6 Matches, one every `step_s` seconds starting at `from_s`. +fn five_matches_every(from_s: i64, step_s: i64) -> Vec { + (0..5) + .map(|i| { + payload( + &format!("EUW1_{i}"), + 1750, + 10 + i as u32, + "Champion", + (i % 8 + 1) as u8, + i % 2 == 0, + (from_s + i * step_s) * 1000, + ) + }) + .collect() +} + +fn started_at(matches: &[Match]) -> Vec { + matches.iter().map(|m| m.started_at_ms).collect() +} + +#[test] +fn tracker_can_be_shared_between_threads() { + fn assert_send_sync() {} + assert_send_sync::(); +} + +#[test] +fn imports_the_recorded_matches() { + let dir = tempfile::tempdir().unwrap(); + let tracker = open( + &dir.path().join("arena.db"), + FakeHistory::new(recorded_account(), recorded_matches()), + ); + + let report = sync(&tracker); + + assert_eq!(report.account, recorded_account()); + assert_eq!((report.added, report.stored), (6, 6)); + let mut want: Vec = recorded_matches().iter().map(|raw| expected(raw)).collect(); + want.sort_by_key(|m| m.started_at_ms); + assert_eq!(tracker.matches(SELF_PUUID).unwrap(), want); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 6); + assert_eq!(tracker.accounts().unwrap(), [recorded_account()]); +} + +#[test] +fn importing_twice_changes_nothing_and_fetches_nothing() { + let dir = tempfile::tempdir().unwrap(); + let fake = FakeHistory::new(recorded_account(), recorded_matches()); + let fetches = fake.fetch_counter(); + let tracker = open(&dir.path().join("arena.db"), fake); + sync(&tracker); + let first = tracker.matches(SELF_PUUID).unwrap(); + + let report = sync(&tracker); + + assert_eq!((report.added, report.stored), (0, 6)); + assert_eq!(fetches.load(Ordering::SeqCst), 6); + assert_eq!(tracker.matches(SELF_PUUID).unwrap(), first); +} + +#[test] +fn interrupted_import_keeps_what_was_stored_and_resumes_with_the_rest() { + let dir = tempfile::tempdir().unwrap(); + let db = dir.path().join("arena.db"); + let flaky = open( + &db, + FakeHistory::new(recorded_account(), five_matches(1_000_000)).failing_after(2), + ); + + let err = flaky.sync(RIOT_ID, &mut |_| {}).unwrap_err(); + + assert!(matches!(err, Error::Source(SourceError::Network(_)))); + assert_eq!(flaky.match_count(SELF_PUUID).unwrap(), 2); + drop(flaky); + + let healthy = FakeHistory::new(recorded_account(), five_matches(1_000_000)); + let fetches = healthy.fetch_counter(); + let tracker = open(&db, healthy); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 2); + + let report = sync(&tracker); + + // The two stored are the newest ones: the missing older ones are still found. + assert_eq!((report.added, report.stored), (3, 5)); + assert_eq!(fetches.load(Ordering::SeqCst), 3); + assert_eq!(tracker.matches(SELF_PUUID).unwrap().len(), 5); +} + +#[test] +fn later_sync_fetches_only_newer_matches() { + let dir = tempfile::tempdir().unwrap(); + let db = dir.path().join("arena.db"); + let days_apart = |from_s| five_matches_every(from_s, 10 * 24 * 3600); + sync(&open( + &db, + FakeHistory::new(recorded_account(), days_apart(1_000_000)), + )); + + let mut now_on_riot = days_apart(1_000_000); + now_on_riot.push(payload( + "EUW1_new1", + 1750, + 1, + "Annie", + 1, + true, + 4_500_000_000, + )); + now_on_riot.push(payload( + "EUW1_new2", + 1740, + 2, + "Olaf", + 3, + true, + 4_501_000_000, + )); + let fake = FakeHistory::new(recorded_account(), now_on_riot); + let (fetches, listed) = (fake.fetch_counter(), fake.listed_counter()); + let tracker = open(&db, fake); + + let report = sync(&tracker); + + assert_eq!((report.added, report.stored), (2, 7)); + assert_eq!(fetches.load(Ordering::SeqCst), 2); + // Riot is only asked for recent Matches: the newest stored one (listed again) and the new ones. + assert_eq!(listed.load(Ordering::SeqCst), 3); +} + +#[test] +fn matches_are_returned_oldest_first_whatever_the_delivery_order() { + let dir = tempfile::tempdir().unwrap(); + let mut payloads = five_matches(1_000_000); + payloads.swap(0, 3); + payloads.swap(1, 4); + let delivered: Vec = payloads.iter().map(|p| started_ms(p)).collect(); + assert!(!delivered.is_sorted() && !delivered.iter().rev().is_sorted()); + let tracker = open( + &dir.path().join("arena.db"), + FakeHistory::new(recorded_account(), payloads).delivered_as_given(), + ); + sync(&tracker); + + let started = started_at(&tracker.matches(SELF_PUUID).unwrap()); + + assert_eq!(started.len(), 5); + assert!(started.is_sorted()); +} + +fn started_ms(payload: &str) -> i64 { + let v: Value = serde_json::from_str(payload).unwrap(); + v["info"]["gameStartTimestamp"].as_i64().unwrap() +} + +#[test] +fn a_catch_up_cut_short_fetches_the_older_matches_next_time() { + let dir = tempfile::tempdir().unwrap(); + let db = dir.path().join("arena.db"); + let at = |hours: i64| (1_000_000 + hours * 3600) * 1000; + let known = payload("EUW1_1", 1750, 1, "A", 4, false, at(0)); + sync(&open( + &db, + FakeHistory::new(recorded_account(), vec![known.clone()]), + )); + // Three Matches played while the app was closed. + let mut on_riot = vec![known]; + for i in 2..=4 { + let id = format!("EUW1_{i}"); + on_riot.push(payload(&id, 1750, i, "B", 4, false, at(i64::from(i)))); + } + + // The catch-up stores the newest one, then dies. + let cut = open( + &db, + FakeHistory::new(recorded_account(), on_riot.clone()).failing_after(1), + ); + assert!(cut.sync(RIOT_ID, &mut |_| {}).is_err()); + assert_eq!(cut.match_count(SELF_PUUID).unwrap(), 2); + drop(cut); + + let report = sync(&open(&db, FakeHistory::new(recorded_account(), on_riot))); + + assert_eq!((report.added, report.stored), (2, 4)); +} + +#[test] +fn a_match_that_started_earlier_but_was_published_later_is_still_imported() { + let dir = tempfile::tempdir().unwrap(); + let db = dir.path().join("arena.db"); + let at = |hours: i64| (1_000_000 + hours * 3600) * 1000; + let first = payload("EUW1_1", 1750, 1, "A", 4, false, at(0)); + let newest = payload("EUW1_2", 1750, 2, "B", 4, false, at(30)); + let fake = FakeHistory::new(recorded_account(), vec![first, newest]); + let tracker = open(&db, fake); + sync(&tracker); + + // A game that began before the newest stored one ends only now. + let late = FakeHistory::new( + recorded_account(), + vec![ + payload("EUW1_1", 1750, 1, "A", 4, false, at(0)), + payload("EUW1_2", 1750, 2, "B", 4, false, at(30)), + payload("EUW1_3", 1750, 3, "C", 1, true, at(10)), + ], + ); + drop(tracker); + + let report = sync(&open(&db, late)); + + assert_eq!((report.added, report.stored), (1, 3)); +} + +#[test] +fn a_match_that_cannot_be_delivered_or_read_does_not_block_the_others() { + let dir = tempfile::tempdir().unwrap(); + let at = |hours: i64| (1_000_000 + hours * 3600) * 1000; + let fake = FakeHistory::new( + recorded_account(), + vec![ + payload("EUW1_1", 1750, 1, "A", 4, false, at(1)), + payload("EUW1_2", 1750, 2, "B", 2, true, at(3)), + ], + ); + fake.add_missing("EUW1_gone", at(4)); + fake.add_unreadable("EUW1_garbled", at(2), "pas du JSON"); + fake.add_unreadable("EUW1_empty_object", at(0), "{}"); + let tracker = open(&dir.path().join("arena.db"), fake); + let mut progress = Vec::new(); + + let report = tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap(); + + assert_eq!((report.added, report.stored), (2, 2)); + assert_eq!( + progress.last(), + Some(&SyncProgress { + fetched: 5, + to_fetch: 5 + }) + ); + let again = sync(&tracker); + assert_eq!((again.added, again.stored), (0, 2)); +} + +#[test] +fn other_participants_may_lack_any_field() { + let dir = tempfile::tempdir().unwrap(); + let thin = common::without_fields_for_others( + &payload("EUW1_1", 1750, 7, "Zed", 2, true, 1_000_000_000), + &["placement", "win", "championId", "championName", "teamId"], + ); + let tracker = open( + &dir.path().join("arena.db"), + FakeHistory::new(recorded_account(), vec![thin]), + ); + + let report = sync(&tracker); + + assert_eq!(report.added, 1); + let stored = tracker.matches(SELF_PUUID).unwrap(); + assert_eq!((stored[0].champion_id, stored[0].placement), (7, 2)); +} + +#[test] +fn an_account_resolved_to_another_puuid_is_a_second_account() { + let dir = tempfile::tempdir().unwrap(); + let db = dir.path().join("arena.db"); + let at = |hours: i64| (1_000_000 + hours * 3600) * 1000; + let build = |puuid: &str, ids: &[u32]| -> Vec { + ids.iter() + .map(|&i| { + let raw = payload( + &format!("EUW1_{i}"), + 1750, + i, + "A", + 1, + true, + at(i64::from(i)), + ); + played_by(&raw, puuid) + }) + .collect() + }; + // Under the development key, Joueur#EUW is P1. + let account = |puuid: &str| Account { + puuid: puuid.into(), + ..recorded_account() + }; + let first = open(&db, FakeHistory::new(account("P1"), build("P1", &[1, 2]))); + sync(&first); + let before = first.matches("P1").unwrap(); + drop(first); + + // Under the personal key it is P2: nothing proves it is the same Account. + let tracker = open( + &db, + FakeHistory::new(account("P2"), build("P2", &[1, 2, 3])), + ); + + let report = sync(&tracker); + + assert_eq!(report.account.puuid, "P2"); + assert_eq!((report.added, report.stored), (3, 3)); + assert_eq!(tracker.matches("P1").unwrap(), before); + let mut puuids: Vec = tracker + .accounts() + .unwrap() + .into_iter() + .map(|a| a.puuid) + .collect(); + puuids.sort(); + assert_eq!(puuids, ["P1", "P2"]); +} + +const LEGACY_SCHEMA: &str = " +CREATE TABLE accounts ( + puuid TEXT PRIMARY KEY, game_name TEXT NOT NULL, tag_line TEXT NOT NULL, + full_import_done INTEGER NOT NULL DEFAULT 0 +); +CREATE TABLE matches ( + puuid TEXT NOT NULL, match_id TEXT NOT NULL, queue_id INTEGER NOT NULL, + champion_id INTEGER NOT NULL, champion_name TEXT NOT NULL, placement INTEGER NOT NULL, + win INTEGER NOT NULL, started_at_ms INTEGER NOT NULL, raw TEXT NOT NULL, + PRIMARY KEY (puuid, match_id) +); +INSERT INTO accounts VALUES ('fixture-puuid-self', 'Joueur', 'EUW', 1); +INSERT INTO matches VALUES ('fixture-puuid-self', 'EUW1_1', 1750, 1, 'A', 4, 0, 1000000000, '{}');"; + +#[test] +fn a_database_written_before_the_sync_mark_keeps_working() { + let dir = tempfile::tempdir().unwrap(); + let db = dir.path().join("arena.db"); + rusqlite::Connection::open(&db) + .unwrap() + .execute_batch(LEGACY_SCHEMA) + .unwrap(); + let other = Account { + puuid: "fixture-puuid-other".into(), + game_name: "Autre".into(), + tag_line: "FIX".into(), + }; + let theirs = vec![played_by( + &payload("EUW1_9", 1750, 9, "I", 1, true, 1_000_005_000), + &other.puuid, + )]; + let tracker = open( + &db, + FakeHistory::new( + recorded_account(), + vec![ + payload("EUW1_1", 1750, 1, "A", 4, false, 1_000_000_000), + payload("EUW1_2", 1750, 2, "B", 1, true, 1_000_003_000), + ], + ) + .with_account(other.clone(), theirs), + ); + + // No mark yet: everything is listed, what is stored is not fetched again. + let report = sync(&tracker); + assert_eq!((report.added, report.stored), (1, 2)); + // A new Account can be added to the old table. + let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap(); + assert_eq!((report.added, report.stored), (1, 1)); + assert_eq!(tracker.accounts().unwrap().len(), 2); +} + +#[test] +fn queues_map_to_formats_and_non_matches_are_skipped() { + let dir = tempfile::tempdir().unwrap(); + let at = |i: i64| (1_000_000 + i) * 1000; + let fake = FakeHistory::new( + recorded_account(), + vec![ + payload("EUW1_1", 1750, 1, "A", 1, true, at(1)), + payload("EUW1_2", 1740, 2, "B", 2, true, at(2)), + payload("EUW1_3", 1700, 3, "C", 3, true, at(3)), + payload("EUW1_4", 1710, 4, "D", 4, true, at(4)), + ], + ) + .listed_under(1700, payload("EUW1_5", 1704, 5, "E", 1, true, at(5))) + .listed_under(1700, payload("EUW1_6", 9999, 6, "F", 5, false, at(6))) + .listed_under( + 1700, + with_game_mode(&payload("EUW1_7", 1700, 7, "G", 1, true, at(7)), "ARAM"), + ); + let tracker = open(&dir.path().join("arena.db"), fake); + + let report = sync(&tracker); + + assert_eq!((report.added, report.stored), (5, 5)); + let formats: Vec<_> = tracker + .matches(SELF_PUUID) + .unwrap() + .into_iter() + .map(|m| (m.match_id, m.format)) + .collect(); + assert_eq!( + formats, + [ + ("EUW1_1".into(), Format::Arena3x6), + ("EUW1_2".into(), Format::BraveryArena), + ("EUW1_3".into(), Format::Arena16), + ("EUW1_4".into(), Format::Arena16), + ("EUW1_6".into(), Format::Other(9999)), + ] + ); +} + +#[test] +fn a_rate_limit_is_waited_out_and_the_import_completes() { + let dir = tempfile::tempdir().unwrap(); + let tracker = open( + &dir.path().join("arena.db"), + FakeHistory::new(recorded_account(), recorded_matches()).rate_limited_once(), + ); + + let report = sync(&tracker); + + assert_eq!((report.added, report.stored), (6, 6)); +} + +#[test] +fn progress_goes_from_nothing_fetched_to_everything_fetched() { + let dir = tempfile::tempdir().unwrap(); + let tracker = open( + &dir.path().join("arena.db"), + FakeHistory::new(recorded_account(), recorded_matches()), + ); + + let mut progress = Vec::new(); + tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap(); + + let want: Vec<_> = (0..=6) + .map(|fetched| SyncProgress { + fetched, + to_fetch: 6, + }) + .collect(); + assert_eq!(progress, want); + + progress.clear(); + tracker.sync(RIOT_ID, &mut |p| progress.push(p)).unwrap(); + assert_eq!( + progress, + [SyncProgress { + fetched: 0, + to_fetch: 0 + }] + ); +} + +#[test] +fn two_accounts_keep_separate_matches() { + let dir = tempfile::tempdir().unwrap(); + let db = dir.path().join("arena.db"); + sync(&open( + &db, + FakeHistory::new(recorded_account(), five_matches(1_000_000)), + )); + let other = Account { + puuid: "fixture-puuid-other".into(), + game_name: "Autre".into(), + tag_line: "FIX".into(), + }; + let theirs: Vec = five_matches(5_000_000)[..2] + .iter() + .map(|raw| played_by(raw, &other.puuid)) + .collect(); + let tracker = open(&db, FakeHistory::new(other.clone(), theirs)); + + let report = tracker.sync("Autre#FIX", &mut |_| {}).unwrap(); + + assert_eq!((report.added, report.stored), (2, 2)); + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 5); + assert_eq!(tracker.match_count(&other.puuid).unwrap(), 2); + assert!( + tracker + .matches(&other.puuid) + .unwrap() + .iter() + .all(|m| m.started_at_ms >= 5_000_000_000) + ); + assert_eq!(tracker.accounts().unwrap().len(), 2); +} + +#[test] +fn matches_without_the_account_are_skipped() { + let dir = tempfile::tempdir().unwrap(); + let stranger = Account { + puuid: "fixture-puuid-stranger".into(), + game_name: "Joueur".into(), + tag_line: "EUW".into(), + }; + let tracker = open( + &dir.path().join("arena.db"), + FakeHistory::new(stranger, recorded_matches()), + ); + + let report = sync(&tracker); + + assert_eq!((report.added, report.stored), (0, 0)); +} + +#[test] +fn riot_ids_are_validated_and_must_exist() { + let dir = tempfile::tempdir().unwrap(); + let tracker = open( + &dir.path().join("arena.db"), + FakeHistory::new(recorded_account(), recorded_matches()), + ); + + for bad in ["Joueur", "#EUW", "Joueur#"] { + let err = tracker.sync(bad, &mut |_| {}).unwrap_err(); + assert!(matches!(err, Error::InvalidRiotId(_)), "{bad}"); + } + let err = tracker.sync("Inconnu#EUW", &mut |_| {}).unwrap_err(); + assert!(matches!(err, Error::Source(SourceError::NotFound))); +} + +#[test] +fn readers_are_not_blocked_while_a_fetch_is_in_flight() { + let dir = tempfile::tempdir().unwrap(); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec()) + .gated(entered_tx, release_rx); + let tracker = open(&dir.path().join("arena.db"), fake); + + thread::scope(|scope| { + let import = scope.spawn(|| sync(&tracker)); + entered_rx.recv().unwrap(); + // The import is now waiting on the source; the UI thread must still get answers. + assert_eq!(tracker.match_count(SELF_PUUID).unwrap(), 0); + assert_eq!(tracker.accounts().unwrap().len(), 1); + release_tx.send(()).unwrap(); + assert_eq!(import.join().unwrap().added, 1); + }); +} + +#[test] +fn concurrent_syncs_run_one_after_the_other_and_fetch_each_match_once() { + let dir = tempfile::tempdir().unwrap(); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let fake = FakeHistory::new(recorded_account(), recorded_matches()[..1].to_vec()) + .gated(entered_tx, release_rx); + let fetches = fake.fetch_counter(); + let tracker = open(&dir.path().join("arena.db"), fake); + + let (overlapped, added) = thread::scope(|scope| { + let first = scope.spawn(|| sync(&tracker)); + entered_rx.recv().unwrap(); + let second = scope.spawn(|| sync(&tracker)); + // Without the lock, the second sync would reach the source while the first waits there. + let overlapped = entered_rx.recv_timeout(Duration::from_millis(300)).is_ok(); + release_tx.send(()).unwrap(); + release_tx.send(()).unwrap(); + let added = (first.join().unwrap().added, second.join().unwrap().added); + (overlapped, added) + }); + + assert!(!overlapped); + assert_eq!(added, (1, 0)); + assert_eq!(fetches.load(Ordering::SeqCst), 1); +} diff --git a/crates/core/tests/statistics.rs b/crates/core/tests/statistics.rs new file mode 100644 index 0000000..b86caaf --- /dev/null +++ b/crates/core/tests/statistics.rs @@ -0,0 +1,595 @@ +mod common; + +use arena_tracker_core::{ + Champion, ChampionRow, ChampionState, Column, Error, Format, Scope, Season, SeasonScope, + StateFilter, Statistics, Tracker, sort_rows, +}; +use common::jan_2026 as jan; +use common::{ + CATALOG, FakeHistory, RIOT_ID, S1, S2, SELF_PUUID, at, date, imported_tracker, payloads, + played_match, recorded_account, run, seasons, +}; +use std::sync::atomic::Ordering; + +fn stats(tracker: &Tracker, season: &str, format: Option) -> Statistics { + let scope = Scope { + season: SeasonScope::Season(season.into()), + format, + }; + tracker.statistics(SELF_PUUID, &scope).unwrap() +} + +fn all_seasons(tracker: &Tracker) -> Statistics { + let scope = Scope { + season: SeasonScope::AllSeasons, + format: None, + }; + tracker.statistics(SELF_PUUID, &scope).unwrap() +} + +fn row(stats: &Statistics, champion_id: u32) -> &ChampionRow { + stats + .rows + .iter() + .find(|r| r.champion.id == champion_id) + .unwrap() +} + +#[test] +fn attempts_run_up_to_the_first_top_1_and_no_further() { + let dir = tempfile::tempdir().unwrap(); + let tracker = imported_tracker(dir.path(), &run(11, &[5, 4, 1, 3], jan(2, 0))); + + let stats = stats(&tracker, S1, None); + + let yi = row(&stats, 11); + assert_eq!(yi.state, Some(ChampionState::Completed)); + assert_eq!(yi.attempts, Some(3)); + assert_eq!(yi.matches, 4); + let challenge = stats.challenge.unwrap(); + assert_eq!((challenge.completed, challenge.first_tries), (1, 0)); + assert_eq!(challenge.attempts, 3); +} + +#[test] +fn champion_states() { + let dir = tempfile::tempdir().unwrap(); + let matches = [run(222, &[1], jan(2, 0)), run(103, &[3, 5], jan(2, 0))].concat(); + let tracker = imported_tracker(dir.path(), &matches); + + let stats = stats(&tracker, S1, None); + + let first_try = row(&stats, 222); + assert_eq!(first_try.state, Some(ChampionState::Completed)); + assert_eq!(first_try.attempts, Some(1)); + let in_progress = row(&stats, 103); + assert_eq!(in_progress.state, Some(ChampionState::InProgress)); + assert_eq!(in_progress.attempts, Some(2)); + let never_played = row(&stats, 8); + assert_eq!(never_played.state, Some(ChampionState::NeverPlayed)); + assert_eq!(never_played.attempts, Some(0)); + assert_eq!(stats.challenge.unwrap().first_tries, 1); +} + +#[test] +fn challenge_totals_count_every_attempt_but_average_only_completed_champions() { + let dir = tempfile::tempdir().unwrap(); + let matches = [ + run(11, &[5, 4, 1, 3], jan(2, 0)), // Completed in 3 + run(222, &[1], jan(3, 0)), // First Try + run(103, &[3, 5], jan(4, 0)), // in progress, 2 Attempts so far + ] + .concat(); + let tracker = imported_tracker(dir.path(), &matches); + + let challenge = stats(&tracker, S1, None).challenge.unwrap(); + + assert_eq!(challenge.completed, 2); + assert_eq!(challenge.total, CATALOG.len()); + assert_eq!(challenge.attempts, 3 + 1 + 2); + assert_eq!(challenge.average_attempts, Some(2.0)); + assert_eq!(challenge.first_tries, 1); +} + +#[test] +fn average_attempts_is_none_when_nothing_is_completed() { + let dir = tempfile::tempdir().unwrap(); + let tracker = imported_tracker(dir.path(), &run(103, &[3, 5], jan(2, 0))); + + let challenge = stats(&tracker, S1, None).challenge.unwrap(); + + assert_eq!(challenge.completed, 0); + assert_eq!(challenge.average_attempts, None); + assert_eq!(challenge.attempts, 2); +} + +#[test] +fn a_top_1_in_any_format_completes_the_champion() { + let dir = tempfile::tempdir().unwrap(); + let matches = [ + played_match(11, 5, jan(2, 0)).in_format(1740), + played_match(11, 1, jan(2, 1)).in_format(1700), + ] + .to_vec(); + let tracker = imported_tracker(dir.path(), &matches); + + let stats = stats(&tracker, S1, Some(Format::BraveryArena)); + + // Only the Bravery Arena Match is in scope, yet the Challenge still sees both. + assert_eq!(row(&stats, 11).matches, 1); + assert_eq!(row(&stats, 11).state, Some(ChampionState::Completed)); + assert_eq!(row(&stats, 11).attempts, Some(2)); + assert_eq!(stats.challenge.unwrap().completed, 1); +} + +#[test] +fn the_format_filter_changes_statistics_and_never_the_challenge() { + let dir = tempfile::tempdir().unwrap(); + let matches = vec![ + played_match(11, 5, jan(2, 0)), + played_match(11, 1, jan(2, 1)).in_format(1740), + played_match(11, 3, jan(2, 2)), + played_match(11, 6, jan(2, 4)).in_format(1740), + played_match(222, 2, jan(3, 0)).in_format(1740), + ]; + let tracker = imported_tracker(dir.path(), &matches); + + let everything = stats(&tracker, S1, None); + let filtered = stats(&tracker, S1, Some(Format::Arena3x6)); + + let (all, only) = (row(&everything, 11), row(&filtered, 11)); + assert_eq!( + (all.matches, all.top1, all.wins, all.best_placement), + (4, 1, 2, Some(1)) + ); + assert_eq!(all.average_placement, Some(3.75)); + assert_eq!(all.last_match_ms, Some(jan(2, 4))); + assert_eq!( + (only.matches, only.top1, only.wins, only.best_placement), + (2, 0, 1, Some(3)) + ); + assert_eq!(only.average_placement, Some(4.0)); + assert_eq!(only.last_match_ms, Some(jan(2, 2))); + assert_eq!(row(&filtered, 222).matches, 0); + assert_eq!(row(&filtered, 222).last_match_ms, None); + assert_eq!( + everything.charts.placements, + [(1, 1), (2, 1), (3, 1), (4, 0), (5, 1), (6, 1)] + ); + assert_eq!( + filtered.charts.placements, + [(1, 0), (2, 0), (3, 1), (4, 0), (5, 1)] + ); + + // Unchanged: the Challenge, every state and Attempts count, the two Challenge charts. + assert_eq!(everything.challenge, filtered.challenge); + for (a, b) in everything.rows.iter().zip(&filtered.rows) { + assert_eq!( + (a.state, a.attempts), + (b.state, b.attempts), + "{}", + a.champion.name + ); + } + assert_eq!( + everything.charts.completed_over_time, + filtered.charts.completed_over_time + ); + assert_eq!( + everything.charts.attempts_to_complete, + filtered.charts.attempts_to_complete + ); + assert_eq!(everything.formats, [Format::Arena3x6, Format::BraveryArena]); + assert_eq!(filtered.formats, everything.formats); +} + +#[test] +fn a_season_starts_at_its_first_millisecond() { + let dir = tempfile::tempdir().unwrap(); + let s1_start = date(2026, 1, 1).start_ms(); + let s2_start = date(2026, 4, 1).start_ms(); + let matches = vec![ + played_match(1, 4, s1_start - 1), // before the first Season + played_match(8, 4, s1_start), // first instant of S1 + played_match(11, 4, s2_start - 1), // last millisecond of S1 + played_match(19, 4, s2_start), // first instant of S2 + ]; + let tracker = imported_tracker(dir.path(), &matches); + + let in_season = |name| -> Vec { + let stats = stats(&tracker, name, None); + let mut ids: Vec = stats + .rows + .iter() + .filter(|r| r.matches > 0) + .map(|r| r.champion.id) + .collect(); + ids.sort(); + ids + }; + + assert_eq!(in_season(S1), [8, 11]); + assert_eq!(in_season(S2), [19]); + let everything = all_seasons(&tracker); + assert_eq!(everything.rows.iter().filter(|r| r.matches > 0).count(), 4); + assert_eq!(row(&everything, 1).matches, 1); +} + +#[test] +fn each_season_has_its_own_challenge_and_the_current_one_is_found_by_date() { + let dir = tempfile::tempdir().unwrap(); + let matches = [ + run(11, &[1], jan(2, 0)), + run(11, &[4], at(date(2026, 4, 2), 0)), + ] + .concat(); + let tracker = imported_tracker(dir.path(), &matches); + + let past = stats(&tracker, S1, None); + let current = stats(&tracker, S2, None); + + assert_eq!(past.challenge.unwrap().completed, 1); + let challenge = current.challenge.clone().unwrap(); + assert_eq!((challenge.completed, challenge.attempts), (0, 1)); + assert_eq!(row(¤t, 11).state, Some(ChampionState::InProgress)); + + let name = |ms| tracker.current_season(ms).map(|s| s.name); + assert_eq!(name(date(2026, 1, 1).start_ms() - 1), None); + assert_eq!(name(date(2026, 1, 1).start_ms()), Some(S1.into())); + assert_eq!(name(date(2026, 4, 1).start_ms() - 1), Some(S1.into())); + assert_eq!(name(date(2026, 4, 1).start_ms()), Some(S2.into())); + assert_eq!(name(date(2100, 1, 1).start_ms()), Some(S2.into())); + assert_eq!(tracker.seasons(), seasons()); +} + +#[test] +fn the_all_seasons_view_has_no_challenge() { + let dir = tempfile::tempdir().unwrap(); + let matches = [ + run(11, &[1], jan(2, 0)), + run(11, &[4], at(date(2026, 4, 2), 0)), + run(222, &[3], at(date(2025, 6, 1), 0)), + ] + .concat(); + let tracker = imported_tracker(dir.path(), &matches); + + let stats = all_seasons(&tracker); + + assert_eq!(stats.challenge, None); + let yi = row(&stats, 11); + assert_eq!((yi.matches, yi.top1, yi.best_placement), (2, 1, Some(1))); + assert_eq!(yi.average_placement, Some(2.5)); + assert_eq!((yi.attempts, yi.state), (None, None)); + assert_eq!( + (row(&stats, 222).attempts, row(&stats, 222).state), + (None, None) + ); + assert_eq!(row(&stats, 8).state, Some(ChampionState::NeverPlayed)); + assert_eq!(row(&stats, 8).attempts, None); + assert!(stats.charts.completed_over_time.is_empty()); + assert_eq!(stats.charts.attempts_to_complete, [0; 5]); + assert_eq!(stats.charts.placements, [(1, 1), (2, 0), (3, 1), (4, 1)]); +} + +#[test] +fn an_unknown_season_is_an_error() { + let dir = tempfile::tempdir().unwrap(); + let tracker = imported_tracker(dir.path(), &[]); + let scope = Scope { + season: SeasonScope::Season("Saison Z".into()), + format: None, + }; + + let err = tracker.statistics(SELF_PUUID, &scope).unwrap_err(); + + assert!(matches!(err, Error::UnknownSeason(name) if name == "Saison Z")); +} + +#[test] +fn an_edited_season_table_reassigns_stored_matches_without_importing_again() { + let dir = tempfile::tempdir().unwrap(); + let matches = [run(11, &[4], jan(1, 1)), run(19, &[4], jan(3, 1))].concat(); + drop(imported_tracker(dir.path(), &matches)); + + let history = FakeHistory::new(recorded_account(), payloads(&matches)); + let fetches = history.fetch_counter(); + let tracker = Tracker::open(&dir.path().join("arena.db"), Box::new(history)) + .unwrap() + .with_seasons(vec![ + Season { + name: "Début".into(), + start: date(2026, 1, 1), + official_track: None, + }, + Season { + name: "Suite".into(), + start: date(2026, 1, 2), + official_track: None, + }, + ]); + + let report = tracker.sync(RIOT_ID, &mut |_| {}).unwrap(); + + assert_eq!((report.added, fetches.load(Ordering::SeqCst)), (0, 0)); + let played = |name| -> Vec { + stats(&tracker, name, None) + .rows + .iter() + .filter(|r| r.matches > 0) + .map(|r| r.champion.id) + .collect() + }; + assert_eq!(played("Début"), [11]); + assert_eq!(played("Suite"), [19]); + assert!( + tracker + .statistics( + SELF_PUUID, + &Scope { + season: SeasonScope::Season(S1.into()), + format: None + } + ) + .is_err() + ); +} + +#[test] +fn row_values_for_one_champion() { + let dir = tempfile::tempdir().unwrap(); + let matches = vec![ + played_match(11, 4, jan(2, 1)), + played_match(11, 1, jan(2, 2)).in_format(1740), + played_match(11, 2, jan(2, 3)).in_format(1700), + ]; + let tracker = imported_tracker(dir.path(), &matches); + + let stats = stats(&tracker, S1, None); + + let yi = row(&stats, 11); + assert_eq!( + yi.champion, + Champion { + id: 11, + key: "MasterYi".into(), + name: "Maître Yi".into() + } + ); + assert_eq!(yi.matches, 3); + assert_eq!(yi.best_placement, Some(1)); + assert_eq!(yi.top1, 1); + assert_eq!(yi.wins, 2); + assert_eq!(yi.average_placement, Some(7.0 / 3.0)); + assert_eq!(yi.last_match_ms, Some(jan(2, 3))); + let unplayed = row(&stats, 8); + assert_eq!(unplayed.matches, 0); + assert_eq!( + ( + unplayed.best_placement, + unplayed.average_placement, + unplayed.last_match_ms + ), + (None, None, None) + ); +} + +#[test] +fn the_chart_series_are_empty_without_matches() { + let dir = tempfile::tempdir().unwrap(); + let tracker = imported_tracker(dir.path(), &[]); + + let charts = stats(&tracker, S1, None).charts; + + assert!(charts.placements.is_empty()); + assert!(charts.completed_over_time.is_empty()); + assert_eq!(charts.attempts_to_complete, [0; 5]); +} + +#[test] +fn the_chart_series_follow_the_completions() { + let dir = tempfile::tempdir().unwrap(); + let matches = [ + run(1, &[1], jan(2, 1)), + run(8, &[1], jan(2, 5)), + run(11, &[4, 1], jan(5, 0)), + run(19, &[3, 3, 3, 3, 1], jan(6, 0)), + run(103, &[6, 6, 6, 6, 6, 6, 1], jan(6, 8)), + run(222, &[2, 2, 1], jan(10, 0)), + ] + .concat(); + let tracker = imported_tracker(dir.path(), &matches); + + let charts = stats(&tracker, S1, None).charts; + + assert_eq!( + charts.completed_over_time, + [ + (date(2026, 1, 2), 2), + (date(2026, 1, 5), 3), + (date(2026, 1, 6), 5), + (date(2026, 1, 10), 6), + ] + ); + // 1 Attempt: Annie and Vladimir; 2: Maître Yi; 3: Jinx; 5 or more: Warwick and Ahri. + assert_eq!(charts.attempts_to_complete, [2, 1, 1, 0, 2]); +} + +fn bare_row(name: &str, id: u32) -> ChampionRow { + ChampionRow { + champion: Champion { + id, + key: name.into(), + name: name.into(), + }, + portrait: None, + matches: 0, + best_placement: None, + top1: 0, + wins: 0, + average_placement: None, + last_match_ms: None, + attempts: None, + state: None, + } +} + +fn names(rows: &[ChampionRow]) -> Vec<&str> { + rows.iter().map(|r| r.champion.name.as_str()).collect() +} + +#[test] +fn rows_sort_by_column_with_missing_values_last_and_ties_by_name() { + let with_attempts = |name, id, attempts| ChampionRow { + attempts, + ..bare_row(name, id) + }; + let mut rows = vec![ + with_attempts("Bard", 3, Some(3)), + with_attempts("Zed", 4, None), + with_attempts("Annie", 1, Some(3)), + with_attempts("Ahri", 2, Some(1)), + with_attempts("Jinx", 5, Some(0)), + ]; + + sort_rows(&mut rows, Column::Attempts, true); + assert_eq!(names(&rows), ["Annie", "Bard", "Ahri", "Jinx", "Zed"]); + sort_rows(&mut rows, Column::Attempts, false); + assert_eq!(names(&rows), ["Jinx", "Ahri", "Annie", "Bard", "Zed"]); +} + +#[test] +fn rows_sort_by_name_ignoring_case_and_accents() { + let mut rows: Vec<_> = ["Zoé", "Zed", "Maître Yi", "Nami", "ahri"] + .iter() + .zip(1..) + .map(|(name, id)| bare_row(name, id)) + .collect(); + + sort_rows(&mut rows, Column::Champion, false); + assert_eq!(names(&rows), ["ahri", "Maître Yi", "Nami", "Zed", "Zoé"]); + sort_rows(&mut rows, Column::Champion, true); + assert_eq!(names(&rows), ["Zoé", "Zed", "Nami", "Maître Yi", "ahri"]); +} + +#[test] +fn rows_sort_by_numbers_and_dates() { + let rows = vec![ + ChampionRow { + average_placement: Some(2.5), + last_match_ms: Some(10), + matches: 1, + ..bare_row("A", 1) + }, + ChampionRow { + average_placement: Some(1.5), + last_match_ms: Some(30), + matches: 3, + ..bare_row("B", 2) + }, + bare_row("C", 3), + ]; + let order = |column, descending| { + let mut sorted = rows.clone(); + sort_rows(&mut sorted, column, descending); + sorted + .iter() + .map(|r| r.champion.name.clone()) + .collect::>() + .concat() + }; + + assert_eq!(order(Column::AveragePlacement, false), "BAC"); + assert_eq!(order(Column::AveragePlacement, true), "ABC"); + assert_eq!(order(Column::LastMatch, true), "BAC"); + assert_eq!(order(Column::Matches, true), "BAC"); + assert_eq!(order(Column::Wins, false), "ABC"); // all zero: by name +} + +#[test] +fn state_filters_keep_the_expected_rows() { + let with_state = |state| ChampionRow { + state, + ..bare_row("A", 1) + }; + let completed = with_state(Some(ChampionState::Completed)); + let in_progress = with_state(Some(ChampionState::InProgress)); + let never = with_state(Some(ChampionState::NeverPlayed)); + let unknown = with_state(None); + let kept = |filter: StateFilter| -> Vec { + [&completed, &in_progress, &never, &unknown] + .iter() + .map(|r| filter.keeps(r)) + .collect() + }; + + assert_eq!(kept(StateFilter::All), [true, true, true, true]); + assert_eq!(kept(StateFilter::Completed), [true, false, false, false]); + assert_eq!(kept(StateFilter::Remaining), [false, true, true, false]); + assert_eq!(kept(StateFilter::NeverPlayed), [false, false, true, false]); +} + +#[test] +fn open_tracker_alone_uses_the_shipped_seasons() { + let dir = tempfile::tempdir().unwrap(); + let tracker = Tracker::open( + &dir.path().join("arena.db"), + Box::new(FakeHistory::new(recorded_account(), vec![])), + ) + .unwrap(); + + assert_eq!(tracker.seasons(), arena_tracker_core::default_seasons()); +} + +#[test] +fn rows_sort_by_state_with_unknown_states_last() { + let with_state = |name, id, state| ChampionRow { + state, + ..bare_row(name, id) + }; + let mut rows = vec![ + with_state("Zed", 1, Some(ChampionState::NeverPlayed)), + with_state("Bard", 2, None), + with_state("Nami", 3, Some(ChampionState::InProgress)), + with_state("Jinx", 4, Some(ChampionState::Completed)), + with_state("Ahri", 5, Some(ChampionState::NeverPlayed)), + with_state("Annie", 6, Some(ChampionState::Completed)), + ]; + + sort_rows(&mut rows, Column::State, false); + assert_eq!( + names(&rows), + ["Annie", "Jinx", "Nami", "Ahri", "Zed", "Bard"] + ); + sort_rows(&mut rows, Column::State, true); + assert_eq!( + names(&rows), + ["Ahri", "Zed", "Nami", "Annie", "Jinx", "Bard"] + ); +} + +#[test] +fn attempts_follow_start_times_not_the_order_matches_were_stored_in() { + let dir = tempfile::tempdir().unwrap(); + // Riot hands the newest Match over first: the top 1 is stored before the two failures. + let matches = [ + played_match(11, 1, jan(5, 0)), + played_match(11, 4, jan(3, 0)), + played_match(11, 6, jan(2, 0)), + ]; + let tracker = Tracker::open( + &dir.path().join("arena.db"), + Box::new(FakeHistory::new(recorded_account(), payloads(&matches)).delivered_as_given()), + ) + .unwrap() + .with_seasons(seasons()); + tracker.sync(RIOT_ID, &mut |_| {}).unwrap(); + + let stats = stats(&tracker, S1, None); + + let yi = row(&stats, 11); + assert_eq!( + (yi.state, yi.attempts), + (Some(ChampionState::Completed), Some(3)) + ); + assert_eq!(stats.challenge.unwrap().average_attempts, Some(3.0)); +}