From 9d9b67666b09dc490ca6d959b806050d6826193c Mon Sep 17 00:00:00 2001 From: Nessar Date: Thu, 19 Nov 2026 18:11:02 +0100 Subject: [PATCH 1/6] Capture Arena 3x6 bans, hovers and lock-in for #13 --- .../fixtures/client/arena_champ_select.json | 216 ++++++++++++++++++ 1 file changed, 216 insertions(+) create mode 100644 crates/core/tests/fixtures/client/arena_champ_select.json diff --git a/crates/core/tests/fixtures/client/arena_champ_select.json b/crates/core/tests/fixtures/client/arena_champ_select.json new file mode 100644 index 0000000..9f43fa8 --- /dev/null +++ b/crates/core/tests/fixtures/client/arena_champ_select.json @@ -0,0 +1,216 @@ +{ + "gameflow": { + "phase": "ChampSelect", + "map": { + "id": 30, + "gameMode": "CHERRY" + }, + "gameData": { + "queue": { + "id": 1750, + "gameMode": "CHERRY" + } + } + }, + "pickableChampionIds": [ + 103, + 12, + 16, + 233, + 25, + 50 + ], + "disabledChampionIds": [], + "ownedChampionsMinimal": [ + { + "id": 12, + "ownership": { + "owned": true + } + }, + { + "id": 16, + "ownership": { + "owned": true + } + }, + { + "id": 25, + "ownership": { + "owned": true + } + }, + { + "id": 50, + "ownership": { + "owned": true + } + }, + { + "id": 103, + "ownership": { + "owned": true + } + }, + { + "id": 233, + "ownership": { + "owned": true + } + } + ], + "sessions": [ + { + "localPlayerCellId": 16, + "myTeam": [ + { + "cellId": 16, + "championId": 0, + "championPickIntent": 0 + }, + { + "cellId": 17, + "championId": 0, + "championPickIntent": 0 + } + ], + "actions": [], + "bans": { + "myTeamBans": [], + "theirTeamBans": [] + } + }, + { + "localPlayerCellId": 16, + "myTeam": [ + { + "cellId": 16, + "championId": 0, + "championPickIntent": 0 + }, + { + "cellId": 17, + "championId": 0, + "championPickIntent": 25 + } + ], + "actions": [ + [ + { + "type": "ban", + "championId": 12, + "completed": true + }, + { + "type": "ban", + "championId": 50, + "completed": false + } + ] + ], + "bans": { + "myTeamBans": [], + "theirTeamBans": [] + } + }, + { + "localPlayerCellId": 16, + "myTeam": [ + { + "cellId": 16, + "championId": 0, + "championPickIntent": 233 + }, + { + "cellId": 17, + "championId": 0, + "championPickIntent": 25 + } + ], + "actions": [ + [ + { + "type": "ban", + "championId": 12, + "completed": true + }, + { + "type": "ban", + "championId": 50, + "completed": true + } + ] + ], + "bans": { + "myTeamBans": [], + "theirTeamBans": [] + } + }, + { + "localPlayerCellId": 16, + "myTeam": [ + { + "cellId": 16, + "championId": 0, + "championPickIntent": 16 + }, + { + "cellId": 17, + "championId": 25, + "championPickIntent": 25 + } + ], + "actions": [ + [ + { + "type": "ban", + "championId": 12, + "completed": true + }, + { + "type": "ban", + "championId": 50, + "completed": true + } + ] + ], + "bans": { + "myTeamBans": [], + "theirTeamBans": [] + } + }, + { + "localPlayerCellId": 16, + "myTeam": [ + { + "cellId": 16, + "championId": 16, + "championPickIntent": 0 + }, + { + "cellId": 17, + "championId": 25, + "championPickIntent": 25 + } + ], + "actions": [ + [ + { + "type": "ban", + "championId": 12, + "completed": true + }, + { + "type": "ban", + "championId": 50, + "completed": true + } + ] + ], + "bans": { + "myTeamBans": [], + "theirTeamBans": [] + } + } + ] +} -- 2.54.0 From fabaa8a60f2ca6ce685da6d9222921099571551c Mon Sep 17 00:00:00 2001 From: Nessar Date: Thu, 19 Nov 2026 18:16:38 +0100 Subject: [PATCH 2/6] Record the five anvil champions from the same Arena session --- crates/core/tests/fixtures/client/arena_champ_select.json | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/core/tests/fixtures/client/arena_champ_select.json b/crates/core/tests/fixtures/client/arena_champ_select.json index 9f43fa8..bd93b65 100644 --- a/crates/core/tests/fixtures/client/arena_champ_select.json +++ b/crates/core/tests/fixtures/client/arena_champ_select.json @@ -212,5 +212,12 @@ "theirTeamBans": [] } } + ], + "crowdFavoriteChampionIds": [ + 233, + 64, + 5, + 16, + 68 ] } -- 2.54.0 From f4a9e5e7a8ee9902e5ea4f2376ae1b134937b2e3 Mon Sep 17 00:00:00 2001 From: Nessar Date: Thu, 19 Nov 2026 18:31:21 +0100 Subject: [PATCH 3/6] Show live Arena champion picks and crowd favorites (#13) --- crates/app/src/champion_table.rs | 13 ++ crates/app/src/main.rs | 15 +- crates/app/src/stats_page.rs | 271 +++++++++++++++++++++++++++++-- crates/app/src/worker.rs | 61 +++++-- crates/core/src/champ_select.rs | 121 ++++++++++++++ crates/core/src/client.rs | 9 + crates/core/src/follow.rs | 19 ++- crates/core/src/league_client.rs | 75 ++++++++- crates/core/src/lib.rs | 2 + crates/core/tests/common/mod.rs | 14 ++ crates/core/tests/follow.rs | 75 +++++++++ 11 files changed, 636 insertions(+), 39 deletions(-) create mode 100644 crates/core/src/champ_select.rs diff --git a/crates/app/src/champion_table.rs b/crates/app/src/champion_table.rs index 3e831f1..1448f66 100644 --- a/crates/app/src/champion_table.rs +++ b/crates/app/src/champion_table.rs @@ -194,6 +194,19 @@ impl ChampionTable { } } +/// Prepared on pick/statistics changes so a redraw only lays out the labels. +pub fn pick_labels(row: &ChampionRow) -> Vec { + SPECS + .iter() + .map(|spec| { + if spec.key == SortKey::Champion { + return row.champion.name.clone().into(); + } + format!("{} · {}", spec.title, cell_text(row, spec.key)).into() + }) + .collect() +} + /// A cell of `spec`'s column, header or body: fixed width, shrinking with the window. // Text past it is clipped: an ellipsis (`text_ellipsis`) cost 0.2 ms per frame (#31). fn cell(spec: &Spec) -> Div { diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 060f1f9..bdf651a 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -43,6 +43,7 @@ struct RootView { fallback_riot_id: String, tx: Sender, _form_events: Subscription, + _champ_select: Subscription, } impl RootView { @@ -82,10 +83,22 @@ impl RootView { KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)), KeyEvent::Back => {} } + this.form.update(cx, |form, cx| form.reset(window, cx)); this.screen = Screen::Page; this.focus.focus(window, cx); cx.notify(); }); + let champ_select = cx.subscribe_in( + &page, + window, + |this, _, _: &stats_page::ChampSelectTransition, window, cx| { + if this.screen == Screen::Settings { + this.screen = Screen::Page; + this.focus.focus(window, cx); + cx.notify(); + } + }, + ); let screen = if first_launch { Screen::Prompt } else { @@ -101,6 +114,7 @@ impl RootView { fallback_riot_id: riot_id, tx, _form_events: form_events, + _champ_select: champ_select, } } @@ -120,7 +134,6 @@ impl Render for RootView { let settings = settings_button(self.screen == Screen::Page, cx).on_click(cx.listener( |this, _, window, cx| { if this.screen == Screen::Page { - this.form.update(cx, |form, cx| form.reset(window, cx)); this.screen = Screen::Settings; this.focus.focus(window, cx); cx.notify(); diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs index 99bf697..6ff8ac9 100644 --- a/crates/app/src/stats_page.rs +++ b/crates/app/src/stats_page.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arena_tracker_core::{ - Account, ChallengeSummary, ChampionSearch, Charts, Format, ProgressCheck, Scope, SeasonScope, - StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, + Account, ChallengeSummary, ChampSelect, ChampionSearch, Charts, Format, ProgressCheck, Scope, + SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, }; use gpui_kit::base::async_util::{Receiver, Sender}; use gpui_kit::component::StyledExt as _; @@ -76,12 +76,18 @@ impl SelectItem for AccountItem { } } +pub struct ChampSelectTransition; +impl EventEmitter for StatsPage {} + pub struct StatsPage { tracker: Arc, tx: Sender, notice: Option, /// As of the last follower round or refresh. status: Status, + selection: crate::worker::Selection, + current_pick: Vec, + favorites: Vec, accounts: Vec, last_active: Option, /// The Account the user picked instead of following the one being updated. @@ -242,6 +248,9 @@ impl StatsPage { tracker, tx, notice, + selection: None, + current_pick: Vec::new(), + favorites: Vec::new(), accounts: Vec::new(), last_active: None, pinned: None, @@ -337,14 +346,39 @@ impl StatsPage { } } Msg::Champions => self.reload_in_background(window, cx), + Msg::Selection(selection) => { + if self.selection == selection { + return; + } + let next = selection.as_ref().and_then(|s| s.as_ref().ok()); + let changed_page = self.selection.is_some() != selection.is_some(); + let previous = self.selection.as_ref().and_then(|s| s.as_ref().ok()); + let switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id); + let pool_changed = + previous.map(|(_, s)| &s.pickable) != next.map(|(_, s)| &s.pickable); + self.selection = selection; + if switch { + self.stats_generation += 1; + self.stats = None; + self.stats_error = None; + self.stored = None; + self.reload_in_background(window, cx); + } + if changed_page { + cx.emit(ChampSelectTransition); + } + self.update_picks(); + if pool_changed || switch { + self.refresh_table(cx); + } + } Msg::Round { status, reload } => { - // A follower round that changes nothing shown must not rebuild the page (they keep coming). - let unchanged = status == self.status + if status == self.status && !reload && !self.pending_round && self.progress.is_none() - && !self.crashed; - if unchanged { + && !self.crashed + { return; } self.status = status; @@ -449,6 +483,26 @@ impl StatsPage { cx: &mut Context, ) -> Option { self.last_reload = Instant::now(); + if self.selection.is_some() { + if computing { + self.stats_generation += 1; + } + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + self.current_season = self + .tracker + .current_season(now.as_millis() as i64) + .map(|s| s.name); + let (id, _) = self.selection.as_ref()?.as_ref().ok()?; + let id = id.to_lowercase(); + return self + .accounts + .iter() + .find(|a| riot_id(a).to_lowercase() == id) + .filter(|_| self.current_season.is_some()) + .map(|a| a.puuid.clone()); + } if matches!(self.season, SeasonScope::AllSeasons) && !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed) { @@ -470,6 +524,21 @@ impl StatsPage { viewed } + fn statistics_scope(&self) -> Scope { + if self.selection.is_some() + && let Some(season) = &self.current_season + { + return Scope { + season: SeasonScope::Season(season.clone()), + format: None, + }; + } + Scope { + season: self.season.clone(), + format: self.format, + } + } + /// Requests the statistics from a worker (`start_job`: none is running), or shows none when no /// Account is viewed. fn recompute_in_background( @@ -481,10 +550,7 @@ impl StatsPage { let viewed = self.prepare_statistics(start_job, window, cx); if let Some(puuid) = viewed { if start_job { - let scope = Scope { - season: self.season.clone(), - format: self.format, - }; + let scope = self.statistics_scope(); // A below-normal worker keeps hidden and visible windows responsive (rule #1). spawn_statistics( self.tracker.clone(), @@ -512,10 +578,7 @@ impl StatsPage { self.stats_error = None; self.stored = None; if let Some(puuid) = &viewed { - let scope = Scope { - season: self.season.clone(), - format: self.format, - }; + let scope = self.statistics_scope(); match self.tracker.statistics(puuid, &scope) { Ok(stats) => self.stats = Some(stats), Err(e) => self.stats_error = Some(format!("Statistiques indisponibles : {e}")), @@ -527,6 +590,12 @@ impl StatsPage { /// Shows `stats`: the Format choices, the charts and the table. fn show_statistics(&mut self, window: &mut Window, cx: &mut Context) { + if self.selection.is_some() { + self.update_picks(); + self.refresh_table(cx); + cx.notify(); + return; + } let charts = self.stats.as_ref().map(|s| &s.charts); let in_season = self.in_season(); self.charts @@ -546,19 +615,134 @@ impl StatsPage { cx.notify(); } + fn live_pick(&self) -> Option<&ChampSelect> { + self.selection.as_ref()?.as_ref().ok().map(|(_, pick)| pick) + } + + fn update_picks(&mut self) { + let rows = self.stats.as_ref().map_or(&[][..], |s| s.rows.as_slice()); + let pick = self.live_pick(); + let current = pick + .and_then(|s| s.current_row(rows)) + .map(crate::champion_table::pick_labels) + .unwrap_or_default(); + self.favorites = pick + .into_iter() + .flat_map(|s| { + s.crowd_favorites.iter().flatten().map(|id| { + let row = rows.iter().find(|r| r.champion.id == *id); + let mut label = + row.map_or_else(|| format!("Champion {id}"), |r| r.champion.name.clone()); + if let Some(state) = row.and_then(|r| r.state) { + label.push_str(" · "); + label.push_str(crate::text::state_label(Some(state))); + } + if !s.pickable.contains(id) && s.current != Some(*id) { + label.push_str(" · Indisponible"); + } + SharedString::from(label) + }) + }) + .collect(); + self.favorites.sort(); + self.current_pick = current; + } + fn refresh_table(&mut self, cx: &mut Context) { let rows = self.stats.iter().flat_map(|s| &s.rows); let rows = rows - .filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion)) + .filter(|row| match &self.selection { + Some(Ok((_, pick))) => pick.remaining(row), + Some(Err(_)) => false, + None => self.filter.keeps(row) && self.search.matches(&row.champion), + }) .cloned() .collect(); - let in_season = self.in_season(); + let in_season = self.selection.is_some() || self.in_season(); self.table.update(cx, |table, cx| { table.set_rows(rows, in_season); cx.notify(); }); } + fn champ_select_view(&self, cx: &App) -> Div { + let pick = self.live_pick(); + let border = cx.theme().border; + let mut page = div().v_flex().size_full().p_3().gap_3().child( + div() + .text_xl() + .font_weight(FontWeight::SEMIBOLD) + .child("Sélection des champions · Arena"), + ); + let Some(pick) = pick else { + return page.child("Sélection indisponible dans le client."); + }; + page = page.child(match self.current_pick.split_first() { + Some((name, labels)) => div() + .h_flex() + .items_center() + .flex_wrap() + .gap_x_4() + .gap_y_1() + .child(div().font_weight(FontWeight::SEMIBOLD).child(name.clone())) + .children( + labels + .iter() + .cloned() + .map(|label| div().text_sm().child(label)), + ), + None => div().child(pick.current.map_or_else( + || "Aucun champion sélectionné".to_owned(), + |id| format!("Champion {id} · Statistiques indisponibles"), + )), + }); + page.child( + div() + .v_flex() + .gap_2() + .p_3() + .border_1() + .border_color(border) + .rounded_md() + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .child("Favoris du public · Enclume"), + ) + .child( + div() + .h_flex() + .flex_wrap() + .gap_x_4() + .gap_y_1() + .children(self.favorites.iter().cloned().map(|name| div().child(name))) + .when(self.favorites.is_empty(), |row| { + row.child("Aucun favori communiqué par le client") + }), + ), + ) + .child( + div() + .font_weight(FontWeight::SEMIBOLD) + .child("Champions disponibles à valider"), + ) + .when(self.stats.is_none(), |page| { + page.child(self.stats_error.clone().unwrap_or_else(|| { + if self.current_season.is_none() { + "Aucune Saison en cours" + } else if self.status.updating.is_none() { + "Compte indisponible" + } else { + "Chargement des statistiques…" + } + .into() + })) + }) + .when(self.stats.is_some(), |page| { + page.child(div().flex_1().min_h_0().child(self.table.clone())) + }) + } + /// One line each, the most important first; the stored data stays visible under all. fn banners(&self) -> Vec { let mut banners = Vec::new(); @@ -859,6 +1043,9 @@ impl Render for StatsPage { let theme = cx.theme(); (theme.border, theme.muted_foreground) }; + if self.selection.is_some() { + return self.champ_select_view(cx); + } let options = filters(self.in_season()); let selected = options.iter().position(|(_, f)| *f == self.filter); let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref()); @@ -1110,6 +1297,58 @@ mod tests { }); } + #[gpui::test] + async fn champ_select_uses_the_signed_in_accounts_challenge_and_restores_the_pinned_page( + cx: &mut TestAppContext, + ) { + use crate::worker::Msg; + use arena_tracker_core::{ChampSelect, SeasonScope}; + cx.executor().allow_parking(); + let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap(); + tracker.sync("Bob#EUW", &mut |_| {}).unwrap(); + tracker.follow_client(0, Some("Alice#EUW"), &mut |_| {}); + let (page, mut window) = open_page_with_tracker(cx, tracker); + let pick = ChampSelect { + current: Some(39), + pickable: [39].into(), + crowd_favorites: Some(vec![39]), + }; + window.update(|w, cx| { + page.update(cx, |p, cx| { + p.pinned = Some("Bob".into()); + p.season = SeasonScope::AllSeasons; + p.filter = StateFilter::NeverPlayed; + p.reload(w, cx); + assert!(p.stats.as_ref().unwrap().rows.is_empty()); + p.apply(Msg::Selection(Some(Ok(("Alice#EUW".into(), pick)))), w, cx); + }) + }); + cx.condition(&page, |p, _| !p.current_pick.is_empty()).await; + page.read_with(cx, |p, cx| { + assert_eq!(p.current_pick[0].as_ref(), "Irelia"); + assert!( + p.current_pick + .iter() + .any(|l| l.starts_with("Tentatives · 1")) + ); + assert_eq!(p.favorites.len(), 1); + assert!(p.favorites[0].starts_with("Irelia · ")); + assert_eq!(p.table.read(cx).names(), ["Irelia"]); + }); + window.update(|w, cx| { + page.update(cx, |p, cx| { + p.apply(Msg::Selection(None), w, cx); + }) + }); + cx.condition(&page, |p, _| p.stats.is_some()).await; + page.read_with(cx, |p, cx| { + assert_eq!(p.viewed().unwrap().puuid, "Bob"); + assert_eq!(p.season, SeasonScope::AllSeasons); + assert_eq!(p.filter, StateFilter::NeverPlayed); + assert!(p.table.read(cx).names().is_empty()); + }); + } + #[gpui::test] fn typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) { let (page, cx) = open_page(cx); diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs index 807ba90..aae96ed 100644 --- a/crates/app/src/worker.rs +++ b/crates/app/src/worker.rs @@ -6,16 +6,24 @@ use std::sync::Arc; use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; -use arena_tracker_core::{Scope, Statistics, Status, SyncProgress, Tracker}; +use arena_tracker_core::{ + ChampSelect, ClientError, Scope, Statistics, Status, SyncProgress, Tracker, +}; use gpui_kit::base::async_util::Sender; +pub type Selection = Option>; + pub enum Msg { + Selection(Selection), /// A sync is fetching Matches. Progress(SyncProgress), /// The champion catalog and portraits were refreshed. Champions, /// A follower round ended; `reload` when the stored data may have changed. - Round { status: Status, reload: bool }, + Round { + status: Status, + reload: bool, + }, /// A refresh ended. Refreshed(Status), /// Statistics for a requested scope were computed. @@ -103,8 +111,7 @@ fn spawn_guarded(tx: Sender, on_panic: Msg, body: impl FnOnce(&Sender) }); } -/// Keeps the active Account up to date for as long as the app runs: one thread, rounds of -/// `follow_client` separated by `wait_for_client`. `fallback_riot_id` is the configured Riot ID. +/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds and a live selection subscription. `fallback_riot_id` is the configured Riot ID. /// The champion catalog and portraits are fetched on another thread, so a first launch's /// import never waits for them. pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sender) { @@ -113,20 +120,48 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende let _ = champions.refresh_champions(); let _ = tx.try_send(Msg::Champions); }); - spawn_guarded(tx, Msg::Crashed, move |tx| { + // Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks. + let (wake, rounds) = std::sync::mpsc::sync_channel(1); + let history = tracker.clone(); + spawn_guarded(tx.clone(), Msg::Crashed, move |tx| { let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty()); let mut first = true; - loop { - let changed = tracker.follow_client(now_ms(), fallback, &mut |progress| { + for () in rounds { + let changed = history.follow_client(now_ms(), fallback, &mut |progress| { let _ = tx.try_send(Msg::Progress(progress)); }); - let status = tracker.status(); - let _ = tx.try_send(Msg::Round { - status, - reload: changed || first, - }); + if tx + .try_send(Msg::Round { + status: history.status(), + reload: changed || first, + }) + .is_err() + { + break; + } first = false; - tracker.wait_for_client(); + } + }); + spawn_guarded(tx, Msg::Crashed, move |tx| { + let mut previous = None; + let mut selection_only = false; + while !tx.is_closed() { + if !selection_only + && matches!( + wake.try_send(()), + Err(std::sync::mpsc::TrySendError::Disconnected(())) + ) + { + break; + } + let selection = tracker.champ_select(); + if selection != previous { + if tx.try_send(Msg::Selection(selection.clone())).is_err() { + break; + } + previous = selection; + } + selection_only = tracker.wait_for_client(); } }); } diff --git a/crates/core/src/champ_select.rs b/crates/core/src/champ_select.rs new file mode 100644 index 0000000..2c477c3 --- /dev/null +++ b/crates/core/src/champ_select.rs @@ -0,0 +1,121 @@ +//! The local player's pick and the champions offered during an Arena champ select. +use std::collections::HashSet; + +use serde_json::Value; + +use crate::league_client::parse; +use crate::{ChampionRow, ChampionState, ClientError}; + +#[derive(Clone, Debug, PartialEq)] +pub struct ChampSelect { + pub current: Option, + /// The five anvil champions. None when the client could not report the list. + pub crowd_favorites: Option>, + pub pickable: HashSet, +} + +fn champion_id(value: &Value) -> Option { + u32::try_from(value.as_u64()?).ok().filter(|id| *id != 0) +} + +fn array(value: &Value) -> Result<&[Value], ClientError> { + value + .as_array() + .map(Vec::as_slice) + .ok_or_else(|| ClientError::Other("Liste de champions illisible".into())) +} + +impl ChampSelect { + pub fn available_champions( + pickable: &str, + disabled: &str, + owned: &str, + ) -> Result, ClientError> { + let mut ids: HashSet<_> = array(&parse(owned)?)? + .iter() + .filter(|c| c["ownership"]["owned"] == true) + .filter_map(|c| champion_id(&c["id"])) + .collect(); + for id in array(&parse(disabled)?)?.iter().filter_map(champion_id) { + ids.remove(&id); + } + Ok(array(&parse(pickable)?)? + .iter() + .filter_map(champion_id) + .filter(|id| ids.contains(id)) + .collect()) + } + + pub fn from_session( + body: &str, + mut pickable: HashSet, + crowd_favorites: Option>, + ) -> Result { + let session = parse(body)?; + let local = session["localPlayerCellId"] + .as_i64() + .ok_or(ClientError::Absent)?; + let team = array(&session["myTeam"])?; + let me = team + .iter() + .find(|p| p["cellId"] == local) + .ok_or(ClientError::Absent)?; + let current = + champion_id(&me["championId"]).or_else(|| champion_id(&me["championPickIntent"])); + for player in team + .iter() + .filter(|p| p["cellId"] != local && p["team"] == me["team"]) + { + if let Some(id) = champion_id(&player["championId"]) { + pickable.remove(&id); + } + } + // In Arena the confirmed bans were in actions while both team ban lists were empty. + for turn in array(&session["actions"])? { + for action in array(turn)? { + if action["type"] == "ban" + && action["completed"] == true + && let Some(id) = champion_id(&action["championId"]) + { + pickable.remove(&id); + } + } + } + for key in ["myTeamBans", "theirTeamBans"] { + if let Some(bans) = session["bans"][key].as_array() { + for id in bans.iter().filter_map(champion_id) { + pickable.remove(&id); + } + } + } + Ok(Self { + current, + pickable, + crowd_favorites, + }) + } + + pub fn current_row<'a>(&self, rows: &'a [ChampionRow]) -> Option<&'a ChampionRow> { + let id = self.current?; + rows.iter().find(|r| r.champion.id == id) + } + + pub fn remaining(&self, row: &ChampionRow) -> bool { + row.state.is_some_and(|s| s != ChampionState::Completed) + && self.pickable.contains(&row.champion.id) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pickable_excludes_disabled_unowned_and_unavailable_champions() { + let owned = r#"[{"id":1,"ownership":{"owned":true}},{"id":2,"ownership":{"owned":false}},{"id":3,"ownership":{"owned":true}},{"id":4,"ownership":{"owned":true}}]"#; + assert_eq!( + ChampSelect::available_champions("[1,2,3]", "[3]", owned).unwrap(), + HashSet::from([1]) + ); + } +} diff --git a/crates/core/src/client.rs b/crates/core/src/client.rs index d4feb08..afedbf4 100644 --- a/crates/core/src/client.rs +++ b/crates/core/src/client.rs @@ -8,8 +8,17 @@ pub trait GameClientSource: Send + Sync { /// 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>; + /// Reads the live Arena selection after gameflow enters champ select. + fn champ_select(&self) -> Result { + Err(ClientError::Absent) + } /// Blocks until the client reports a change or `timeout` elapses. fn wait_for_change(&self, timeout: Duration); + /// True when only the live selection needs another read. + fn wait_for_selection_event(&self, timeout: Duration) -> bool { + self.wait_for_change(timeout); + false + } } #[derive(Debug, Clone, PartialEq)] diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs index 6ad80d7..c60c55d 100644 --- a/crates/core/src/follow.rs +++ b/crates/core/src/follow.rs @@ -303,17 +303,30 @@ impl Tracker { self.status() != before || added > 0 } + /// The signed-in Riot ID and its live pick. Independent of slow Match history imports. + pub fn champ_select(&self) -> Option> { + let client = self.client.as_ref()?; + let flow = client.gameflow().ok()?; + (flow.arena && flow.phase == GamePhase::ChampSelect).then(|| { + let (name, tag) = client.signed_in()?; + Ok((format!("{name}#{tag}"), client.champ_select()?)) + }) + } + /// 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) { + pub fn wait_for_client(&self) -> bool { 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), + Some(client) => client.wait_for_selection_event(timeout), + None => { + thread::sleep(timeout); + false + } } } diff --git a/crates/core/src/league_client.rs b/crates/core/src/league_client.rs index 1dedc2e..b762068 100644 --- a/crates/core/src/league_client.rs +++ b/crates/core/src/league_client.rs @@ -27,10 +27,15 @@ 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] = [ +const FAVORITES: &str = "/lol-lobby-team-builder/champ-select/v1/crowd-favorte-champion-list"; +const TOPICS: &[&str] = &[ "OnJsonApiEvent_lol-gameflow_v1_session", "OnJsonApiEvent_lol-summoner_v1_current-summoner", "OnJsonApiEvent_lol-champ-select_v1_session", + "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids", + "OnJsonApiEvent_lol-champ-select_v1_disabled-champion-ids", + "OnJsonApiEvent_lol-champions_v1_owned-champions-minimal", + "OnJsonApiEvent_lol-lobby-team-builder_champ-select_v1_crowd-favorite-champion-list", ]; /// The local League client's API (unofficial, read-only). Deliberately no `Debug`: it handles @@ -42,6 +47,13 @@ pub struct LeagueClient { /// configuration is downloaded once per track. tracks: Mutex)>>, events: Mutex>, + pool: Mutex>, +} + +struct ChampionPool { + available: std::collections::HashSet, + favorites: Option>, + next_favorites_read: Instant, } struct Events(WebSocket>); @@ -82,6 +94,7 @@ impl LeagueClient { agent, tracks: Mutex::default(), events: Mutex::default(), + pool: Mutex::default(), } } @@ -155,7 +168,40 @@ impl GameClientSource for LeagueClient { fn gameflow(&self) -> Result { let (status, body) = self.get("/lol-gameflow/v1/session")?; - decode_gameflow(status, &body) + let flow = decode_gameflow(status, &body)?; + if !flow.arena || flow.phase != GamePhase::ChampSelect { + *lock(&self.pool) = None; + } + Ok(flow) + } + + fn champ_select(&self) -> Result { + let session = self.get_ok("/lol-champ-select/v1/session")?; + let mut pool = lock(&self.pool); + if pool.is_none() { + let available = crate::ChampSelect::available_champions( + &self.get_ok("/lol-champ-select/v1/pickable-champion-ids")?, + &self.get_ok("/lol-champ-select/v1/disabled-champion-ids")?, + &self.get_ok("/lol-champions/v1/owned-champions-minimal")?, + )?; + *pool = Some(ChampionPool { + available, + favorites: None, + next_favorites_read: Instant::now(), + }); + } + let pool = pool.as_mut().unwrap(); + if pool.favorites.as_ref().is_none_or(Vec::is_empty) + && Instant::now() >= pool.next_favorites_read + { + // The GET spells it "favorte"; the event spells it "favorite". + pool.favorites = self + .get_ok(FAVORITES) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()); + pool.next_favorites_read = Instant::now() + Duration::from_secs(1); + } + crate::ChampSelect::from_session(&session, pool.available.clone(), pool.favorites.clone()) } fn official_progress(&self, track_name: &str) -> Result, ClientError> { @@ -183,14 +229,23 @@ impl GameClientSource for LeagueClient { } fn wait_for_change(&self, timeout: Duration) { + self.wait_for_selection_event(timeout); + } + + fn wait_for_selection_event(&self, timeout: Duration) -> bool { let started = Instant::now(); let mut events = lock(&self.events); if events.is_none() { + *lock(&self.pool) = None; *events = self.connect(); + // Re-read the snapshot after subscribing. + if events.is_some() { + return false; + } } let Some(connection) = events.as_mut() else { thread::sleep(timeout.min(TIMEOUT)); - return; + return false; }; // Right after subscribing, the client sends one empty text frame per subscription // (observed on patch 16.22): they and pings are not changes. @@ -203,14 +258,22 @@ impl GameClientSource for LeagueClient { .map_err(tungstenite::Error::Io) .and_then(|()| connection.0.read()); match read { - Ok(Message::Text(text)) if !text.is_empty() => return, + Ok(Message::Text(text)) if !text.is_empty() => { + let topic = text.split('"').nth(1).unwrap_or_default(); + let session = topic == "OnJsonApiEvent_lol-champ-select_v1_session"; + if !session { + *lock(&self.pool) = None; + } + return topic.starts_with("OnJsonApiEvent_lol-champ-select_") + || topic.ends_with("_crowd-favorite-champion-list"); + } Ok(Message::Close(_)) => *events = None, Ok(_) => continue, Err(tungstenite::Error::Io(e)) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} Err(_) => *events = None, } - return; + return false; } } } @@ -271,7 +334,7 @@ fn install_dir_from_settings(yaml: &str) -> Option { (!path.is_empty()).then(|| path.into()) } -fn parse(body: &str) -> Result { +pub(crate) fn parse(body: &str) -> Result { serde_json::from_str(body) .map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}"))) } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 010a1df..df8f615 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1,3 +1,4 @@ +mod champ_select; mod champion_search; mod champions; mod client; @@ -12,6 +13,7 @@ mod seasons; mod statistics; mod tracker; +pub use champ_select::ChampSelect; pub use champion_search::ChampionSearch; pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon}; pub use client::{ClientError, GameClientSource, GamePhase, Gameflow}; diff --git a/crates/core/tests/common/mod.rs b/crates/core/tests/common/mod.rs index 3c9ccf5..a528df5 100644 --- a/crates/core/tests/common/mod.rs +++ b/crates/core/tests/common/mod.rs @@ -569,6 +569,7 @@ struct ClientState { gameflow: Gameflow, tracks: HashMap, waits: Vec, + selection: Option, } impl FakeClient { @@ -633,6 +634,10 @@ impl FakeClient { self.state.lock().unwrap().gameflow.game_id = game_id; } + pub fn set_selection(&self, value: arena_tracker_core::ChampSelect) { + self.state.lock().unwrap().selection = Some(value); + } + pub fn set_track(&self, name: &str, value: u32) { self.state.lock().unwrap().tracks.insert(name.into(), value); } @@ -659,6 +664,15 @@ impl GameClientSource for FakeClient { Ok(state.gameflow.clone()) } + fn champ_select(&self) -> Result { + self.state + .lock() + .unwrap() + .selection + .clone() + .ok_or(ClientError::Absent) + } + fn official_progress(&self, track_name: &str) -> Result, ClientError> { let state = self.state.lock().unwrap(); state.signed_in.as_ref().ok_or(ClientError::Absent)?; diff --git a/crates/core/tests/follow.rs b/crates/core/tests/follow.rs index 882172a..6af9682 100644 --- a/crates/core/tests/follow.rs +++ b/crates/core/tests/follow.rs @@ -1023,3 +1023,78 @@ fn banners_point_to_the_parametres_screen_and_never_to_a_missing_field() { assert!(!text(problem).contains("réglages")); } } + +#[test] +fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge() { + use arena_tracker_core::{ChampSelect, ChampionState}; + use serde_json::Value; + let capture: Value = + serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap(); + let world = World::new( + &[12, 16, 25, 50, 103, 233].map(|id| played_match(id, if id == 16 { 1 } else { 4 }, now())), + ); + let tracker = world.tracker(); + let read = |frame: usize| { + ChampSelect::from_session( + &capture["sessions"][frame].to_string(), + ChampSelect::available_champions( + &capture["pickableChampionIds"].to_string(), + &capture["disabledChampionIds"].to_string(), + &capture["ownedChampionsMinimal"].to_string(), + ) + .unwrap(), + Some(serde_json::from_value(capture["crowdFavoriteChampionIds"].clone()).unwrap()), + ) + .unwrap() + }; + world.client.set_selection(read(0)); + world.client.set_phase("ChampSelect", false); + round(&tracker); + assert!(tracker.champ_select().is_none()); + world.client.set_phase("ChampSelect", true); + let rows = tracker + .statistics( + SELF_PUUID, + &Scope { + season: SeasonScope::Season(S2.into()), + format: None, + }, + ) + .unwrap() + .rows; + for (frame, current, remaining) in [ + (0, None, vec![12, 25, 50, 103, 233]), + (1, None, vec![25, 50, 103, 233]), + ( + 2, + Some((233, ChampionState::InProgress)), + vec![25, 103, 233], + ), + (3, Some((16, ChampionState::Completed)), vec![103, 233]), + (4, Some((16, ChampionState::Completed)), vec![103, 233]), + ] { + world.client.set_selection(read(frame)); + round(&tracker); + let (account, pick) = tracker.champ_select().unwrap().unwrap(); + assert_eq!(account, "Joueur#EUW"); + assert_eq!( + pick.crowd_favorites.as_deref(), + Some([233, 64, 5, 16, 68].as_slice()) + ); + assert_eq!( + pick.current_row(&rows) + .map(|r| (r.champion.id, r.attempts, r.state)), + current.map(|(id, state)| (id, Some(1), Some(state))) + ); + let mut ids: Vec<_> = rows + .iter() + .filter(|r| pick.remaining(r)) + .map(|r| r.champion.id) + .collect(); + ids.sort_unstable(); + assert_eq!(ids, remaining); + } + world.client.set_phase("InProgress", true); + round(&tracker); + assert!(tracker.champ_select().is_none()); +} -- 2.54.0 From 5ba32518754ba772b64d7102b3f5e01359fe98cb Mon Sep 17 00:00:00 2001 From: Nessar Date: Thu, 19 Nov 2026 20:25:31 +0100 Subject: [PATCH 4/6] Fix champ select review findings (#13) - redraw the page on hover and lock-in changes, and reset the settings form when champ select takes the window away - keep the current pick when a client read fails; only a real answer that the draft is over ends it - read the client once per wake and share it between the follower and the live selection, reuse session event payloads, and touch only the cached champion list an event concerns - replay the captured raw client responses in the fake and cover the list cache, event updates and the anvil-champion read - name the five champions anvil champions and the set pickable, document them, and prepare redraw strings ahead of render --- CONTEXT.md | 15 ++ crates/app/src/main.rs | 2 + crates/app/src/stats_page.rs | 203 ++++++++++++++++---------- crates/app/src/text.rs | 2 +- crates/app/src/worker.rs | 63 +++++--- crates/core/src/champ_select.rs | 242 ++++++++++++++++++++++++++----- crates/core/src/client.rs | 60 +++++++- crates/core/src/follow.rs | 117 ++++++++++----- crates/core/src/league_client.rs | 199 +++++++++++++++++-------- crates/core/src/lib.rs | 8 +- crates/core/tests/common/mod.rs | 70 +++++++-- crates/core/tests/follow.rs | 89 ++++++++---- 12 files changed, 799 insertions(+), 271 deletions(-) diff --git a/CONTEXT.md b/CONTEXT.md index 47d7caa..928d160 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -52,6 +52,18 @@ _Avoid_: Split, run A League of Legends account; the active Account is the one signed in to the game client. _Avoid_: Player, profile, summoner +**Champ select**: +The draft before an Arena Match, where each player bans and picks a champion; only an Arena champ select opens the champ select view. +_Avoid_: Draft, selection + +**Anvil champions**: +The five champions the game favours in the current Arena patch and shows during champ select; the game client calls them crowd favorites. +_Avoid_: Crowd favorites, favorites + +**Pickable**: +A champion the local player can still pick in the current Arena champ select: offered by the client, not disabled, and neither banned nor taken by another player. +_Avoid_: Available, owned, remaining + **Official Progress**: The game's own per-Season count of champions it considers completed, used only to cross-check a Challenge. _Avoid_: Riot challenge, tracker @@ -71,5 +83,8 @@ The interface is in French. Each glossary term has one French word in user-facin | Win | Victoire | | Season | Saison | | Account | Compte | +| Champ select | Sélection des champions | +| Anvil champions | Champions de l'Enclume | +| Pickable | Disponible | | Official Progress | Progression officielle | | Placement, Format, Top N | unchanged | diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index bdf651a..3fd14ec 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -93,6 +93,8 @@ impl RootView { window, |this, _, _: &stats_page::ChampSelectTransition, window, cx| { if this.screen == Screen::Settings { + // Champ select takes the window away: do not bring back half-typed edits. + this.form.update(cx, |form, cx| form.reset(window, cx)); this.screen = Screen::Page; this.focus.focus(window, cx); cx.notify(); diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs index 6ff8ac9..0aa0c6d 100644 --- a/crates/app/src/stats_page.rs +++ b/crates/app/src/stats_page.rs @@ -4,8 +4,9 @@ use std::sync::Arc; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arena_tracker_core::{ - Account, ChallengeSummary, ChampSelect, ChampionSearch, Charts, Format, ProgressCheck, Scope, - SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, UpdateProblem, + Account, ChallengeSummary, ChampSelect, ChampionRow, ChampionSearch, Charts, Format, + ProgressCheck, Scope, SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, + UpdateProblem, same_riot_id, }; use gpui_kit::base::async_util::{Receiver, Sender}; use gpui_kit::component::StyledExt as _; @@ -86,8 +87,13 @@ pub struct StatsPage { /// As of the last follower round or refresh. status: Status, selection: crate::worker::Selection, - current_pick: Vec, - favorites: Vec, + /// The current champion's cells, prepared when the pick or the statistics change. + current_labels: Vec, + /// What the panel says when the current champion has no statistics row. + current_fallback: SharedString, + /// What the panel says while the statistics are missing. + selection_notice: SharedString, + anvil_labels: Vec, accounts: Vec, last_active: Option, /// The Account the user picked instead of following the one being updated. @@ -249,8 +255,10 @@ impl StatsPage { tx, notice, selection: None, - current_pick: Vec::new(), - favorites: Vec::new(), + current_labels: Vec::new(), + current_fallback: SharedString::default(), + selection_notice: SharedString::default(), + anvil_labels: Vec::new(), accounts: Vec::new(), last_active: None, pinned: None, @@ -350,12 +358,15 @@ impl StatsPage { if self.selection == selection { return; } - let next = selection.as_ref().and_then(|s| s.as_ref().ok()); - let changed_page = self.selection.is_some() != selection.is_some(); - let previous = self.selection.as_ref().and_then(|s| s.as_ref().ok()); + let previous = self.selection.as_ref(); + let next = selection.as_ref(); + let changed_page = previous.is_some() != next.is_some(); let switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id); - let pool_changed = - previous.map(|(_, s)| &s.pickable) != next.map(|(_, s)| &s.pickable); + let pool_changed = match (previous, next) { + (Some((_, before)), Some((_, after))) => !before.same_pickable(after), + (None, None) => false, + _ => true, + }; self.selection = selection; if switch { self.stats_generation += 1; @@ -371,8 +382,12 @@ impl StatsPage { if pool_changed || switch { self.refresh_table(cx); } + // A hover or lock-in changes neither the Account nor the pool: redraw the page + // so the current-pick panel follows, even when the table is untouched. + cx.notify(); } Msg::Round { status, reload } => { + // A follower round that changes nothing shown must not rebuild the page (they keep coming). if status == self.status && !reload && !self.pending_round @@ -388,6 +403,9 @@ impl StatsPage { if reload { self.reload_in_background(window, cx); } + if self.in_champ_select() { + self.update_picks(); + } } Msg::Refreshed(status) => { self.status = status; @@ -483,7 +501,7 @@ impl StatsPage { cx: &mut Context, ) -> Option { self.last_reload = Instant::now(); - if self.selection.is_some() { + if self.in_champ_select() { if computing { self.stats_generation += 1; } @@ -494,12 +512,11 @@ impl StatsPage { .tracker .current_season(now.as_millis() as i64) .map(|s| s.name); - let (id, _) = self.selection.as_ref()?.as_ref().ok()?; - let id = id.to_lowercase(); + let (id, _) = self.selection.as_ref()?; return self .accounts .iter() - .find(|a| riot_id(a).to_lowercase() == id) + .find(|a| same_riot_id(&riot_id(a), id)) .filter(|_| self.current_season.is_some()) .map(|a| a.puuid.clone()); } @@ -525,7 +542,7 @@ impl StatsPage { } fn statistics_scope(&self) -> Scope { - if self.selection.is_some() + if self.in_champ_select() && let Some(season) = &self.current_season { return Scope { @@ -590,7 +607,7 @@ impl StatsPage { /// Shows `stats`: the Format choices, the charts and the table. fn show_statistics(&mut self, window: &mut Window, cx: &mut Context) { - if self.selection.is_some() { + if self.in_champ_select() { self.update_picks(); self.refresh_table(cx); cx.notify(); @@ -615,50 +632,75 @@ impl StatsPage { cx.notify(); } - fn live_pick(&self) -> Option<&ChampSelect> { - self.selection.as_ref()?.as_ref().ok().map(|(_, pick)| pick) + fn in_champ_select(&self) -> bool { + self.selection.is_some() + } + + fn live_champ_select(&self) -> Option<&ChampSelect> { + self.selection.as_ref().map(|(_, pick)| pick) } fn update_picks(&mut self) { let rows = self.stats.as_ref().map_or(&[][..], |s| s.rows.as_slice()); - let pick = self.live_pick(); - let current = pick + let pick = self.live_champ_select(); + let current_labels = pick .and_then(|s| s.current_row(rows)) .map(crate::champion_table::pick_labels) .unwrap_or_default(); - self.favorites = pick - .into_iter() - .flat_map(|s| { - s.crowd_favorites.iter().flatten().map(|id| { - let row = rows.iter().find(|r| r.champion.id == *id); - let mut label = - row.map_or_else(|| format!("Champion {id}"), |r| r.champion.name.clone()); - if let Some(state) = row.and_then(|r| r.state) { - label.push_str(" · "); - label.push_str(crate::text::state_label(Some(state))); - } - if !s.pickable.contains(id) && s.current != Some(*id) { - label.push_str(" · Indisponible"); - } - SharedString::from(label) - }) + let mut anvil_labels: Vec = pick + .map(|s| { + s.anvil_champions + .iter() + .map(|id| { + let row = rows.iter().find(|r| r.champion.id == *id); + let mut label = champion_label(row, *id); + if let Some(state) = row.and_then(|r| r.state) { + label.push_str(" · "); + label.push_str(crate::text::state_label(Some(state))); + } + if !s.can_pick(*id) { + label.push_str(" · Indisponible"); + } + SharedString::from(label) + }) + .collect() }) - .collect(); - self.favorites.sort(); - self.current_pick = current; + .unwrap_or_default(); + anvil_labels.sort(); + let current_fallback = match pick { + Some(s) => match s.current { + Some(id) if current_labels.is_empty() => { + let row = rows.iter().find(|r| r.champion.id == id); + format!("{} · Statistiques indisponibles", champion_label(row, id)).into() + } + Some(_) => SharedString::default(), + None => "Aucun champion sélectionné".into(), + }, + None => "Sélection indisponible dans le client.".into(), + }; + let selection_notice = match (&self.stats_error, self.stats.is_some()) { + (Some(error), _) => error.clone().into(), + (None, true) => SharedString::default(), + (None, false) if self.current_season.is_none() => "Aucune Saison en cours".into(), + (None, false) if self.status.updating.is_none() => "Compte indisponible".into(), + (None, false) => "Chargement des statistiques…".into(), + }; + self.current_labels = current_labels; + self.anvil_labels = anvil_labels; + self.current_fallback = current_fallback; + self.selection_notice = selection_notice; } fn refresh_table(&mut self, cx: &mut Context) { let rows = self.stats.iter().flat_map(|s| &s.rows); let rows = rows .filter(|row| match &self.selection { - Some(Ok((_, pick))) => pick.remaining(row), - Some(Err(_)) => false, + Some((_, pick)) => pick.remaining(row), None => self.filter.keeps(row) && self.search.matches(&row.champion), }) .cloned() .collect(); - let in_season = self.selection.is_some() || self.in_season(); + let in_season = self.in_champ_select() || self.in_season(); self.table.update(cx, |table, cx| { table.set_rows(rows, in_season); cx.notify(); @@ -666,7 +708,6 @@ impl StatsPage { } fn champ_select_view(&self, cx: &App) -> Div { - let pick = self.live_pick(); let border = cx.theme().border; let mut page = div().v_flex().size_full().p_3().gap_3().child( div() @@ -674,10 +715,10 @@ impl StatsPage { .font_weight(FontWeight::SEMIBOLD) .child("Sélection des champions · Arena"), ); - let Some(pick) = pick else { + if self.live_champ_select().is_none() { return page.child("Sélection indisponible dans le client."); - }; - page = page.child(match self.current_pick.split_first() { + } + page = page.child(match self.current_labels.split_first() { Some((name, labels)) => div() .h_flex() .items_center() @@ -691,10 +732,7 @@ impl StatsPage { .cloned() .map(|label| div().text_sm().child(label)), ), - None => div().child(pick.current.map_or_else( - || "Aucun champion sélectionné".to_owned(), - |id| format!("Champion {id} · Statistiques indisponibles"), - )), + None => div().child(self.current_fallback.clone()), }); page.child( div() @@ -707,7 +745,7 @@ impl StatsPage { .child( div() .font_weight(FontWeight::SEMIBOLD) - .child("Favoris du public · Enclume"), + .child("Champions de l'Enclume"), ) .child( div() @@ -715,9 +753,14 @@ impl StatsPage { .flex_wrap() .gap_x_4() .gap_y_1() - .children(self.favorites.iter().cloned().map(|name| div().child(name))) - .when(self.favorites.is_empty(), |row| { - row.child("Aucun favori communiqué par le client") + .children( + self.anvil_labels + .iter() + .cloned() + .map(|name| div().child(name)), + ) + .when(self.anvil_labels.is_empty(), |row| { + row.child("Aucun champion de l'Enclume communiqué par le client") }), ), ) @@ -727,16 +770,7 @@ impl StatsPage { .child("Champions disponibles à valider"), ) .when(self.stats.is_none(), |page| { - page.child(self.stats_error.clone().unwrap_or_else(|| { - if self.current_season.is_none() { - "Aucune Saison en cours" - } else if self.status.updating.is_none() { - "Compte indisponible" - } else { - "Chargement des statistiques…" - } - .into() - })) + page.child(self.selection_notice.clone()) }) .when(self.stats.is_some(), |page| { page.child(div().flex_1().min_h_0().child(self.table.clone())) @@ -777,6 +811,11 @@ impl StatsPage { } } +/// The champion's name, or the client's id when the catalog does not know it. +fn champion_label(row: Option<&ChampionRow>, id: u32) -> String { + row.map_or_else(|| format!("Champion {id}"), |row| row.champion.name.clone()) +} + fn tile( label: &'static str, value: String, @@ -1043,7 +1082,7 @@ impl Render for StatsPage { let theme = cx.theme(); (theme.border, theme.muted_foreground) }; - if self.selection.is_some() { + if self.in_champ_select() { return self.champ_select_view(cx); } let options = filters(self.in_season()); @@ -1308,11 +1347,7 @@ mod tests { tracker.sync("Bob#EUW", &mut |_| {}).unwrap(); tracker.follow_client(0, Some("Alice#EUW"), &mut |_| {}); let (page, mut window) = open_page_with_tracker(cx, tracker); - let pick = ChampSelect { - current: Some(39), - pickable: [39].into(), - crowd_favorites: Some(vec![39]), - }; + let pick = ChampSelect::new(Some(39), [39].into(), vec![39]); window.update(|w, cx| { page.update(cx, |p, cx| { p.pinned = Some("Bob".into()); @@ -1320,21 +1355,35 @@ mod tests { p.filter = StateFilter::NeverPlayed; p.reload(w, cx); assert!(p.stats.as_ref().unwrap().rows.is_empty()); - p.apply(Msg::Selection(Some(Ok(("Alice#EUW".into(), pick)))), w, cx); + p.apply(Msg::Selection(Some(("Alice#EUW".into(), pick))), w, cx); }) }); - cx.condition(&page, |p, _| !p.current_pick.is_empty()).await; + cx.condition(&page, |p, _| !p.current_labels.is_empty()) + .await; page.read_with(cx, |p, cx| { - assert_eq!(p.current_pick[0].as_ref(), "Irelia"); + assert_eq!(p.current_labels[0].as_ref(), "Irelia"); assert!( - p.current_pick + p.current_labels .iter() .any(|l| l.starts_with("Tentatives · 1")) ); - assert_eq!(p.favorites.len(), 1); - assert!(p.favorites[0].starts_with("Irelia · ")); + assert_eq!(p.anvil_labels.len(), 1); + assert!(p.anvil_labels[0].starts_with("Irelia · ")); assert_eq!(p.table.read(cx).names(), ["Irelia"]); }); + + // A hover change touches neither the Account nor the pool: the panel must still update. + let next = ChampSelect::new(None, [39].into(), vec![39]); + window.update(|w, cx| { + page.update(cx, |p, cx| { + p.apply(Msg::Selection(Some(("Alice#EUW".into(), next))), w, cx); + }) + }); + page.read_with(cx, |p, _| { + assert!(p.current_labels.is_empty()); + assert_eq!(p.current_fallback.as_ref(), "Aucun champion sélectionné"); + }); + window.update(|w, cx| { page.update(cx, |p, cx| { p.apply(Msg::Selection(None), w, cx); diff --git a/crates/app/src/text.rs b/crates/app/src/text.rs index 694bd48..0b99908 100644 --- a/crates/app/src/text.rs +++ b/crates/app/src/text.rs @@ -30,7 +30,7 @@ pub const CLIENT_ABSENT: &str = const INTERNAL_ERROR: &str = "Mise à jour impossible : erreur interne."; pub fn riot_id(account: &Account) -> String { - format!("{}#{}", account.game_name, account.tag_line) + arena_tracker_core::riot_id(&account.game_name, &account.tag_line) } /// The discreet line under the Challenge tile. diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs index aae96ed..80ed6e2 100644 --- a/crates/app/src/worker.rs +++ b/crates/app/src/worker.rs @@ -7,11 +7,12 @@ use std::thread; use std::time::{SystemTime, UNIX_EPOCH}; use arena_tracker_core::{ - ChampSelect, ClientError, Scope, Statistics, Status, SyncProgress, Tracker, + ChampSelect, ClientEvent, Scope, Statistics, Status, SyncProgress, Tracker, }; use gpui_kit::base::async_util::Sender; -pub type Selection = Option>; +/// The signed-in Riot ID and its pick, or none outside an Arena champ select. +pub type Selection = Option<(String, ChampSelect)>; pub enum Msg { Selection(Selection), @@ -111,7 +112,9 @@ fn spawn_guarded(tx: Sender, on_panic: Msg, body: impl FnOnce(&Sender) }); } -/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds and a live selection subscription. `fallback_riot_id` is the configured Riot ID. +/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds +/// and a live selection subscription. Each wake reads the client once and shares that read with +/// both. `fallback_riot_id` is the configured Riot ID. /// The champion catalog and portraits are fetched on another thread, so a first launch's /// import never waits for them. pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sender) { @@ -122,14 +125,23 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende }); // Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks. let (wake, rounds) = std::sync::mpsc::sync_channel(1); + let latest = Arc::new(std::sync::Mutex::new(None)); let history = tracker.clone(); + let history_latest = latest.clone(); spawn_guarded(tx.clone(), Msg::Crashed, move |tx| { let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty()); let mut first = true; for () in rounds { - let changed = history.follow_client(now_ms(), fallback, &mut |progress| { + let snapshot = history_latest.lock().unwrap().take(); + let mut progress = |progress| { let _ = tx.try_send(Msg::Progress(progress)); - }); + }; + let changed = match snapshot { + Some(snapshot) => { + history.follow_client_with(now_ms(), fallback, &snapshot, &mut progress) + } + None => history.follow_client(now_ms(), fallback, &mut progress), + }; if tx .try_send(Msg::Round { status: history.status(), @@ -144,24 +156,41 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende }); spawn_guarded(tx, Msg::Crashed, move |tx| { let mut previous = None; - let mut selection_only = false; + let mut snapshot = tracker.client_snapshot(); + let mut share = true; while !tx.is_closed() { - if !selection_only - && matches!( + // The follower round uses the same read as the live selection: one gameflow request + // per wake, and none for a champ select event. + if share { + *latest.lock().unwrap() = Some(snapshot.clone()); + if matches!( wake.try_send(()), Err(std::sync::mpsc::TrySendError::Disconnected(())) - ) - { - break; - } - let selection = tracker.champ_select(); - if selection != previous { - if tx.try_send(Msg::Selection(selection.clone())).is_err() { + ) { break; } - previous = selection; } - selection_only = tracker.wait_for_client(); + match tracker.champ_select_with(&snapshot) { + Ok(selection) if selection != previous => { + if tx.try_send(Msg::Selection(selection.clone())).is_err() { + break; + } + previous = selection; + } + Ok(_) => {} + // A failed read is not the draft ending: keep what the page shows. + Err(_) => {} + } + // A champ select event costs no request while the draft is already known; any other + // event, or a snapshot that predates the draft, needs a fresh read. + share = tracker.wait_for_client() == ClientEvent::Other + || !snapshot + .gameflow + .as_ref() + .is_ok_and(|flow| flow.is_arena_champ_select()); + if share { + snapshot = tracker.client_snapshot(); + } } }); } diff --git a/crates/core/src/champ_select.rs b/crates/core/src/champ_select.rs index 2c477c3..67012c8 100644 --- a/crates/core/src/champ_select.rs +++ b/crates/core/src/champ_select.rs @@ -1,17 +1,37 @@ //! The local player's pick and the champions offered during an Arena champ select. use std::collections::HashSet; +use std::sync::Arc; use serde_json::Value; use crate::league_client::parse; use crate::{ChampionRow, ChampionState, ClientError}; -#[derive(Clone, Debug, PartialEq)] +pub(crate) const PICKABLE_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids"; +pub(crate) const DISABLED_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_disabled-champion-ids"; +pub(crate) const ANVIL_EVENT: &str = + "OnJsonApiEvent_lol-lobby-team-builder_champ-select_v1_crowd-favorite-champion-list"; + +/// The local player's live pick and the champions they can still pick. +#[derive(Clone, Debug)] pub struct ChampSelect { pub current: Option, - /// The five anvil champions. None when the client could not report the list. - pub crowd_favorites: Option>, - pub pickable: HashSet, + /// The five anvil champions; empty when the client reports none. The client calls them + /// crowd favorites. + pub anvil_champions: Vec, + /// The champions the draft offers, before its bans and the other players' picks. Shared with + /// the client's cache instead of cloned on every session event. + pickable: Arc>, + /// Banned or taken by another player in this session. + excluded: HashSet, +} + +impl PartialEq for ChampSelect { + fn eq(&self, other: &Self) -> bool { + self.current == other.current + && self.anvil_champions == other.anvil_champions + && self.same_pickable(other) + } } fn champion_id(value: &Value) -> Option { @@ -25,33 +45,51 @@ fn array(value: &Value) -> Result<&[Value], ClientError> { .ok_or_else(|| ClientError::Other("Liste de champions illisible".into())) } +fn ids(body: &str) -> Result, ClientError> { + Ok(array(&parse(body)?)? + .iter() + .filter_map(champion_id) + .collect()) +} + +fn ids_from_event(data: &Value) -> Option> { + data.as_array() + .map(|ids| ids.iter().filter_map(champion_id).collect()) +} + +fn ordered_ids(data: &Value) -> Option> { + data.as_array() + .map(|ids| ids.iter().filter_map(champion_id).collect()) +} + impl ChampSelect { - pub fn available_champions( + /// A selection with nothing banned or taken, for tests and callers with a ready pool. + pub fn new(current: Option, pickable: HashSet, anvil_champions: Vec) -> Self { + Self { + current, + anvil_champions, + pickable: Arc::new(pickable), + excluded: HashSet::new(), + } + } + + /// The champions the client offers, minus those disabled for this draft. The pickable list + /// is the client's answer to what the player can pick: it already includes free-rotation and + /// rented champions, so ownership is not consulted. + pub fn pickable_champions( pickable: &str, disabled: &str, - owned: &str, - ) -> Result, ClientError> { - let mut ids: HashSet<_> = array(&parse(owned)?)? - .iter() - .filter(|c| c["ownership"]["owned"] == true) - .filter_map(|c| champion_id(&c["id"])) - .collect(); - for id in array(&parse(disabled)?)?.iter().filter_map(champion_id) { - ids.remove(&id); - } - Ok(array(&parse(pickable)?)? - .iter() - .filter_map(champion_id) - .filter(|id| ids.contains(id)) - .collect()) + ) -> Result>, ClientError> { + let pickable = ids(pickable)?; + let disabled = ids(disabled)?; + Ok(Arc::new(pickable.difference(&disabled).copied().collect())) } pub fn from_session( - body: &str, - mut pickable: HashSet, - crowd_favorites: Option>, + session: &Value, + pickable: Arc>, + anvil_champions: Vec, ) -> Result { - let session = parse(body)?; let local = session["localPlayerCellId"] .as_i64() .ok_or(ClientError::Absent)?; @@ -62,12 +100,13 @@ impl ChampSelect { .ok_or(ClientError::Absent)?; let current = champion_id(&me["championId"]).or_else(|| champion_id(&me["championPickIntent"])); + let mut excluded = HashSet::new(); for player in team .iter() .filter(|p| p["cellId"] != local && p["team"] == me["team"]) { if let Some(id) = champion_id(&player["championId"]) { - pickable.remove(&id); + excluded.insert(id); } } // In Arena the confirmed bans were in actions while both team ban lists were empty. @@ -77,21 +116,20 @@ impl ChampSelect { && action["completed"] == true && let Some(id) = champion_id(&action["championId"]) { - pickable.remove(&id); + excluded.insert(id); } } } for key in ["myTeamBans", "theirTeamBans"] { if let Some(bans) = session["bans"][key].as_array() { - for id in bans.iter().filter_map(champion_id) { - pickable.remove(&id); - } + excluded.extend(bans.iter().filter_map(champion_id)); } } Ok(Self { current, + anvil_champions, pickable, - crowd_favorites, + excluded, }) } @@ -100,22 +138,154 @@ impl ChampSelect { rows.iter().find(|r| r.champion.id == id) } + /// Whether the local player can still pick this champion. Their own pick always stays + /// pickable. + pub fn can_pick(&self, id: u32) -> bool { + self.current == Some(id) || (self.pickable.contains(&id) && !self.excluded.contains(&id)) + } + + /// Whether both selections offer the same champions, whatever the current pick. The shared + /// set makes the common case a pointer comparison. + pub fn same_pickable(&self, other: &Self) -> bool { + (Arc::ptr_eq(&self.pickable, &other.pickable) || self.pickable == other.pickable) + && self.excluded == other.excluded + } + + /// A champion still to complete in the Challenge and pickable in this draft. The player's + /// own hovered or locked champion stays in the list while not Completed: they can pick it. pub fn remaining(&self, row: &ChampionRow) -> bool { - row.state.is_some_and(|s| s != ChampionState::Completed) - && self.pickable.contains(&row.champion.id) + row.state.is_some_and(|s| s != ChampionState::Completed) && self.can_pick(row.champion.id) + } +} + +/// The champion lists of a draft: fetched once, then updated from the client's events. +#[derive(Debug, Default)] +pub(crate) struct ChampSelectLists { + /// The client's pickable list, before the disabled champions are removed. + offered: HashSet, + disabled: HashSet, + anvil: Vec, + /// `offered` minus `disabled`, rebuilt only when either list changes. + pickable: Arc>, +} + +impl ChampSelectLists { + pub(crate) fn fetch( + pickable: &str, + disabled: &str, + anvil: Option<&str>, + ) -> Result { + let mut lists = Self { + offered: ids(pickable)?, + disabled: ids(disabled)?, + ..Self::default() + }; + if let Some(body) = anvil + && let Ok(value) = parse(body) + && let Some(ids) = ordered_ids(&value) + { + lists.anvil = ids; + } + lists.rebuild(); + Ok(lists) + } + + fn rebuild(&mut self) { + self.pickable = Arc::new(self.offered.difference(&self.disabled).copied().collect()); + } + + pub(crate) fn pickable(&self) -> Arc> { + self.pickable.clone() + } + + pub(crate) fn anvil(&self) -> &[u32] { + &self.anvil + } + + /// Applies one client event. Returns false when the topic concerns something else; the lists + /// it does not concern are left untouched. + pub(crate) fn apply_event(&mut self, topic: &str, data: &Value) -> bool { + match topic { + PICKABLE_EVENT => { + if let Some(ids) = ids_from_event(data) { + self.offered = ids; + self.rebuild(); + } + true + } + DISABLED_EVENT => { + if let Some(ids) = ids_from_event(data) { + self.disabled = ids; + self.rebuild(); + } + true + } + ANVIL_EVENT => { + if let Some(ids) = ordered_ids(data) { + self.anvil = ids; + } + true + } + _ => false, + } } } #[cfg(test)] mod tests { use super::*; + use serde_json::json; #[test] - fn pickable_excludes_disabled_unowned_and_unavailable_champions() { - let owned = r#"[{"id":1,"ownership":{"owned":true}},{"id":2,"ownership":{"owned":false}},{"id":3,"ownership":{"owned":true}},{"id":4,"ownership":{"owned":true}}]"#; + fn pickable_excludes_disabled_champions() { assert_eq!( - ChampSelect::available_champions("[1,2,3]", "[3]", owned).unwrap(), - HashSet::from([1]) + &*ChampSelect::pickable_champions("[1,2,3]", "[3]").unwrap(), + &HashSet::from([1, 2]) ); } + + #[test] + fn the_lists_change_only_for_the_events_that_concern_them() { + let mut lists = ChampSelectLists::fetch("[1,2,3]", "[3]", Some("[9,8]")).unwrap(); + assert_eq!(&*lists.pickable(), &HashSet::from([1, 2])); + assert_eq!(lists.anvil(), [9, 8]); + + // A gameflow event used to clear the whole cache, costing three requests again. + assert!(!lists.apply_event( + "OnJsonApiEvent_lol-gameflow_v1_session", + &json!({"phase": "ChampSelect"}) + )); + assert_eq!(&*lists.pickable(), &HashSet::from([1, 2])); + assert_eq!(lists.anvil(), [9, 8]); + + assert!(lists.apply_event(PICKABLE_EVENT, &json!([1, 4]))); + assert_eq!(&*lists.pickable(), &HashSet::from([1, 4])); + assert_eq!(lists.anvil(), [9, 8]); + + assert!(lists.apply_event(DISABLED_EVENT, &json!([1]))); + assert_eq!(&*lists.pickable(), &HashSet::from([4])); + + assert!(lists.apply_event(ANVIL_EVENT, &json!([5, 6]))); + assert_eq!(lists.anvil(), [5, 6]); + } + + #[test] + fn the_anvil_champions_are_read_once_when_the_draft_starts() { + assert!( + ChampSelectLists::fetch("[]", "[]", None) + .unwrap() + .anvil() + .is_empty() + ); + assert_eq!( + ChampSelectLists::fetch("[]", "[]", Some("[1,2]")) + .unwrap() + .anvil(), + [1, 2] + ); + // A malformed anvil answer only loses the anvil list, not the pickable one. + let lists = ChampSelectLists::fetch("[7]", "[]", Some("not json")).unwrap(); + assert_eq!(&*lists.pickable(), &HashSet::from([7])); + assert!(lists.anvil().is_empty()); + } } diff --git a/crates/core/src/client.rs b/crates/core/src/client.rs index afedbf4..0210a80 100644 --- a/crates/core/src/client.rs +++ b/crates/core/src/client.rs @@ -12,12 +12,41 @@ pub trait GameClientSource: Send + Sync { fn champ_select(&self) -> Result { Err(ClientError::Absent) } - /// Blocks until the client reports a change or `timeout` elapses. - fn wait_for_change(&self, timeout: Duration); - /// True when only the live selection needs another read. - fn wait_for_selection_event(&self, timeout: Duration) -> bool { - self.wait_for_change(timeout); - false + /// Blocks until the client reports an event or `timeout` elapses, and says which kind it was. + fn wait_for_event(&self, timeout: Duration) -> ClientEvent; +} + +/// What a wait saw: a champ select change, or anything else (gameflow, summoner, a timeout). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ClientEvent { + /// The champ select session or one of its champion lists changed. + Selection, + /// Anything else. + #[default] + Other, +} + +/// One read of the client, shared by the follower round and the live selection: a wake makes one +/// gameflow request, not one per reader. +#[derive(Clone, Debug)] +pub struct ClientSnapshot { + pub signed_in: Result<(String, String), ClientError>, + pub gameflow: Result, +} + +impl ClientSnapshot { + pub fn read(source: &dyn GameClientSource) -> Self { + Self { + signed_in: source.signed_in(), + gameflow: source.gameflow(), + } + } + + pub fn absent() -> Self { + Self { + signed_in: Err(ClientError::Absent), + gameflow: Err(ClientError::Absent), + } } } @@ -58,6 +87,13 @@ pub struct Gameflow { pub game_id: Option, } +impl Gameflow { + /// The only time the live pick is shown. + pub fn is_arena_champ_select(&self) -> bool { + self.arena && self.phase == GamePhase::ChampSelect + } +} + #[cfg(test)] mod tests { use super::*; @@ -84,4 +120,16 @@ mod tests { assert_eq!(GamePhase::from_client(name), phase, "{name}"); } } + + #[test] + fn only_an_arena_champ_select_shows_the_live_pick() { + let flow = |phase, arena| Gameflow { + phase, + arena, + game_id: None, + }; + assert!(flow(GamePhase::ChampSelect, true).is_arena_champ_select()); + assert!(!flow(GamePhase::ChampSelect, false).is_arena_champ_select()); + assert!(!flow(GamePhase::InGame, true).is_arena_champ_select()); + } } diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs index c60c55d..da78d11 100644 --- a/crates/core/src/follow.rs +++ b/crates/core/src/follow.rs @@ -5,7 +5,7 @@ use std::time::Duration; use rusqlite::OptionalExtension; -use crate::client::{GameClientSource, GamePhase, Gameflow}; +use crate::client::{ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow}; use crate::error::{Error, SourceError}; use crate::model::{Account, SyncProgress, SyncReport}; use crate::seasons::Season; @@ -129,14 +129,20 @@ pub(crate) struct Follow { official_progress: ProgressCheck, } -fn riot_id(account: &Account) -> String { - format!("{}#{}", account.game_name, account.tag_line) +/// `gameName#tagLine`, the one place a Riot ID is built. +pub fn riot_id(game_name: &str, tag_line: &str) -> String { + format!("{game_name}#{tag_line}") } -fn same_riot_id(a: &str, b: &str) -> bool { +/// Riot IDs differ in case only when they name the same Account. +pub fn same_riot_id(a: &str, b: &str) -> bool { a.to_lowercase() == b.to_lowercase() } +fn account_riot_id(account: &Account) -> String { + riot_id(&account.game_name, &account.tag_line) +} + impl Tracker { /// Without a client, it is always absent. pub fn with_client(mut self, client: Box) -> Tracker { @@ -191,16 +197,39 @@ impl Tracker { now_ms: i64, fallback_riot_id: Option<&str>, on_progress: &mut dyn FnMut(SyncProgress), + ) -> bool { + self.follow_client_with( + now_ms, + fallback_riot_id, + &self.client_snapshot(), + on_progress, + ) + } + + /// One read of the client for this wake; the follower round and the live selection share it. + pub fn client_snapshot(&self) -> ClientSnapshot { + match &self.client { + Some(client) => ClientSnapshot::read(client.as_ref()), + None => ClientSnapshot::absent(), + } + } + + /// A follower round on a client read already made for this wake. + pub fn follow_client_with( + &self, + now_ms: i64, + fallback_riot_id: Option<&str>, + snapshot: &ClientSnapshot, + 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 signed_in = snapshot + .signed_in + .as_ref() + .ok() + .map(|(name, tag)| riot_id(name, tag)); + let gameflow = snapshot.gameflow.as_ref().ok().cloned(); let adopt = { let mut follow = self.follow(); if let Some(id) = fallback_riot_id.map(str::trim).filter(|id| !id.is_empty()) { @@ -287,7 +316,7 @@ impl Tracker { .follow() .updating .as_ref() - .is_some_and(|a| same_riot_id(&riot_id(a), signed_in)) => + .is_some_and(|a| same_riot_id(&account_riot_id(a), signed_in)) => { client .official_progress(&track) @@ -303,29 +332,51 @@ impl Tracker { self.status() != before || added > 0 } - /// The signed-in Riot ID and its live pick. Independent of slow Match history imports. - pub fn champ_select(&self) -> Option> { - let client = self.client.as_ref()?; - let flow = client.gameflow().ok()?; - (flow.arena && flow.phase == GamePhase::ChampSelect).then(|| { - let (name, tag) = client.signed_in()?; - Ok((format!("{name}#{tag}"), client.champ_select()?)) - }) + /// The signed-in Riot ID and its live pick, independent of slow Match history imports. + /// `Err` means the read failed: keep what is shown. `Ok(None)` means no Arena champ select + /// is running. + pub fn champ_select(&self) -> Result, crate::ClientError> { + self.champ_select_with(&self.client_snapshot()) + } + + /// The live pick from a client read already made for this wake. + pub fn champ_select_with( + &self, + snapshot: &ClientSnapshot, + ) -> Result, crate::ClientError> { + let flow = match &snapshot.gameflow { + Ok(flow) => flow, + Err(crate::ClientError::Absent) => return Ok(None), + Err(error) => return Err(error.clone()), + }; + if !flow.is_arena_champ_select() { + return Ok(None); + } + let (name, tag) = match &snapshot.signed_in { + Ok(id) => id, + Err(crate::ClientError::Absent) => return Ok(None), + Err(error) => return Err(error.clone()), + }; + let Some(client) = &self.client else { + return Ok(None); + }; + Ok(Some((riot_id(name, tag), client.champ_select()?))) } /// 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) -> bool { + /// events cause try it only once its time has come. The event says whether only the live + /// selection needs another read. + pub fn wait_for_client(&self) -> ClientEvent { let timeout = if self.follow().pending.is_empty() { WAIT_OTHERWISE } else { WAIT_WHILE_PENDING }; match &self.client { - Some(client) => client.wait_for_selection_event(timeout), + Some(client) => client.wait_for_event(timeout), None => { thread::sleep(timeout); - false + ClientEvent::Other } } } @@ -342,7 +393,7 @@ impl Tracker { }; let result = match (signed_in, updating) { (Some(id), _) => self.adopt(&id, on_progress), - (None, Some(account)) => self.update(&riot_id(&account), on_progress), + (None, Some(account)) => self.update(&account_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)), @@ -355,7 +406,7 @@ impl Tracker { /// 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)) + last.map(|a| account_riot_id(&a)) .or_else(|| self.follow().fallback.clone()) } @@ -368,10 +419,10 @@ impl Tracker { /// adds a Match ends the waits for the games the client gave no id for. fn update( &self, - riot_id: &str, + account_id: &str, on_progress: &mut dyn FnMut(SyncProgress), ) -> Result { - match self.sync(riot_id, on_progress) { + match self.sync(account_id, on_progress) { Ok(report) => { if report.added > 0 { self.follow().pending.retain(|p| p.game_id.is_some()); @@ -386,15 +437,15 @@ impl Tracker { /// active one is the stored Account with that Riot ID, if any: never the previous Account. fn adopt( &self, - riot_id: &str, + account_id: &str, on_progress: &mut dyn FnMut(SyncProgress), ) -> Result { - let result = self.update(riot_id, on_progress); + let result = self.update(account_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)) + .find(|a| same_riot_id(&account_riot_id(a), account_id)) }), }; if let Some(account) = &account @@ -404,7 +455,7 @@ impl Tracker { } let mut follow = self.follow(); follow.updating = account; - follow.adopted = result.is_ok().then(|| riot_id.into()); + follow.adopted = result.is_ok().then(|| account_id.into()); follow.adopt_retry_after_ms = follow.adopt_retry_after_ms.filter(|_| result.is_err()); result } @@ -421,7 +472,7 @@ impl Tracker { 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); + let added = self.update(&account_riot_id(account), on_progress); return (added.map_or(0, |report| report.added), false); }; match self.fetch_and_store(&account.puuid, &match_id) { diff --git a/crates/core/src/league_client.rs b/crates/core/src/league_client.rs index b762068..e7f0702 100644 --- a/crates/core/src/league_client.rs +++ b/crates/core/src/league_client.rs @@ -17,7 +17,8 @@ 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::champ_select::{ANVIL_EVENT, ChampSelectLists, DISABLED_EVENT, PICKABLE_EVENT}; +use crate::client::{ClientError, ClientEvent, GameClientSource, GamePhase, Gameflow}; use crate::riot::encode; /// Riot's published root certificate: the client's certificate is signed by it, and it is @@ -27,15 +28,19 @@ 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 FAVORITES: &str = "/lol-lobby-team-builder/champ-select/v1/crowd-favorte-champion-list"; +const SESSION: &str = "/lol-champ-select/v1/session"; +const PICKABLE: &str = "/lol-champ-select/v1/pickable-champion-ids"; +const DISABLED: &str = "/lol-champ-select/v1/disabled-champion-ids"; +/// The client calls the five anvil champions "crowd favorites" and spells it "favorte" here. +const ANVIL_CHAMPIONS: &str = "/lol-lobby-team-builder/champ-select/v1/crowd-favorte-champion-list"; +const SESSION_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_session"; const TOPICS: &[&str] = &[ "OnJsonApiEvent_lol-gameflow_v1_session", "OnJsonApiEvent_lol-summoner_v1_current-summoner", - "OnJsonApiEvent_lol-champ-select_v1_session", - "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids", - "OnJsonApiEvent_lol-champ-select_v1_disabled-champion-ids", - "OnJsonApiEvent_lol-champions_v1_owned-champions-minimal", - "OnJsonApiEvent_lol-lobby-team-builder_champ-select_v1_crowd-favorite-champion-list", + SESSION_EVENT, + PICKABLE_EVENT, + DISABLED_EVENT, + ANVIL_EVENT, ]; /// The local League client's API (unofficial, read-only). Deliberately no `Debug`: it handles @@ -47,13 +52,14 @@ pub struct LeagueClient { /// configuration is downloaded once per track. tracks: Mutex)>>, events: Mutex>, - pool: Mutex>, + champion_lists: Mutex, } -struct ChampionPool { - available: std::collections::HashSet, - favorites: Option>, - next_favorites_read: Instant, +/// The champion lists of the current draft and the latest session the client sent as an event. +#[derive(Default)] +struct ChampSelectCache { + lists: Option, + session: Option, } struct Events(WebSocket>); @@ -94,7 +100,7 @@ impl LeagueClient { agent, tracks: Mutex::default(), events: Mutex::default(), - pool: Mutex::default(), + champion_lists: Mutex::default(), } } @@ -169,39 +175,35 @@ impl GameClientSource for LeagueClient { fn gameflow(&self) -> Result { let (status, body) = self.get("/lol-gameflow/v1/session")?; let flow = decode_gameflow(status, &body)?; - if !flow.arena || flow.phase != GamePhase::ChampSelect { - *lock(&self.pool) = None; + if !flow.is_arena_champ_select() { + *lock(&self.champion_lists) = ChampSelectCache::default(); } Ok(flow) } fn champ_select(&self) -> Result { - let session = self.get_ok("/lol-champ-select/v1/session")?; - let mut pool = lock(&self.pool); - if pool.is_none() { - let available = crate::ChampSelect::available_champions( - &self.get_ok("/lol-champ-select/v1/pickable-champion-ids")?, - &self.get_ok("/lol-champ-select/v1/disabled-champion-ids")?, - &self.get_ok("/lol-champions/v1/owned-champions-minimal")?, - )?; - *pool = Some(ChampionPool { - available, - favorites: None, - next_favorites_read: Instant::now(), - }); + let session = { + let mut cache = lock(&self.champion_lists); + cache.session.take() + }; + let session = match session { + Some(session) => session, + None => parse(&self.get_ok(SESSION)?)?, + }; + let mut cache = lock(&self.champion_lists); + if cache.lists.is_none() { + let pickable = self.get_ok(PICKABLE)?; + let disabled = self.get_ok(DISABLED)?; + // The anvil list is a bonus: a failed read leaves it empty until an event delivers it. + let anvil = self.get_ok(ANVIL_CHAMPIONS).ok(); + cache.lists = Some(ChampSelectLists::fetch( + &pickable, + &disabled, + anvil.as_deref(), + )?); } - let pool = pool.as_mut().unwrap(); - if pool.favorites.as_ref().is_none_or(Vec::is_empty) - && Instant::now() >= pool.next_favorites_read - { - // The GET spells it "favorte"; the event spells it "favorite". - pool.favorites = self - .get_ok(FAVORITES) - .ok() - .and_then(|s| serde_json::from_str(&s).ok()); - pool.next_favorites_read = Instant::now() + Duration::from_secs(1); - } - crate::ChampSelect::from_session(&session, pool.available.clone(), pool.favorites.clone()) + let lists = cache.lists.as_ref().expect("set just above"); + crate::ChampSelect::from_session(&session, lists.pickable(), lists.anvil().to_vec()) } fn official_progress(&self, track_name: &str) -> Result, ClientError> { @@ -228,24 +230,21 @@ impl GameClientSource for LeagueClient { decode_counter(&body, counter_id.as_deref()) } - fn wait_for_change(&self, timeout: Duration) { - self.wait_for_selection_event(timeout); - } - - fn wait_for_selection_event(&self, timeout: Duration) -> bool { + fn wait_for_event(&self, timeout: Duration) -> ClientEvent { let started = Instant::now(); let mut events = lock(&self.events); if events.is_none() { - *lock(&self.pool) = None; + // A reconnection may follow a client restart: the lists belong to the previous one. + *lock(&self.champion_lists) = ChampSelectCache::default(); *events = self.connect(); // Re-read the snapshot after subscribing. if events.is_some() { - return false; + return ClientEvent::Other; } } let Some(connection) = events.as_mut() else { thread::sleep(timeout.min(TIMEOUT)); - return false; + return ClientEvent::Other; }; // Right after subscribing, the client sends one empty text frame per subscription // (observed on patch 16.22): they and pings are not changes. @@ -259,13 +258,10 @@ impl GameClientSource for LeagueClient { .and_then(|()| connection.0.read()); match read { Ok(Message::Text(text)) if !text.is_empty() => { - let topic = text.split('"').nth(1).unwrap_or_default(); - let session = topic == "OnJsonApiEvent_lol-champ-select_v1_session"; - if !session { - *lock(&self.pool) = None; - } - return topic.starts_with("OnJsonApiEvent_lol-champ-select_") - || topic.ends_with("_crowd-favorite-champion-list"); + let Some((topic, data)) = decode_event(&text) else { + continue; + }; + return self.apply_event(&topic, data); } Ok(Message::Close(_)) => *events = None, Ok(_) => continue, @@ -273,7 +269,30 @@ impl GameClientSource for LeagueClient { if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {} Err(_) => *events = None, } - return false; + return ClientEvent::Other; + } + } +} + +impl LeagueClient { + /// Applies one event to the cache, touching only the list it concerns. + fn apply_event(&self, topic: &str, data: Value) -> ClientEvent { + match topic { + SESSION_EVENT => { + let mut cache = lock(&self.champion_lists); + if data.is_object() { + cache.session = Some(data); + } + ClientEvent::Selection + } + PICKABLE_EVENT | DISABLED_EVENT | ANVIL_EVENT => { + let mut cache = lock(&self.champion_lists); + if let Some(lists) = cache.lists.as_mut() { + lists.apply_event(topic, &data); + } + ClientEvent::Selection + } + _ => ClientEvent::Other, } } } @@ -339,6 +358,13 @@ pub(crate) fn parse(body: &str) -> Result { .map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}"))) } +/// Topic and data of a WebSocket event frame, `[8, "topic", data]`. +fn decode_event(text: &str) -> Option<(String, Value)> { + let frame = parse(text).ok()?; + let topic = frame.get(1)?.as_str()?.to_owned(); + Some((topic, frame.get(2).cloned().unwrap_or(Value::Null))) +} + 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()); @@ -350,7 +376,7 @@ fn decode_signed_in(body: &str) -> Result<(String, String), ClientError> { /// 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 { +pub fn decode_gameflow(status: u16, body: &str) -> Result { match status { 404 => Ok(Gameflow::default()), 200 => { @@ -606,6 +632,60 @@ mod tests { assert_eq!(decode_counter("{}", Some(counter)), Ok(None)); } + #[test] + fn reads_the_topic_and_data_of_an_event_frame() { + let frame = r#"[8,"OnJsonApiEvent_lol-champ-select_v1_session",{"localPlayerCellId":16}]"#; + let (topic, data) = decode_event(frame).unwrap(); + assert_eq!(topic, SESSION_EVENT); + assert_eq!(data["localPlayerCellId"], 16); + assert!(decode_event("not json").is_none()); + assert!(decode_event("[]").is_none()); + } + + #[test] + fn events_update_only_the_list_they_concern() { + use serde_json::json; + use std::collections::HashSet; + + let client = LeagueClient::in_dir(PathBuf::new()); + *lock(&client.champion_lists) = ChampSelectCache { + lists: Some(ChampSelectLists::fetch("[1,2]", "[2]", Some("[9]")).unwrap()), + session: None, + }; + // A gameflow event leaves the champion lists alone; the old code cleared them all. + assert_eq!( + client.apply_event("OnJsonApiEvent_lol-gameflow_v1_session", json!({})), + ClientEvent::Other + ); + { + let cache = lock(&client.champion_lists); + let lists = cache.lists.as_ref().unwrap(); + assert_eq!(&*lists.pickable(), &HashSet::from([1])); + assert_eq!(lists.anvil(), [9]); + } + assert_eq!( + client.apply_event(PICKABLE_EVENT, json!([1, 3])), + ClientEvent::Selection + ); + assert_eq!( + &*lock(&client.champion_lists) + .lists + .as_ref() + .unwrap() + .pickable(), + &HashSet::from([1, 3]) + ); + // A session event is kept for the next read instead of a GET. + assert_eq!( + client.apply_event(SESSION_EVENT, json!({"localPlayerCellId": 16})), + ClientEvent::Selection + ); + assert_eq!( + lock(&client.champion_lists).session, + Some(json!({"localPlayerCellId": 16})) + ); + } + #[test] fn without_a_lockfile_the_client_is_absent() { let dir = tempfile::tempdir().unwrap(); @@ -614,7 +694,10 @@ mod tests { 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_eq!( + client.wait_for_event(Duration::from_millis(50)), + ClientEvent::Other + ); 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 df8f615..98333a0 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -16,12 +16,14 @@ mod tracker; pub use champ_select::ChampSelect; pub use champion_search::ChampionSearch; pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon}; -pub use client::{ClientError, GameClientSource, GamePhase, Gameflow}; +pub use client::{ClientError, ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow}; pub use config::{Config, Preferences, ThemePreference, 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 follow::{ + MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem, riot_id, same_riot_id, +}; +pub use league_client::{LeagueClient, decode_gameflow}; pub use model::{Account, Format, Match, SyncProgress, SyncReport}; pub use riot::RiotApi; pub use seasons::{Season, default_seasons, load_seasons}; diff --git a/crates/core/tests/common/mod.rs b/crates/core/tests/common/mod.rs index a528df5..39b6010 100644 --- a/crates/core/tests/common/mod.rs +++ b/crates/core/tests/common/mod.rs @@ -10,8 +10,9 @@ 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, + Account, ChampSelect, Champion, ChampionCatalog, ChampionSource, ClientError, ClientEvent, + Date, GameClientSource, GamePhase, Gameflow, MatchHistorySource, Season, SourceError, Tracker, + decode_gameflow, }; use serde_json::Value; @@ -569,7 +570,21 @@ struct ClientState { gameflow: Gameflow, tracks: HashMap, waits: Vec, - selection: Option, + /// The raw bodies the client answers for the current draft. + champ_select: Option, + /// A raw gameflow body, replayed through the same parser as the live client. + raw_gameflow: Option, + gameflow_error: Option, + champ_select_error: Option, +} + +/// The raw client responses of a draft, replayed through the same parsing as the live client. +#[derive(Clone)] +pub struct RawChampSelect { + pub pickable: String, + pub disabled: String, + pub anvil: String, + pub session: String, } impl FakeClient { @@ -622,6 +637,7 @@ impl FakeClient { /// `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.raw_gameflow = None; state.gameflow = Gameflow { phase: GamePhase::from_client(phase), arena, @@ -629,13 +645,27 @@ impl FakeClient { }; } + /// Replays a captured gameflow body through the live client's parser. + pub fn set_gameflow(&self, body: &str) { + self.state.lock().unwrap().raw_gameflow = Some(body.into()); + } + /// 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_selection(&self, value: arena_tracker_core::ChampSelect) { - self.state.lock().unwrap().selection = Some(value); + pub fn set_champ_select(&self, raw: RawChampSelect) { + self.state.lock().unwrap().champ_select = Some(raw); + } + + /// The next gameflow or champ select read fails with this, until cleared. + pub fn fail_gameflow(&self, error: Option) { + self.state.lock().unwrap().gameflow_error = error; + } + + pub fn fail_champ_select(&self, error: Option) { + self.state.lock().unwrap().champ_select_error = error; } pub fn set_track(&self, name: &str, value: u32) { @@ -661,16 +691,27 @@ impl GameClientSource for FakeClient { fn gameflow(&self) -> Result { let state = self.state.lock().unwrap(); state.signed_in.as_ref().ok_or(ClientError::Absent)?; - Ok(state.gameflow.clone()) + if let Some(error) = &state.gameflow_error { + return Err(error.clone()); + } + match &state.raw_gameflow { + Some(body) => decode_gameflow(200, body), + None => Ok(state.gameflow.clone()), + } } - fn champ_select(&self) -> Result { - self.state - .lock() - .unwrap() - .selection - .clone() - .ok_or(ClientError::Absent) + fn champ_select(&self) -> Result { + let state = self.state.lock().unwrap(); + if let Some(error) = &state.champ_select_error { + return Err(error.clone()); + } + let raw = state.champ_select.as_ref().ok_or(ClientError::Absent)?; + let session = serde_json::from_str(&raw.session) + .map_err(|error| ClientError::Other(error.to_string()))?; + let pickable = ChampSelect::pickable_champions(&raw.pickable, &raw.disabled)?; + let anvil = serde_json::from_str(&raw.anvil) + .map_err(|error| ClientError::Other(error.to_string()))?; + ChampSelect::from_session(&session, pickable, anvil) } fn official_progress(&self, track_name: &str) -> Result, ClientError> { @@ -679,7 +720,8 @@ impl GameClientSource for FakeClient { Ok(state.tracks.get(track_name).copied()) } - fn wait_for_change(&self, timeout: Duration) { + fn wait_for_event(&self, timeout: Duration) -> ClientEvent { self.state.lock().unwrap().waits.push(timeout); + ClientEvent::Other } } diff --git a/crates/core/tests/follow.rs b/crates/core/tests/follow.rs index 6af9682..ab257f7 100644 --- a/crates/core/tests/follow.rs +++ b/crates/core/tests/follow.rs @@ -7,12 +7,12 @@ 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, + Account, ClientError, 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, + FakeClient, FakeHistory, PlayedMatch, RawChampSelect, S2, S2_TRACK, SELF_PUUID, at, date, + payload, payloads, played_by, played_match, recorded_account, run, seasons, }; const OTHER_PUUID: &str = "fixture-puuid-other"; @@ -1026,7 +1026,7 @@ fn banners_point_to_the_parametres_screen_and_never_to_a_missing_field() { #[test] fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge() { - use arena_tracker_core::{ChampSelect, ChampionState}; + use arena_tracker_core::ChampionState; use serde_json::Value; let capture: Value = serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap(); @@ -1034,24 +1034,21 @@ fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge( &[12, 16, 25, 50, 103, 233].map(|id| played_match(id, if id == 16 { 1 } else { 4 }, now())), ); let tracker = world.tracker(); - let read = |frame: usize| { - ChampSelect::from_session( - &capture["sessions"][frame].to_string(), - ChampSelect::available_champions( - &capture["pickableChampionIds"].to_string(), - &capture["disabledChampionIds"].to_string(), - &capture["ownedChampionsMinimal"].to_string(), - ) - .unwrap(), - Some(serde_json::from_value(capture["crowdFavoriteChampionIds"].clone()).unwrap()), - ) - .unwrap() + // The fake replays the captured raw responses: `Tracker` parses them as it does the client's. + let set_frame = |frame: usize| { + world.client.set_champ_select(RawChampSelect { + pickable: capture["pickableChampionIds"].to_string(), + disabled: capture["disabledChampionIds"].to_string(), + anvil: capture["crowdFavoriteChampionIds"].to_string(), + session: capture["sessions"][frame].to_string(), + }); }; - world.client.set_selection(read(0)); + set_frame(0); world.client.set_phase("ChampSelect", false); round(&tracker); - assert!(tracker.champ_select().is_none()); - world.client.set_phase("ChampSelect", true); + assert_eq!(tracker.champ_select(), Ok(None)); + // The captured gameflow body goes through the live client's parser too. + world.client.set_gameflow(&capture["gameflow"].to_string()); let rows = tracker .statistics( SELF_PUUID, @@ -1073,14 +1070,11 @@ fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge( (3, Some((16, ChampionState::Completed)), vec![103, 233]), (4, Some((16, ChampionState::Completed)), vec![103, 233]), ] { - world.client.set_selection(read(frame)); + set_frame(frame); round(&tracker); let (account, pick) = tracker.champ_select().unwrap().unwrap(); assert_eq!(account, "Joueur#EUW"); - assert_eq!( - pick.crowd_favorites.as_deref(), - Some([233, 64, 5, 16, 68].as_slice()) - ); + assert_eq!(pick.anvil_champions, [233, 64, 5, 16, 68]); assert_eq!( pick.current_row(&rows) .map(|r| (r.champion.id, r.attempts, r.state)), @@ -1096,5 +1090,48 @@ fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge( } world.client.set_phase("InProgress", true); round(&tracker); - assert!(tracker.champ_select().is_none()); + assert_eq!(tracker.champ_select(), Ok(None)); +} + +#[test] +fn a_failed_champ_select_read_keeps_the_pick_until_the_draft_really_ends() { + use serde_json::Value; + let capture: Value = + serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap(); + let world = World::new(&[]); + let tracker = world.tracker(); + world.client.set_champ_select(RawChampSelect { + pickable: capture["pickableChampionIds"].to_string(), + disabled: capture["disabledChampionIds"].to_string(), + anvil: capture["crowdFavoriteChampionIds"].to_string(), + session: capture["sessions"][0].to_string(), + }); + world.client.set_gameflow(&capture["gameflow"].to_string()); + let shown = tracker.champ_select().unwrap(); + assert!(shown.is_some()); + + // A failed gameflow or session request is not an answer that the draft is over. + world + .client + .fail_gameflow(Some(ClientError::Other("HTTP 500".into()))); + assert_eq!( + tracker.champ_select(), + Err(ClientError::Other("HTTP 500".into())) + ); + world.client.fail_gameflow(None); + world + .client + .fail_champ_select(Some(ClientError::Other("HTTP 500".into()))); + assert_eq!( + tracker.champ_select(), + Err(ClientError::Other("HTTP 500".into())) + ); + world.client.fail_champ_select(None); + assert_eq!(tracker.champ_select().unwrap(), shown); + + // Leaving champ select, or the client going away, does end it. + world.client.set_phase("InProgress", true); + assert_eq!(tracker.champ_select(), Ok(None)); + world.client.sign_out(); + assert_eq!(tracker.champ_select(), Ok(None)); } -- 2.54.0 From cf15eeeb8f22e136c02385ab23eb657ec6c94759 Mon Sep 17 00:00:00 2001 From: Nessar Date: Thu, 19 Nov 2026 20:32:46 +0100 Subject: [PATCH 5/6] Decode client events from their data and keep the draft on a timeout (#13) Event frames are [8, topic, {data, eventType, uri}]; decode_event returned the whole envelope, so the cached session had no localPlayerCellId and the pickable/disabled/anvil lists ignored the update until a fresh GET. It now returns the envelope's data (null on Delete, which the cache already ignores). The tests use enveloped frames, including one from raw text to the cached state. transport_error mapped every non-TLS error to Absent, so one request timing out while the client loads the draft sent the page back to statistics. A timeout or an I/O error other than connection refused is now Other, which champ_select_with treats as transient. Other readers of ClientError only use .ok(), so nothing else changes. Co-Authored-By: Claude Opus 5.5 --- crates/core/src/league_client.rs | 88 ++++++++++++++++++++++++++++++-- 1 file changed, 83 insertions(+), 5 deletions(-) diff --git a/crates/core/src/league_client.rs b/crates/core/src/league_client.rs index e7f0702..0e918d0 100644 --- a/crates/core/src/league_client.rs +++ b/crates/core/src/league_client.rs @@ -318,12 +318,17 @@ fn tls_config() -> Result { ) } -/// A rejected certificate is worth telling apart from a client that is simply not there. +/// A rejected certificate, a timeout or a dropped connection is worth telling apart from a +/// client that is simply not there (nothing listens): the first ones say nothing about the draft. 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}")) } + ureq::Error::Timeout(_) => ClientError::Other(format!("Le client ne répond pas : {e}")), + ureq::Error::Io(ref io) if io.kind() != ErrorKind::ConnectionRefused => { + ClientError::Other(format!("Échange avec le client interrompu : {e}")) + } _ => ClientError::Absent, } } @@ -358,11 +363,14 @@ pub(crate) fn parse(body: &str) -> Result { .map_err(|e| ClientError::Other(format!("Réponse du client illisible : {e}"))) } -/// Topic and data of a WebSocket event frame, `[8, "topic", data]`. +/// Topic and resource of a WebSocket event frame, +/// `[8, "topic", {"data": resource, "eventType": ..., "uri": ...}]`; the resource is null on a +/// `Delete`. fn decode_event(text: &str) -> Option<(String, Value)> { let frame = parse(text).ok()?; let topic = frame.get(1)?.as_str()?.to_owned(); - Some((topic, frame.get(2).cloned().unwrap_or(Value::Null))) + let data = frame.pointer("/2/data").cloned().unwrap_or(Value::Null); + Some((topic, data)) } fn decode_signed_in(body: &str) -> Result<(String, String), ClientError> { @@ -634,14 +642,84 @@ mod tests { #[test] fn reads_the_topic_and_data_of_an_event_frame() { - let frame = r#"[8,"OnJsonApiEvent_lol-champ-select_v1_session",{"localPlayerCellId":16}]"#; - let (topic, data) = decode_event(frame).unwrap(); + let (topic, data) = decode_event(&frame( + SESSION_EVENT, + "Update", + r#"{"localPlayerCellId":16}"#, + )) + .unwrap(); assert_eq!(topic, SESSION_EVENT); assert_eq!(data["localPlayerCellId"], 16); + let (_, data) = decode_event(&frame(SESSION_EVENT, "Delete", "null")).unwrap(); + assert!(data.is_null()); assert!(decode_event("not json").is_none()); assert!(decode_event("[]").is_none()); } + /// A frame as the client sends it: the resource sits in the envelope's `data`. + fn frame(topic: &str, event_type: &str, data: &str) -> String { + format!(r#"[8,"{topic}",{{"data":{data},"eventType":"{event_type}","uri":"/x"}}]"#) + } + + #[test] + fn a_raw_event_frame_updates_the_cached_session_and_lists() { + use serde_json::json; + use std::collections::HashSet; + + let client = LeagueClient::in_dir(PathBuf::new()); + *lock(&client.champion_lists) = ChampSelectCache { + lists: Some(ChampSelectLists::fetch("[1,2]", "[]", Some("[]")).unwrap()), + session: None, + }; + let apply = |topic, event_type, data: &str| { + let (topic, data) = decode_event(&frame(topic, event_type, data)).unwrap(); + client.apply_event(&topic, data) + }; + assert_eq!( + apply(SESSION_EVENT, "Update", r#"{"localPlayerCellId":16}"#), + ClientEvent::Selection + ); + assert_eq!( + apply(ANVIL_EVENT, "Update", "[9,8]"), + ClientEvent::Selection + ); + assert_eq!( + apply(PICKABLE_EVENT, "Update", "[2]"), + ClientEvent::Selection + ); + // A Delete carries no data: it neither wipes nor corrupts what is cached. + assert_eq!( + apply(SESSION_EVENT, "Delete", "null"), + ClientEvent::Selection + ); + assert_eq!(apply(ANVIL_EVENT, "Delete", "null"), ClientEvent::Selection); + assert_eq!( + apply(PICKABLE_EVENT, "Delete", "null"), + ClientEvent::Selection + ); + let cache = lock(&client.champion_lists); + assert_eq!(cache.session, Some(json!({"localPlayerCellId": 16}))); + let lists = cache.lists.as_ref().unwrap(); + assert_eq!(lists.anvil(), [9, 8]); + assert_eq!(&*lists.pickable(), &HashSet::from([2])); + } + + #[test] + fn only_a_client_that_is_gone_is_absent() { + let io = |kind| ureq::Error::Io(std::io::Error::from(kind)); + assert_eq!( + transport_error(io(ErrorKind::ConnectionRefused)), + ClientError::Absent + ); + for transient in [ + ureq::Error::Timeout(ureq::Timeout::Global), + io(ErrorKind::TimedOut), + io(ErrorKind::ConnectionReset), + ] { + assert!(matches!(transport_error(transient), ClientError::Other(_))); + } + } + #[test] fn events_update_only_the_list_they_concern() { use serde_json::json; -- 2.54.0 From 304d958c729609c5ce793356e448fada4ad41ebe Mon Sep 17 00:00:00 2001 From: Nessar Date: Thu, 19 Nov 2026 20:58:09 +0100 Subject: [PATCH 6/6] Fix the final champ select review findings (#13) --- CONTEXT.md | 2 +- crates/app/src/main.rs | 18 ++- crates/app/src/stats_page.rs | 145 ++++++++++-------- crates/app/src/text.rs | 19 +-- crates/app/src/worker.rs | 49 +++--- crates/core/src/champ_select.rs | 247 ++++++++++++++++++++----------- crates/core/src/client.rs | 74 +++++++-- crates/core/src/follow.rs | 25 ++-- crates/core/src/league_client.rs | 220 ++++++++++++++------------- crates/core/src/lib.rs | 5 +- crates/core/tests/common/mod.rs | 79 +++++++--- crates/core/tests/follow.rs | 104 ++++++++----- 12 files changed, 612 insertions(+), 375 deletions(-) diff --git a/CONTEXT.md b/CONTEXT.md index 928d160..5000df9 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -62,7 +62,7 @@ _Avoid_: Crowd favorites, favorites **Pickable**: A champion the local player can still pick in the current Arena champ select: offered by the client, not disabled, and neither banned nor taken by another player. -_Avoid_: Available, owned, remaining +_Avoid_: Available, owned **Official Progress**: The game's own per-Season count of champions it considers completed, used only to cross-check a Challenge. diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 3fd14ec..0f3959d 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -83,10 +83,7 @@ impl RootView { KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)), KeyEvent::Back => {} } - this.form.update(cx, |form, cx| form.reset(window, cx)); - this.screen = Screen::Page; - this.focus.focus(window, cx); - cx.notify(); + this.show_page(window, cx); }); let champ_select = cx.subscribe_in( &page, @@ -94,10 +91,7 @@ impl RootView { |this, _, _: &stats_page::ChampSelectTransition, window, cx| { if this.screen == Screen::Settings { // Champ select takes the window away: do not bring back half-typed edits. - this.form.update(cx, |form, cx| form.reset(window, cx)); - this.screen = Screen::Page; - this.focus.focus(window, cx); - cx.notify(); + this.show_page(window, cx); } }, ); @@ -123,6 +117,14 @@ impl RootView { fn can_refresh(&self, cx: &App) -> bool { self.screen != Screen::Prompt && self.form.read(cx).has_key() && !self.page.read(cx).busy() } + + /// Leaves the key form for the page, discarding half-typed edits. + fn show_page(&mut self, window: &mut Window, cx: &mut Context) { + self.form.update(cx, |form, cx| form.reset(window, cx)); + self.screen = Screen::Page; + self.focus.focus(window, cx); + cx.notify(); + } } impl Render for RootView { diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs index 0aa0c6d..7813334 100644 --- a/crates/app/src/stats_page.rs +++ b/crates/app/src/stats_page.rs @@ -6,7 +6,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use arena_tracker_core::{ Account, ChallengeSummary, ChampSelect, ChampionRow, ChampionSearch, Charts, Format, ProgressCheck, Scope, SeasonScope, StateFilter, Statistics, Status, SyncProgress, Tracker, - UpdateProblem, same_riot_id, + UpdateProblem, account_riot_id, same_riot_id, }; use gpui_kit::base::async_util::{Receiver, Sender}; use gpui_kit::component::StyledExt as _; @@ -20,8 +20,8 @@ use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use crate::champion_table::ChampionTable; -use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, riot_id, sync_line}; -use crate::worker::{Msg, RefreshGate, spawn_refresh, spawn_statistics}; +use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, sync_line}; +use crate::worker::{LiveChampSelect, Msg, RefreshGate, spawn_refresh, spawn_statistics}; const ALL_SEASONS: &str = "Toutes les Saisons"; const ALL_FORMATS: &str = "Tous les Formats"; @@ -32,6 +32,12 @@ const CHARTS_HEIGHT: f32 = 206.; /// While an import runs, the page is recomputed at most this often. const RELOAD_EVERY: Duration = Duration::from_secs(1); +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64) +} + /// Hides page parts for issue #27 measurements only with `--features profile`. #[inline] pub fn shown(part: &str) -> bool { @@ -86,13 +92,17 @@ pub struct StatsPage { notice: Option, /// As of the last follower round or refresh. status: Status, - selection: crate::worker::Selection, + champ_select: LiveChampSelect, + /// The Account of `champ_select`, resolved when its Riot ID changes. + champ_select_account: Option, + /// The Riot ID `champ_select_account` was resolved for. + champ_select_riot_id: Option, /// The current champion's cells, prepared when the pick or the statistics change. current_labels: Vec, /// What the panel says when the current champion has no statistics row. current_fallback: SharedString, /// What the panel says while the statistics are missing. - selection_notice: SharedString, + champ_select_notice: SharedString, anvil_labels: Vec, accounts: Vec, last_active: Option, @@ -162,10 +172,7 @@ impl StatsPage { .map(|s| s.name.into()) .chain([ALL_SEASONS.into()]) .collect(); - let now_ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_millis() as i64); - let current_season = tracker.current_season(now_ms).map(|s| s.name); + let current_season = tracker.current_season(now_ms()).map(|s| s.name); let season = current_season .clone() .map_or(SeasonScope::AllSeasons, SeasonScope::Season); @@ -254,10 +261,12 @@ impl StatsPage { tracker, tx, notice, - selection: None, + champ_select: None, + champ_select_account: None, + champ_select_riot_id: None, current_labels: Vec::new(), current_fallback: SharedString::default(), - selection_notice: SharedString::default(), + champ_select_notice: SharedString::default(), anvil_labels: Vec::new(), accounts: Vec::new(), last_active: None, @@ -354,12 +363,12 @@ impl StatsPage { } } Msg::Champions => self.reload_in_background(window, cx), - Msg::Selection(selection) => { - if self.selection == selection { + Msg::ChampSelect(champ_select) => { + if self.champ_select == champ_select { return; } - let previous = self.selection.as_ref(); - let next = selection.as_ref(); + let previous = self.champ_select.as_ref(); + let next = champ_select.as_ref(); let changed_page = previous.is_some() != next.is_some(); let switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id); let pool_changed = match (previous, next) { @@ -367,8 +376,11 @@ impl StatsPage { (None, None) => false, _ => true, }; - self.selection = selection; + self.champ_select = champ_select; if switch { + // The Account belongs to the signed-in Riot ID: resolve it once, not on every + // statistics preparation. + self.champ_select_riot_id = None; self.stats_generation += 1; self.stats = None; self.stats_error = None; @@ -382,9 +394,8 @@ impl StatsPage { if pool_changed || switch { self.refresh_table(cx); } - // A hover or lock-in changes neither the Account nor the pool: redraw the page - // so the current-pick panel follows, even when the table is untouched. - cx.notify(); + // A hover or lock-in changes neither the Account nor the pool: the page is + // redrawn by the notification at the end of this message. } Msg::Round { status, reload } => { // A follower round that changes nothing shown must not rebuild the page (they keep coming). @@ -473,11 +484,15 @@ impl StatsPage { .iter() .map(|a| AccountItem { puuid: a.puuid.clone(), - title: riot_id(a).into(), + title: account_riot_id(a).into(), }) .collect(); let changed = items != self.account_items; self.account_items = items.clone(); + if changed { + // The live champ select's Account may now be in the list: resolve it again. + self.champ_select_riot_id = None; + } let viewed = self.viewed().map(|a| a.puuid.clone()); self.account_select.update(cx, |select, cx| { if changed { @@ -505,20 +520,9 @@ impl StatsPage { if computing { self.stats_generation += 1; } - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default(); - self.current_season = self - .tracker - .current_season(now.as_millis() as i64) - .map(|s| s.name); - let (id, _) = self.selection.as_ref()?; - return self - .accounts - .iter() - .find(|a| same_riot_id(&riot_id(a), id)) - .filter(|_| self.current_season.is_some()) - .map(|a| a.puuid.clone()); + self.current_season = self.tracker.current_season(now_ms()).map(|s| s.name); + let puuid = self.champ_select_account()?; + return self.current_season.is_some().then_some(puuid); } if matches!(self.season, SeasonScope::AllSeasons) && !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed) @@ -541,6 +545,21 @@ impl StatsPage { viewed } + /// The Account of the live champ select. Resolved when the signed-in Riot ID changes (or the + /// Accounts do), so preparing statistics builds no Riot ID per Account every time. + fn champ_select_account(&mut self) -> Option { + let id = self.champ_select.as_ref().map(|(id, _)| id.as_str())?; + if self.champ_select_riot_id.as_deref() != Some(id) { + self.champ_select_riot_id = Some(id.into()); + self.champ_select_account = self + .accounts + .iter() + .find(|a| same_riot_id(&account_riot_id(a), id)) + .map(|a| a.puuid.clone()); + } + self.champ_select_account.clone() + } + fn statistics_scope(&self) -> Scope { if self.in_champ_select() && let Some(season) = &self.current_season @@ -633,11 +652,11 @@ impl StatsPage { } fn in_champ_select(&self) -> bool { - self.selection.is_some() + self.champ_select.is_some() } fn live_champ_select(&self) -> Option<&ChampSelect> { - self.selection.as_ref().map(|(_, pick)| pick) + self.champ_select.as_ref().map(|(_, pick)| pick) } fn update_picks(&mut self) { @@ -667,18 +686,25 @@ impl StatsPage { }) .unwrap_or_default(); anvil_labels.sort(); - let current_fallback = match pick { - Some(s) => match s.current { - Some(id) if current_labels.is_empty() => { - let row = rows.iter().find(|r| r.champion.id == id); - format!("{} · Statistiques indisponibles", champion_label(row, id)).into() - } - Some(_) => SharedString::default(), - None => "Aucun champion sélectionné".into(), - }, - None => "Sélection indisponible dans le client.".into(), - }; - let selection_notice = match (&self.stats_error, self.stats.is_some()) { + // Statistics are missing rather than absent when they are still on their way. + let loading = self.stats.is_none() + && self.stats_error.is_none() + && self.current_season.is_some() + && self.status.updating.is_some(); + let current_fallback = pick.map_or_else(SharedString::default, |s| match s.current { + Some(id) if current_labels.is_empty() => { + let row = rows.iter().find(|r| r.champion.id == id); + let note = if loading { + "Chargement des statistiques…" + } else { + "Statistiques indisponibles" + }; + format!("{} · {note}", champion_label(row, id)).into() + } + Some(_) => SharedString::default(), + None => "Aucun champion sélectionné".into(), + }); + let champ_select_notice = match (&self.stats_error, self.stats.is_some()) { (Some(error), _) => error.clone().into(), (None, true) => SharedString::default(), (None, false) if self.current_season.is_none() => "Aucune Saison en cours".into(), @@ -688,13 +714,13 @@ impl StatsPage { self.current_labels = current_labels; self.anvil_labels = anvil_labels; self.current_fallback = current_fallback; - self.selection_notice = selection_notice; + self.champ_select_notice = champ_select_notice; } fn refresh_table(&mut self, cx: &mut Context) { let rows = self.stats.iter().flat_map(|s| &s.rows); let rows = rows - .filter(|row| match &self.selection { + .filter(|row| match &self.champ_select { Some((_, pick)) => pick.remaining(row), None => self.filter.keeps(row) && self.search.matches(&row.champion), }) @@ -709,16 +735,13 @@ impl StatsPage { fn champ_select_view(&self, cx: &App) -> Div { let border = cx.theme().border; - let mut page = div().v_flex().size_full().p_3().gap_3().child( + let page = div().v_flex().size_full().p_3().gap_3().child( div() .text_xl() .font_weight(FontWeight::SEMIBOLD) .child("Sélection des champions · Arena"), ); - if self.live_champ_select().is_none() { - return page.child("Sélection indisponible dans le client."); - } - page = page.child(match self.current_labels.split_first() { + page.child(match self.current_labels.split_first() { Some((name, labels)) => div() .h_flex() .items_center() @@ -733,8 +756,8 @@ impl StatsPage { .map(|label| div().text_sm().child(label)), ), None => div().child(self.current_fallback.clone()), - }); - page.child( + }) + .child( div() .v_flex() .gap_2() @@ -770,7 +793,7 @@ impl StatsPage { .child("Champions disponibles à valider"), ) .when(self.stats.is_none(), |page| { - page.child(self.selection_notice.clone()) + page.child(self.champ_select_notice.clone()) }) .when(self.stats.is_some(), |page| { page.child(div().flex_1().min_h_0().child(self.table.clone())) @@ -1355,7 +1378,7 @@ mod tests { p.filter = StateFilter::NeverPlayed; p.reload(w, cx); assert!(p.stats.as_ref().unwrap().rows.is_empty()); - p.apply(Msg::Selection(Some(("Alice#EUW".into(), pick))), w, cx); + p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), pick))), w, cx); }) }); cx.condition(&page, |p, _| !p.current_labels.is_empty()) @@ -1376,7 +1399,7 @@ mod tests { let next = ChampSelect::new(None, [39].into(), vec![39]); window.update(|w, cx| { page.update(cx, |p, cx| { - p.apply(Msg::Selection(Some(("Alice#EUW".into(), next))), w, cx); + p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), next))), w, cx); }) }); page.read_with(cx, |p, _| { @@ -1386,7 +1409,7 @@ mod tests { window.update(|w, cx| { page.update(cx, |p, cx| { - p.apply(Msg::Selection(None), w, cx); + p.apply(Msg::ChampSelect(None), w, cx); }) }); cx.condition(&page, |p, _| p.stats.is_some()).await; diff --git a/crates/app/src/text.rs b/crates/app/src/text.rs index 0b99908..5406a56 100644 --- a/crates/app/src/text.rs +++ b/crates/app/src/text.rs @@ -1,6 +1,6 @@ //! French display helpers shared by the page and the table. -use arena_tracker_core::{Account, ChampionState, SyncProgress}; +use arena_tracker_core::{ChampionState, SyncProgress}; /// Fixed decimals with a decimal comma: `1,96`. pub fn decimal(value: f64, digits: usize) -> String { @@ -29,10 +29,6 @@ pub const CLIENT_ABSENT: &str = "Client League of Legends non détecté : affichage des données enregistrées."; const INTERNAL_ERROR: &str = "Mise à jour impossible : erreur interne."; -pub fn riot_id(account: &Account) -> String { - arena_tracker_core::riot_id(&account.game_name, &account.tag_line) -} - /// The discreet line under the Challenge tile. pub fn official_note(official: u32) -> String { format!("Progression officielle : {official}") @@ -88,19 +84,6 @@ mod tests { assert_eq!(state_label(None), ""); } - fn account(name: &str, tag: &str) -> Account { - Account { - puuid: "p".into(), - game_name: name.into(), - tag_line: tag.into(), - } - } - - #[test] - fn riot_ids_join_name_and_tag() { - assert_eq!(riot_id(&account("Joueur", "EUW")), "Joueur#EUW"); - } - #[test] fn official_progress_texts() { assert_eq!(official_note(52), "Progression officielle : 52"); diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs index 80ed6e2..65a4f58 100644 --- a/crates/app/src/worker.rs +++ b/crates/app/src/worker.rs @@ -12,10 +12,10 @@ use arena_tracker_core::{ use gpui_kit::base::async_util::Sender; /// The signed-in Riot ID and its pick, or none outside an Arena champ select. -pub type Selection = Option<(String, ChampSelect)>; +pub type LiveChampSelect = Option<(String, ChampSelect)>; pub enum Msg { - Selection(Selection), + ChampSelect(LiveChampSelect), /// A sync is fetching Matches. Progress(SyncProgress), /// The champion catalog and portraits were refreshed. @@ -113,7 +113,7 @@ fn spawn_guarded(tx: Sender, on_panic: Msg, body: impl FnOnce(&Sender) } /// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds -/// and a live selection subscription. Each wake reads the client once and shares that read with +/// and a live champ select subscription. Each wake reads the client once and shares that read with /// both. `fallback_riot_id` is the configured Riot ID. /// The champion catalog and portraits are fetched on another thread, so a first launch's /// import never waits for them. @@ -132,16 +132,15 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty()); let mut first = true; for () in rounds { - let snapshot = history_latest.lock().unwrap().take(); + // Another wake landed while this one's round ran: its read is newer and already + // queued, so this round has nothing of its own to do. + let Some(snapshot) = history_latest.lock().unwrap().take() else { + continue; + }; let mut progress = |progress| { let _ = tx.try_send(Msg::Progress(progress)); }; - let changed = match snapshot { - Some(snapshot) => { - history.follow_client_with(now_ms(), fallback, &snapshot, &mut progress) - } - None => history.follow_client(now_ms(), fallback, &mut progress), - }; + let changed = history.follow_client_with(now_ms(), fallback, &snapshot, &mut progress); if tx .try_send(Msg::Round { status: history.status(), @@ -157,11 +156,11 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende spawn_guarded(tx, Msg::Crashed, move |tx| { let mut previous = None; let mut snapshot = tracker.client_snapshot(); - let mut share = true; + let mut needs_snapshot = true; while !tx.is_closed() { - // The follower round uses the same read as the live selection: one gameflow request - // per wake, and none for a champ select event. - if share { + // The follower round uses the same read as the live champ select: one gameflow + // request per wake, and none for a champ select event. + if needs_snapshot { *latest.lock().unwrap() = Some(snapshot.clone()); if matches!( wake.try_send(()), @@ -171,24 +170,22 @@ pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sende } } match tracker.champ_select_with(&snapshot) { - Ok(selection) if selection != previous => { - if tx.try_send(Msg::Selection(selection.clone())).is_err() { + Ok(champ_select) if champ_select != previous => { + if tx.try_send(Msg::ChampSelect(champ_select.clone())).is_err() { break; } - previous = selection; + previous = champ_select; } Ok(_) => {} - // A failed read is not the draft ending: keep what the page shows. + // A failed read is not the champ select ending: keep what the page shows. Err(_) => {} } - // A champ select event costs no request while the draft is already known; any other - // event, or a snapshot that predates the draft, needs a fresh read. - share = tracker.wait_for_client() == ClientEvent::Other - || !snapshot - .gameflow - .as_ref() - .is_ok_and(|flow| flow.is_arena_champ_select()); - if share { + // A champ select event costs no request once a read has answered: only a gameflow + // event, or a read that failed, needs a fresh one. The gameflow event that starts + // the champ select is that event. + needs_snapshot = + tracker.wait_for_client() == ClientEvent::Other || snapshot.gameflow.is_err(); + if needs_snapshot { snapshot = tracker.client_snapshot(); } } diff --git a/crates/core/src/champ_select.rs b/crates/core/src/champ_select.rs index 67012c8..179c740 100644 --- a/crates/core/src/champ_select.rs +++ b/crates/core/src/champ_select.rs @@ -1,10 +1,11 @@ //! The local player's pick and the champions offered during an Arena champ select. use std::collections::HashSet; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; use serde_json::Value; -use crate::league_client::parse; +use crate::client::Gameflow; +use crate::league_client::{lock, parse}; use crate::{ChampionRow, ChampionState, ClientError}; pub(crate) const PICKABLE_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids"; @@ -19,10 +20,10 @@ pub struct ChampSelect { /// The five anvil champions; empty when the client reports none. The client calls them /// crowd favorites. pub anvil_champions: Vec, - /// The champions the draft offers, before its bans and the other players' picks. Shared with - /// the client's cache instead of cloned on every session event. + /// The champions the champ select offers, before its bans and the other players' picks. + /// Shared with the client's cache instead of cloned on every session event. pickable: Arc>, - /// Banned or taken by another player in this session. + /// Banned or taken by another player in this champ select. excluded: HashSet, } @@ -46,24 +47,21 @@ fn array(value: &Value) -> Result<&[Value], ClientError> { } fn ids(body: &str) -> Result, ClientError> { - Ok(array(&parse(body)?)? - .iter() - .filter_map(champion_id) - .collect()) + let value = parse(body)?; + let ids = + ids_in(&value).ok_or_else(|| ClientError::Other("Liste de champions illisible".into()))?; + Ok(ids.into_iter().collect()) } -fn ids_from_event(data: &Value) -> Option> { - data.as_array() - .map(|ids| ids.iter().filter_map(champion_id).collect()) -} - -fn ordered_ids(data: &Value) -> Option> { - data.as_array() +/// The champion ids of a list, from a body or from an event's data. +fn ids_in(value: &Value) -> Option> { + value + .as_array() .map(|ids| ids.iter().filter_map(champion_id).collect()) } impl ChampSelect { - /// A selection with nothing banned or taken, for tests and callers with a ready pool. + /// A champ select with nothing banned or taken, for callers with a ready pool. pub fn new(current: Option, pickable: HashSet, anvil_champions: Vec) -> Self { Self { current, @@ -73,19 +71,7 @@ impl ChampSelect { } } - /// The champions the client offers, minus those disabled for this draft. The pickable list - /// is the client's answer to what the player can pick: it already includes free-rotation and - /// rented champions, so ownership is not consulted. - pub fn pickable_champions( - pickable: &str, - disabled: &str, - ) -> Result>, ClientError> { - let pickable = ids(pickable)?; - let disabled = ids(disabled)?; - Ok(Arc::new(pickable.difference(&disabled).copied().collect())) - } - - pub fn from_session( + fn from_session( session: &Value, pickable: Arc>, anvil_champions: Vec, @@ -144,21 +130,98 @@ impl ChampSelect { self.current == Some(id) || (self.pickable.contains(&id) && !self.excluded.contains(&id)) } - /// Whether both selections offer the same champions, whatever the current pick. The shared - /// set makes the common case a pointer comparison. + /// Whether both champ selects offer the same champions, whatever the current pick. The + /// shared set makes the common case a pointer comparison. pub fn same_pickable(&self, other: &Self) -> bool { (Arc::ptr_eq(&self.pickable, &other.pickable) || self.pickable == other.pickable) && self.excluded == other.excluded } - /// A champion still to complete in the Challenge and pickable in this draft. The player's - /// own hovered or locked champion stays in the list while not Completed: they can pick it. + /// A champion still to complete in the Challenge and pickable in this champ select. The + /// player's own hovered or locked champion stays in the list while not Completed: they can + /// pick it. pub fn remaining(&self, row: &ChampionRow) -> bool { row.state.is_some_and(|s| s != ChampionState::Completed) && self.can_pick(row.champion.id) } } -/// The champion lists of a draft: fetched once, then updated from the client's events. +/// The live champ select, read the one way both the real client and the tests read it: the +/// session the client sent as an event, else its answer to a session request, and the champion +/// lists read once per champ select. +#[derive(Default)] +pub struct ChampSelectReader { + lists: Mutex>, + /// The latest session the client sent as an event, taken by the next read. + session: Mutex>, +} + +impl ChampSelectReader { + /// Forgets the champ select: the next read belongs to a new one. + pub(crate) fn reset(&self) { + *lock(&self.lists) = None; + *lock(&self.session) = None; + } + + /// Follows a gameflow read: anything but an Arena champ select ends the cached one, whose + /// lists must not leak into the next. + pub fn reset_unless_arena_champ_select(&self, flow: &Gameflow) { + if !flow.is_arena_champ_select() { + self.reset(); + } + } + + /// Keeps the session the client sent as an event for the next read, which then needs no + /// session request. + pub fn set_session(&self, session: Value) { + if session.is_object() { + *lock(&self.session) = Some(session); + } + } + + /// Reads the live champ select. `session` and `lists` make the requests; they run only when + /// the event session or the champion lists are missing, and never under a lock. + pub fn read( + &self, + session: impl FnOnce() -> Result, + lists: impl FnOnce() -> Result<(String, String, Option), ClientError>, + ) -> Result { + let session = match lock(&self.session).take() { + Some(session) => session, + None => parse(&session()?)?, + }; + if lock(&self.lists).is_none() { + let (pickable, disabled, anvil) = lists()?; + let lists = ChampSelectLists::from_bodies(&pickable, &disabled, anvil.as_deref())?; + *lock(&self.lists) = Some(lists); + } + let lists = lock(&self.lists); + let lists = lists.as_ref().expect("set just above"); + ChampSelect::from_session(&session, lists.pickable(), lists.anvil().to_vec()) + } + + /// Applies the client's pickable list event. + pub(crate) fn set_pickable(&self, data: &Value) { + if let Some(lists) = lock(&self.lists).as_mut() { + lists.set_pickable(data); + } + } + + /// Applies the client's disabled list event. + pub(crate) fn set_disabled(&self, data: &Value) { + if let Some(lists) = lock(&self.lists).as_mut() { + lists.set_disabled(data); + } + } + + /// Applies the client's anvil champions event. + pub(crate) fn set_anvil(&self, data: &Value) { + if let Some(lists) = lock(&self.lists).as_mut() { + lists.set_anvil(data); + } + } +} + +/// The champion lists of a champ select: read once, then updated from the client's events. #[derive(Debug, Default)] pub(crate) struct ChampSelectLists { /// The client's pickable list, before the disabled champions are removed. @@ -170,7 +233,7 @@ pub(crate) struct ChampSelectLists { } impl ChampSelectLists { - pub(crate) fn fetch( + pub(crate) fn from_bodies( pickable: &str, disabled: &str, anvil: Option<&str>, @@ -182,7 +245,7 @@ impl ChampSelectLists { }; if let Some(body) = anvil && let Ok(value) = parse(body) - && let Some(ids) = ordered_ids(&value) + && let Some(ids) = ids_in(&value) { lists.anvil = ids; } @@ -202,31 +265,23 @@ impl ChampSelectLists { &self.anvil } - /// Applies one client event. Returns false when the topic concerns something else; the lists - /// it does not concern are left untouched. - pub(crate) fn apply_event(&mut self, topic: &str, data: &Value) -> bool { - match topic { - PICKABLE_EVENT => { - if let Some(ids) = ids_from_event(data) { - self.offered = ids; - self.rebuild(); - } - true - } - DISABLED_EVENT => { - if let Some(ids) = ids_from_event(data) { - self.disabled = ids; - self.rebuild(); - } - true - } - ANVIL_EVENT => { - if let Some(ids) = ordered_ids(data) { - self.anvil = ids; - } - true - } - _ => false, + fn set_pickable(&mut self, data: &Value) { + if let Some(ids) = ids_in(data) { + self.offered = ids.into_iter().collect(); + self.rebuild(); + } + } + + fn set_disabled(&mut self, data: &Value) { + if let Some(ids) = ids_in(data) { + self.disabled = ids.into_iter().collect(); + self.rebuild(); + } + } + + fn set_anvil(&mut self, data: &Value) { + if let Some(ids) = ids_in(data) { + self.anvil = ids; } } } @@ -236,56 +291,82 @@ mod tests { use super::*; use serde_json::json; - #[test] - fn pickable_excludes_disabled_champions() { - assert_eq!( - &*ChampSelect::pickable_champions("[1,2,3]", "[3]").unwrap(), - &HashSet::from([1, 2]) - ); - } - #[test] fn the_lists_change_only_for_the_events_that_concern_them() { - let mut lists = ChampSelectLists::fetch("[1,2,3]", "[3]", Some("[9,8]")).unwrap(); + let mut lists = ChampSelectLists::from_bodies("[1,2,3]", "[3]", Some("[9,8]")).unwrap(); assert_eq!(&*lists.pickable(), &HashSet::from([1, 2])); assert_eq!(lists.anvil(), [9, 8]); - // A gameflow event used to clear the whole cache, costing three requests again. - assert!(!lists.apply_event( - "OnJsonApiEvent_lol-gameflow_v1_session", - &json!({"phase": "ChampSelect"}) - )); + // A Delete carries no data: it changes nothing. + lists.set_pickable(&Value::Null); + lists.set_anvil(&Value::Null); assert_eq!(&*lists.pickable(), &HashSet::from([1, 2])); assert_eq!(lists.anvil(), [9, 8]); - assert!(lists.apply_event(PICKABLE_EVENT, &json!([1, 4]))); + lists.set_pickable(&json!([1, 4])); assert_eq!(&*lists.pickable(), &HashSet::from([1, 4])); assert_eq!(lists.anvil(), [9, 8]); - assert!(lists.apply_event(DISABLED_EVENT, &json!([1]))); + lists.set_disabled(&json!([1])); assert_eq!(&*lists.pickable(), &HashSet::from([4])); - assert!(lists.apply_event(ANVIL_EVENT, &json!([5, 6]))); + lists.set_anvil(&json!([5, 6])); assert_eq!(lists.anvil(), [5, 6]); } #[test] - fn the_anvil_champions_are_read_once_when_the_draft_starts() { + fn the_anvil_champions_are_read_once_when_the_champ_select_starts() { assert!( - ChampSelectLists::fetch("[]", "[]", None) + ChampSelectLists::from_bodies("[]", "[]", None) .unwrap() .anvil() .is_empty() ); assert_eq!( - ChampSelectLists::fetch("[]", "[]", Some("[1,2]")) + ChampSelectLists::from_bodies("[]", "[]", Some("[1,2]")) .unwrap() .anvil(), [1, 2] ); // A malformed anvil answer only loses the anvil list, not the pickable one. - let lists = ChampSelectLists::fetch("[7]", "[]", Some("not json")).unwrap(); + let lists = ChampSelectLists::from_bodies("[7]", "[]", Some("not json")).unwrap(); assert_eq!(&*lists.pickable(), &HashSet::from([7])); assert!(lists.anvil().is_empty()); } + + #[test] + fn a_read_uses_the_session_of_an_event_and_reads_the_lists_once() { + let reader = ChampSelectReader::default(); + let session = || { + Ok( + r#"{"localPlayerCellId":16,"myTeam":[{"cellId":16,"championId":0, + "championPickIntent":0}],"actions":[], + "bans":{"myTeamBans":[],"theirTeamBans":[]}}"# + .to_string(), + ) + }; + let lists = || { + Ok(( + "[1,2]".to_string(), + "[]".to_string(), + Some("[9]".to_string()), + )) + }; + reader.read(session, lists).unwrap(); + + // A session event replaces the request; the lists stay cached. + reader.set_session(json!({ + "localPlayerCellId": 16, + "myTeam": [{"cellId": 16, "championId": 2, "championPickIntent": 0}], + "actions": [], + "bans": {"myTeamBans": [], "theirTeamBans": []} + })); + let pick = reader + .read( + || panic!("the event session must be used"), + || panic!("the lists must stay cached"), + ) + .unwrap(); + assert_eq!(pick.current, Some(2)); + } } diff --git a/crates/core/src/client.rs b/crates/core/src/client.rs index 0210a80..17dc4e2 100644 --- a/crates/core/src/client.rs +++ b/crates/core/src/client.rs @@ -8,10 +8,8 @@ pub trait GameClientSource: Send + Sync { /// 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>; - /// Reads the live Arena selection after gameflow enters champ select. - fn champ_select(&self) -> Result { - Err(ClientError::Absent) - } + /// Reads the live Arena champ select after gameflow enters champ select. + fn champ_select(&self) -> Result; /// Blocks until the client reports an event or `timeout` elapses, and says which kind it was. fn wait_for_event(&self, timeout: Duration) -> ClientEvent; } @@ -20,14 +18,14 @@ pub trait GameClientSource: Send + Sync { #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum ClientEvent { /// The champ select session or one of its champion lists changed. - Selection, + ChampSelect, /// Anything else. #[default] Other, } -/// One read of the client, shared by the follower round and the live selection: a wake makes one -/// gameflow request, not one per reader. +/// One read of the client, shared by the follower round and the live champ select: a wake makes +/// one gameflow request, not one per reader. #[derive(Clone, Debug)] pub struct ClientSnapshot { pub signed_in: Result<(String, String), ClientError>, @@ -36,9 +34,16 @@ pub struct ClientSnapshot { impl ClientSnapshot { pub fn read(source: &dyn GameClientSource) -> Self { + let signed_in = source.signed_in(); + // Nobody signed in means the login screen: no gameflow request. Carrying the error keeps + // `Absent` meaning "no champ select" and a transient failure keeping the one shown. + let gameflow = match &signed_in { + Ok(_) => source.gameflow(), + Err(error) => Err(error.clone()), + }; Self { - signed_in: source.signed_in(), - gameflow: source.gameflow(), + signed_in, + gameflow, } } @@ -96,8 +101,59 @@ impl Gameflow { #[cfg(test)] mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + use super::*; + /// A client whose sign-in and gameflow answers are fixed; counts the gameflow requests. + struct Source { + signed_in: Result<(String, String), ClientError>, + gameflow_calls: AtomicUsize, + } + + impl GameClientSource for Source { + fn signed_in(&self) -> Result<(String, String), ClientError> { + self.signed_in.clone() + } + + fn gameflow(&self) -> Result { + self.gameflow_calls.fetch_add(1, Ordering::SeqCst); + Ok(Gameflow::default()) + } + + fn official_progress(&self, _: &str) -> Result, ClientError> { + Ok(None) + } + + fn champ_select(&self) -> Result { + Err(ClientError::Absent) + } + + fn wait_for_event(&self, _: Duration) -> ClientEvent { + ClientEvent::Other + } + } + + #[test] + fn a_login_screen_makes_no_gameflow_request() { + let source = Source { + signed_in: Err(ClientError::Absent), + gameflow_calls: AtomicUsize::new(0), + }; + let snapshot = ClientSnapshot::read(&source); + assert_eq!(snapshot.gameflow, Err(ClientError::Absent)); + assert_eq!(source.gameflow_calls.load(Ordering::SeqCst), 0); + + // A transient failure is carried, so a shown champ select stays. + let source = Source { + signed_in: Err(ClientError::Other("panne".into())), + gameflow_calls: AtomicUsize::new(0), + }; + let snapshot = ClientSnapshot::read(&source); + assert_eq!(snapshot.gameflow, Err(ClientError::Other("panne".into()))); + assert_eq!(source.gameflow_calls.load(Ordering::SeqCst), 0); + } + #[test] fn client_phases_map_to_game_phases() { for (name, phase) in [ diff --git a/crates/core/src/follow.rs b/crates/core/src/follow.rs index da78d11..6870462 100644 --- a/crates/core/src/follow.rs +++ b/crates/core/src/follow.rs @@ -139,7 +139,8 @@ pub fn same_riot_id(a: &str, b: &str) -> bool { a.to_lowercase() == b.to_lowercase() } -fn account_riot_id(account: &Account) -> String { +/// `gameName#tagLine` of an Account, the one place an Account's Riot ID is built. +pub fn account_riot_id(account: &Account) -> String { riot_id(&account.game_name, &account.tag_line) } @@ -206,7 +207,8 @@ impl Tracker { ) } - /// One read of the client for this wake; the follower round and the live selection share it. + /// One read of the client for this wake; the follower round and the live champ select share + /// it. pub fn client_snapshot(&self) -> ClientSnapshot { match &self.client { Some(client) => ClientSnapshot::read(client.as_ref()), @@ -332,14 +334,9 @@ impl Tracker { self.status() != before || added > 0 } - /// The signed-in Riot ID and its live pick, independent of slow Match history imports. + /// The signed-in Riot ID and its live pick, from a client read already made for this wake. /// `Err` means the read failed: keep what is shown. `Ok(None)` means no Arena champ select /// is running. - pub fn champ_select(&self) -> Result, crate::ClientError> { - self.champ_select_with(&self.client_snapshot()) - } - - /// The live pick from a client read already made for this wake. pub fn champ_select_with( &self, snapshot: &ClientSnapshot, @@ -365,7 +362,7 @@ impl Tracker { /// 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. The event says whether only the live - /// selection needs another read. + /// champ select needs another read. pub fn wait_for_client(&self) -> ClientEvent { let timeout = if self.follow().pending.is_empty() { WAIT_OTHERWISE @@ -532,6 +529,16 @@ mod tests { use std::collections::HashSet; use std::time::Duration; + #[test] + fn account_riot_ids_join_name_and_tag() { + let account = Account { + puuid: "p".into(), + game_name: "Joueur".into(), + tag_line: "EUW".into(), + }; + assert_eq!(account_riot_id(&account), "Joueur#EUW"); + } + #[test] fn every_problem_has_its_own_message() { let messages: HashSet = [ diff --git a/crates/core/src/league_client.rs b/crates/core/src/league_client.rs index 0e918d0..c87e33f 100644 --- a/crates/core/src/league_client.rs +++ b/crates/core/src/league_client.rs @@ -17,7 +17,7 @@ use tungstenite::{Connector, Message, WebSocket, client_tls_with_config}; use ureq::Agent; use ureq::tls::{Certificate, RootCerts, TlsConfig}; -use crate::champ_select::{ANVIL_EVENT, ChampSelectLists, DISABLED_EVENT, PICKABLE_EVENT}; +use crate::champ_select::{ANVIL_EVENT, ChampSelectReader, DISABLED_EVENT, PICKABLE_EVENT}; use crate::client::{ClientError, ClientEvent, GameClientSource, GamePhase, Gameflow}; use crate::riot::encode; @@ -52,14 +52,7 @@ pub struct LeagueClient { /// configuration is downloaded once per track. tracks: Mutex)>>, events: Mutex>, - champion_lists: Mutex, -} - -/// The champion lists of the current draft and the latest session the client sent as an event. -#[derive(Default)] -struct ChampSelectCache { - lists: Option, - session: Option, + champ_select_reader: ChampSelectReader, } struct Events(WebSocket>); @@ -100,7 +93,7 @@ impl LeagueClient { agent, tracks: Mutex::default(), events: Mutex::default(), - champion_lists: Mutex::default(), + champ_select_reader: ChampSelectReader::default(), } } @@ -175,35 +168,23 @@ impl GameClientSource for LeagueClient { fn gameflow(&self) -> Result { let (status, body) = self.get("/lol-gameflow/v1/session")?; let flow = decode_gameflow(status, &body)?; - if !flow.is_arena_champ_select() { - *lock(&self.champion_lists) = ChampSelectCache::default(); - } + self.champ_select_reader + .reset_unless_arena_champ_select(&flow); Ok(flow) } fn champ_select(&self) -> Result { - let session = { - let mut cache = lock(&self.champion_lists); - cache.session.take() - }; - let session = match session { - Some(session) => session, - None => parse(&self.get_ok(SESSION)?)?, - }; - let mut cache = lock(&self.champion_lists); - if cache.lists.is_none() { - let pickable = self.get_ok(PICKABLE)?; - let disabled = self.get_ok(DISABLED)?; - // The anvil list is a bonus: a failed read leaves it empty until an event delivers it. - let anvil = self.get_ok(ANVIL_CHAMPIONS).ok(); - cache.lists = Some(ChampSelectLists::fetch( - &pickable, - &disabled, - anvil.as_deref(), - )?); - } - let lists = cache.lists.as_ref().expect("set just above"); - crate::ChampSelect::from_session(&session, lists.pickable(), lists.anvil().to_vec()) + self.champ_select_reader.read( + || self.get_ok(SESSION), + || { + let pickable = self.get_ok(PICKABLE)?; + let disabled = self.get_ok(DISABLED)?; + // The anvil list is a bonus: a failed read leaves it empty until an event + // delivers it. + let anvil = self.get_ok(ANVIL_CHAMPIONS).ok(); + Ok((pickable, disabled, anvil)) + }, + ) } fn official_progress(&self, track_name: &str) -> Result, ClientError> { @@ -235,7 +216,7 @@ impl GameClientSource for LeagueClient { let mut events = lock(&self.events); if events.is_none() { // A reconnection may follow a client restart: the lists belong to the previous one. - *lock(&self.champion_lists) = ChampSelectCache::default(); + self.champ_select_reader.reset(); *events = self.connect(); // Re-read the snapshot after subscribing. if events.is_some() { @@ -261,7 +242,12 @@ impl GameClientSource for LeagueClient { let Some((topic, data)) = decode_event(&text) else { continue; }; - return self.apply_event(&topic, data); + match self.apply_event(&topic, data) { + // A deleted session carries nothing to show: keep waiting, the gameflow + // event that follows ends the champ select view. + None => continue, + Some(event) => return event, + } } Ok(Message::Close(_)) => *events = None, Ok(_) => continue, @@ -275,29 +261,35 @@ impl GameClientSource for LeagueClient { } impl LeagueClient { - /// Applies one event to the cache, touching only the list it concerns. - fn apply_event(&self, topic: &str, data: Value) -> ClientEvent { + /// Applies one event, touching only the list it concerns. `None` when the event carries + /// nothing to show: a deleted champ select session, which must cost no request. + fn apply_event(&self, topic: &str, data: Value) -> Option { match topic { SESSION_EVENT => { - let mut cache = lock(&self.champion_lists); - if data.is_object() { - cache.session = Some(data); + if data.is_null() { + return None; } - ClientEvent::Selection + self.champ_select_reader.set_session(data); + Some(ClientEvent::ChampSelect) } - PICKABLE_EVENT | DISABLED_EVENT | ANVIL_EVENT => { - let mut cache = lock(&self.champion_lists); - if let Some(lists) = cache.lists.as_mut() { - lists.apply_event(topic, &data); - } - ClientEvent::Selection + PICKABLE_EVENT => { + self.champ_select_reader.set_pickable(&data); + Some(ClientEvent::ChampSelect) } - _ => ClientEvent::Other, + DISABLED_EVENT => { + self.champ_select_reader.set_disabled(&data); + Some(ClientEvent::ChampSelect) + } + ANVIL_EVENT => { + self.champ_select_reader.set_anvil(&data); + Some(ClientEvent::ChampSelect) + } + _ => Some(ClientEvent::Other), } } } -fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { +pub(crate) fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { mutex.lock().unwrap_or_else(PoisonError::into_inner) } @@ -319,7 +311,8 @@ fn tls_config() -> Result { } /// A rejected certificate, a timeout or a dropped connection is worth telling apart from a -/// client that is simply not there (nothing listens): the first ones say nothing about the draft. +/// client that is simply not there (nothing listens): the first ones say nothing about the champ +/// select. fn transport_error(e: ureq::Error) -> ClientError { match e { ureq::Error::Tls(_) | ureq::Error::Rustls(_) => { @@ -661,47 +654,65 @@ mod tests { format!(r#"[8,"{topic}",{{"data":{data},"eventType":"{event_type}","uri":"/x"}}]"#) } + /// A session body the reader can assemble, with this local pick. + fn session(current: u32) -> String { + format!( + r#"{{"localPlayerCellId":16,"myTeam":[{{"cellId":16,"championId":{current}, + "championPickIntent":0}},{{"cellId":17,"championId":0, + "championPickIntent":0}}],"actions":[], + "bans":{{"myTeamBans":[],"theirTeamBans":[]}}}}"# + ) + } + #[test] fn a_raw_event_frame_updates_the_cached_session_and_lists() { - use serde_json::json; - use std::collections::HashSet; - let client = LeagueClient::in_dir(PathBuf::new()); - *lock(&client.champion_lists) = ChampSelectCache { - lists: Some(ChampSelectLists::fetch("[1,2]", "[]", Some("[]")).unwrap()), - session: None, - }; + client + .champ_select_reader + .read( + || Ok(session(0)), + || Ok(("[1,2]".into(), "[]".into(), Some("[]".into()))), + ) + .unwrap(); let apply = |topic, event_type, data: &str| { let (topic, data) = decode_event(&frame(topic, event_type, data)).unwrap(); client.apply_event(&topic, data) }; assert_eq!( - apply(SESSION_EVENT, "Update", r#"{"localPlayerCellId":16}"#), - ClientEvent::Selection + apply(SESSION_EVENT, "Update", &session(16)), + Some(ClientEvent::ChampSelect) ); assert_eq!( apply(ANVIL_EVENT, "Update", "[9,8]"), - ClientEvent::Selection + Some(ClientEvent::ChampSelect) ); assert_eq!( apply(PICKABLE_EVENT, "Update", "[2]"), - ClientEvent::Selection + Some(ClientEvent::ChampSelect) ); - // A Delete carries no data: it neither wipes nor corrupts what is cached. + // A deleted session carries nothing: it costs no request. Other Deletes change nothing + // either, but still wake the follower. + assert_eq!(apply(SESSION_EVENT, "Delete", "null"), None); assert_eq!( - apply(SESSION_EVENT, "Delete", "null"), - ClientEvent::Selection + apply(ANVIL_EVENT, "Delete", "null"), + Some(ClientEvent::ChampSelect) ); - assert_eq!(apply(ANVIL_EVENT, "Delete", "null"), ClientEvent::Selection); assert_eq!( apply(PICKABLE_EVENT, "Delete", "null"), - ClientEvent::Selection + Some(ClientEvent::ChampSelect) ); - let cache = lock(&client.champion_lists); - assert_eq!(cache.session, Some(json!({"localPlayerCellId": 16}))); - let lists = cache.lists.as_ref().unwrap(); - assert_eq!(lists.anvil(), [9, 8]); - assert_eq!(&*lists.pickable(), &HashSet::from([2])); + // The event session replaces the request and the updated lists are used. + let pick = client + .champ_select_reader + .read( + || panic!("the event session must be used"), + || panic!("the lists must stay cached"), + ) + .unwrap(); + assert_eq!(pick.current, Some(16)); + assert_eq!(pick.anvil_champions, [9, 8]); + assert!(!pick.can_pick(1)); + assert!(pick.can_pick(2)); } #[test] @@ -723,44 +734,53 @@ mod tests { #[test] fn events_update_only_the_list_they_concern() { use serde_json::json; - use std::collections::HashSet; let client = LeagueClient::in_dir(PathBuf::new()); - *lock(&client.champion_lists) = ChampSelectCache { - lists: Some(ChampSelectLists::fetch("[1,2]", "[2]", Some("[9]")).unwrap()), - session: None, - }; + client + .champ_select_reader + .read( + || Ok(session(0)), + || Ok(("[1,2]".into(), "[2]".into(), Some("[9]".into()))), + ) + .unwrap(); // A gameflow event leaves the champion lists alone; the old code cleared them all. assert_eq!( client.apply_event("OnJsonApiEvent_lol-gameflow_v1_session", json!({})), - ClientEvent::Other + Some(ClientEvent::Other) ); - { - let cache = lock(&client.champion_lists); - let lists = cache.lists.as_ref().unwrap(); - assert_eq!(&*lists.pickable(), &HashSet::from([1])); - assert_eq!(lists.anvil(), [9]); - } + let read = || { + client + .champ_select_reader + .read(|| Ok(session(0)), || panic!("the lists must stay cached")) + .unwrap() + }; + let pick = read(); + assert_eq!(pick.anvil_champions, [9]); + assert!(pick.can_pick(1)); + assert!(!pick.can_pick(2)); + assert_eq!( client.apply_event(PICKABLE_EVENT, json!([1, 3])), - ClientEvent::Selection + Some(ClientEvent::ChampSelect) ); + let pick = read(); + assert!(pick.can_pick(1)); + assert!(pick.can_pick(3)); + assert!(!pick.can_pick(2)); + + // A session event is kept for the next read instead of a request. assert_eq!( - &*lock(&client.champion_lists) - .lists - .as_ref() - .unwrap() - .pickable(), - &HashSet::from([1, 3]) + client.apply_event(SESSION_EVENT, serde_json::from_str(&session(16)).unwrap()), + Some(ClientEvent::ChampSelect) ); - // A session event is kept for the next read instead of a GET. - assert_eq!( - client.apply_event(SESSION_EVENT, json!({"localPlayerCellId": 16})), - ClientEvent::Selection - ); - assert_eq!( - lock(&client.champion_lists).session, - Some(json!({"localPlayerCellId": 16})) + assert!( + client + .champ_select_reader + .read( + || panic!("the event session must be used"), + || panic!("the lists must stay cached"), + ) + .is_ok() ); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 98333a0..06040f1 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -13,7 +13,7 @@ mod seasons; mod statistics; mod tracker; -pub use champ_select::ChampSelect; +pub use champ_select::{ChampSelect, ChampSelectReader}; pub use champion_search::ChampionSearch; pub use champions::{Champion, ChampionCatalog, ChampionSource, DataDragon}; pub use client::{ClientError, ClientEvent, ClientSnapshot, GameClientSource, GamePhase, Gameflow}; @@ -21,7 +21,8 @@ pub use config::{Config, Preferences, ThemePreference, data_dir}; pub use date::Date; pub use error::{Error, SourceError}; pub use follow::{ - MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem, riot_id, same_riot_id, + MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Status, UpdateProblem, account_riot_id, riot_id, + same_riot_id, }; pub use league_client::{LeagueClient, decode_gameflow}; pub use model::{Account, Format, Match, SyncProgress, SyncReport}; diff --git a/crates/core/tests/common/mod.rs b/crates/core/tests/common/mod.rs index 39b6010..8c40a8a 100644 --- a/crates/core/tests/common/mod.rs +++ b/crates/core/tests/common/mod.rs @@ -2,7 +2,7 @@ // Each test binary uses its own subset of these helpers. #![allow(dead_code)] -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender}; @@ -10,9 +10,9 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use arena_tracker_core::{ - Account, ChampSelect, Champion, ChampionCatalog, ChampionSource, ClientError, ClientEvent, - Date, GameClientSource, GamePhase, Gameflow, MatchHistorySource, Season, SourceError, Tracker, - decode_gameflow, + Account, ChampSelect, ChampSelectReader, Champion, ChampionCatalog, ChampionSource, + ClientError, ClientEvent, Date, GameClientSource, GamePhase, Gameflow, MatchHistorySource, + Season, SourceError, Tracker, decode_gameflow, }; use serde_json::Value; @@ -562,6 +562,9 @@ pub fn recorded_game_id() -> u64 { #[derive(Clone, Default)] pub struct FakeClient { state: Arc>, + /// Session and champion-list bodies the fake's champ select reader asked for. + session_reads: Arc, + list_reads: Arc, } #[derive(Default)] @@ -570,15 +573,20 @@ struct ClientState { gameflow: Gameflow, tracks: HashMap, waits: Vec, - /// The raw bodies the client answers for the current draft. + /// The raw bodies the client answers for the current champ select. champ_select: Option, + /// Reads the champ select the one way the live client does. + champ_select_reader: ChampSelectReader, + /// Session bodies the client reports as events, applied before `wait_for_event` returns. + events: VecDeque, /// A raw gameflow body, replayed through the same parser as the live client. raw_gameflow: Option, gameflow_error: Option, champ_select_error: Option, } -/// The raw client responses of a draft, replayed through the same parsing as the live client. +/// The raw client responses of a champ select, replayed through the same reader as the live +/// client. #[derive(Clone)] pub struct RawChampSelect { pub pickable: String, @@ -659,6 +667,20 @@ impl FakeClient { self.state.lock().unwrap().champ_select = Some(raw); } + /// Reports one of the captured session bodies as the client's champ select event. + pub fn send_champ_select_event(&self, session: &str) { + let session = serde_json::from_str(session).unwrap_or(Value::Null); + self.state.lock().unwrap().events.push_back(session); + } + + /// How many session and champion-list bodies the champ select reader asked the client for. + pub fn champ_select_reads(&self) -> (usize, usize) { + ( + self.session_reads.load(Ordering::SeqCst), + self.list_reads.load(Ordering::SeqCst), + ) + } + /// The next gameflow or champ select read fails with this, until cleared. pub fn fail_gameflow(&self, error: Option) { self.state.lock().unwrap().gameflow_error = error; @@ -694,10 +716,14 @@ impl GameClientSource for FakeClient { if let Some(error) = &state.gameflow_error { return Err(error.clone()); } - match &state.raw_gameflow { - Some(body) => decode_gameflow(200, body), - None => Ok(state.gameflow.clone()), - } + let flow = match &state.raw_gameflow { + Some(body) => decode_gameflow(200, body)?, + None => state.gameflow.clone(), + }; + state + .champ_select_reader + .reset_unless_arena_champ_select(&flow); + Ok(flow) } fn champ_select(&self) -> Result { @@ -706,12 +732,22 @@ impl GameClientSource for FakeClient { return Err(error.clone()); } let raw = state.champ_select.as_ref().ok_or(ClientError::Absent)?; - let session = serde_json::from_str(&raw.session) - .map_err(|error| ClientError::Other(error.to_string()))?; - let pickable = ChampSelect::pickable_champions(&raw.pickable, &raw.disabled)?; - let anvil = serde_json::from_str(&raw.anvil) - .map_err(|error| ClientError::Other(error.to_string()))?; - ChampSelect::from_session(&session, pickable, anvil) + let sessions = self.session_reads.clone(); + let lists = self.list_reads.clone(); + state.champ_select_reader.read( + || { + sessions.fetch_add(1, Ordering::SeqCst); + Ok(raw.session.clone()) + }, + || { + lists.fetch_add(1, Ordering::SeqCst); + Ok(( + raw.pickable.clone(), + raw.disabled.clone(), + Some(raw.anvil.clone()), + )) + }, + ) } fn official_progress(&self, track_name: &str) -> Result, ClientError> { @@ -721,7 +757,14 @@ impl GameClientSource for FakeClient { } fn wait_for_event(&self, timeout: Duration) -> ClientEvent { - self.state.lock().unwrap().waits.push(timeout); - ClientEvent::Other + let mut state = self.state.lock().unwrap(); + state.waits.push(timeout); + match state.events.pop_front() { + Some(session) => { + state.champ_select_reader.set_session(session); + ClientEvent::ChampSelect + } + None => ClientEvent::Other, + } } } diff --git a/crates/core/tests/follow.rs b/crates/core/tests/follow.rs index ab257f7..03f4349 100644 --- a/crates/core/tests/follow.rs +++ b/crates/core/tests/follow.rs @@ -7,8 +7,9 @@ use std::thread; use std::time::{Duration, Instant}; use arena_tracker_core::{ - Account, ClientError, Format, MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Scope, SeasonScope, - SourceError, Tracker, UpdateProblem, + Account, ChampSelect, ChampionRow, ChampionState, ClientError, ClientEvent, Format, + MATCH_RETRIES, ProgressCheck, RETRY_EVERY_MS, Scope, SeasonScope, SourceError, Tracker, + UpdateProblem, }; use common::{ FakeClient, FakeHistory, PlayedMatch, RawChampSelect, S2, S2_TRACK, SELF_PUUID, at, date, @@ -92,6 +93,11 @@ fn round(tracker: &Tracker) -> bool { round_after(tracker, RETRY_EVERY_MS) } +/// The live champ select the page would show, read once at this instant. +fn shown(tracker: &Tracker) -> Result, ClientError> { + tracker.champ_select_with(&tracker.client_snapshot()) +} + fn completed(tracker: &Tracker, puuid: &str) -> usize { let scope = Scope { season: SeasonScope::Season(S2.into()), @@ -1026,15 +1032,36 @@ fn banners_point_to_the_parametres_screen_and_never_to_a_missing_field() { #[test] fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge() { - use arena_tracker_core::ChampionState; use serde_json::Value; + + fn assert_pick( + pick: &ChampSelect, + rows: &[ChampionRow], + current: Option<(u32, ChampionState)>, + remaining: &[u32], + ) { + assert_eq!(pick.anvil_champions, [233, 64, 5, 16, 68]); + assert_eq!( + pick.current_row(rows) + .map(|r| (r.champion.id, r.attempts, r.state)), + current.map(|(id, state)| (id, Some(1), Some(state))) + ); + let mut ids: Vec<_> = rows + .iter() + .filter(|r| pick.remaining(r)) + .map(|r| r.champion.id) + .collect(); + ids.sort_unstable(); + assert_eq!(ids, remaining); + } + let capture: Value = serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap(); let world = World::new( &[12, 16, 25, 50, 103, 233].map(|id| played_match(id, if id == 16 { 1 } else { 4 }, now())), ); let tracker = world.tracker(); - // The fake replays the captured raw responses: `Tracker` parses them as it does the client's. + // The fake replays the captured raw responses through the same reader as the live client. let set_frame = |frame: usize| { world.client.set_champ_select(RawChampSelect { pickable: capture["pickableChampionIds"].to_string(), @@ -1046,7 +1073,7 @@ fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge( set_frame(0); world.client.set_phase("ChampSelect", false); round(&tracker); - assert_eq!(tracker.champ_select(), Ok(None)); + assert_eq!(shown(&tracker), Ok(None)); // The captured gameflow body goes through the live client's parser too. world.client.set_gameflow(&capture["gameflow"].to_string()); let rows = tracker @@ -1059,8 +1086,16 @@ fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge( ) .unwrap() .rows; + + // The first read fetches the session and the champion lists once. + let (account, pick) = shown(&tracker).unwrap().unwrap(); + assert_eq!(account, "Joueur#EUW"); + assert_pick(&pick, &rows, None, &[12, 25, 50, 103, 233]); + assert_eq!(world.client.champ_select_reads(), (1, 1)); + + // Every later change arrives as the client's session event: neither the session nor the + // lists are read again. for (frame, current, remaining) in [ - (0, None, vec![12, 25, 50, 103, 233]), (1, None, vec![25, 50, 103, 233]), ( 2, @@ -1070,31 +1105,26 @@ fn arena_champ_select_replays_bans_hovers_and_lock_in_for_the_current_challenge( (3, Some((16, ChampionState::Completed)), vec![103, 233]), (4, Some((16, ChampionState::Completed)), vec![103, 233]), ] { - set_frame(frame); - round(&tracker); - let (account, pick) = tracker.champ_select().unwrap().unwrap(); - assert_eq!(account, "Joueur#EUW"); - assert_eq!(pick.anvil_champions, [233, 64, 5, 16, 68]); - assert_eq!( - pick.current_row(&rows) - .map(|r| (r.champion.id, r.attempts, r.state)), - current.map(|(id, state)| (id, Some(1), Some(state))) - ); - let mut ids: Vec<_> = rows - .iter() - .filter(|r| pick.remaining(r)) - .map(|r| r.champion.id) - .collect(); - ids.sort_unstable(); - assert_eq!(ids, remaining); + world + .client + .send_champ_select_event(&capture["sessions"][frame].to_string()); + assert_eq!(tracker.wait_for_client(), ClientEvent::ChampSelect); + let (_, pick) = shown(&tracker).unwrap().unwrap(); + assert_pick(&pick, &rows, current, &remaining); + assert_eq!(world.client.champ_select_reads(), (1, 1)); } + + // Leaving the champ select ends it and drops its lists; the next one reads them again. world.client.set_phase("InProgress", true); - round(&tracker); - assert_eq!(tracker.champ_select(), Ok(None)); + assert_eq!(shown(&tracker), Ok(None)); + set_frame(0); + world.client.set_gameflow(&capture["gameflow"].to_string()); + assert!(shown(&tracker).unwrap().is_some()); + assert_eq!(world.client.champ_select_reads(), (2, 2)); } #[test] -fn a_failed_champ_select_read_keeps_the_pick_until_the_draft_really_ends() { +fn a_failed_champ_select_read_keeps_the_pick_until_the_champ_select_really_ends() { use serde_json::Value; let capture: Value = serde_json::from_str(include_str!("fixtures/client/arena_champ_select.json")).unwrap(); @@ -1107,31 +1137,25 @@ fn a_failed_champ_select_read_keeps_the_pick_until_the_draft_really_ends() { session: capture["sessions"][0].to_string(), }); world.client.set_gameflow(&capture["gameflow"].to_string()); - let shown = tracker.champ_select().unwrap(); - assert!(shown.is_some()); + let live = shown(&tracker).unwrap(); + assert!(live.is_some()); - // A failed gameflow or session request is not an answer that the draft is over. + // A failed gameflow or session request is not an answer that the champ select is over. world .client .fail_gameflow(Some(ClientError::Other("HTTP 500".into()))); - assert_eq!( - tracker.champ_select(), - Err(ClientError::Other("HTTP 500".into())) - ); + assert_eq!(shown(&tracker), Err(ClientError::Other("HTTP 500".into()))); world.client.fail_gameflow(None); world .client .fail_champ_select(Some(ClientError::Other("HTTP 500".into()))); - assert_eq!( - tracker.champ_select(), - Err(ClientError::Other("HTTP 500".into())) - ); + assert_eq!(shown(&tracker), Err(ClientError::Other("HTTP 500".into()))); world.client.fail_champ_select(None); - assert_eq!(tracker.champ_select().unwrap(), shown); + assert_eq!(shown(&tracker).unwrap(), live); // Leaving champ select, or the client going away, does end it. world.client.set_phase("InProgress", true); - assert_eq!(tracker.champ_select(), Ok(None)); + assert_eq!(shown(&tracker), Ok(None)); world.client.sign_out(); - assert_eq!(tracker.champ_select(), Ok(None)); + assert_eq!(shown(&tracker), Ok(None)); } -- 2.54.0