From 18b06f8ea6b429b993fba57281a58bea474dc25f Mon Sep 17 00:00:00 2001 From: TO Date: Sat, 21 Nov 2026 02:13:00 +0100 Subject: [PATCH] Read the portraits folders once and stop the card pass offline (#77) The statistics list the portraits folder and its cards subfolder once instead of checking about 340 files. The tall-portrait pass is skipped when the catalog refresh failed and stops at the first network error; the core tells after each attempt whether a portrait was saved, so the worker's throttle can tell the page after any attempt, not only saves. Co-Authored-By: Claude Opus 5.5 --- crates/app/src/worker.rs | 87 +++++++++++++++++++++------------ crates/core/src/champions.rs | 28 ++++++++--- crates/core/src/statistics.rs | 27 ++++++++-- crates/core/tests/champions.rs | 87 ++++++++++++++++++++++++++++++--- crates/core/tests/common/mod.rs | 7 ++- 5 files changed, 183 insertions(+), 53 deletions(-) diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs index 154a260..7cc5260 100644 --- a/crates/app/src/worker.rs +++ b/crates/app/src/worker.rs @@ -81,9 +81,9 @@ impl RefreshGate { /// statistics to show them. const PORTRAITS_TOLD_EVERY: Duration = Duration::from_secs(1); -/// Spaces out what saved portraits cause: the first save is told at once, the next ones at most -/// once per `every`, and one left untold when the pass ends is told then. No timer: a save or -/// the end of the pass is what tells. +/// Spaces out what saved portraits cause: the first save is told at once, the next ones when +/// `every` has passed since the last message, and one still untold when the pass ends is told +/// then. No timer: each attempt of the pass, saved or not, and its end are what tell. struct Throttle { every: Duration, last_told: Option, @@ -99,18 +99,19 @@ impl Throttle { } } - /// A portrait was saved at `now`: true when it must be told now. - fn saved(&mut self, now: Instant) -> bool { - if self + /// An attempt ended at `now`, with a portrait saved or not: true when the page must be told + /// now, as a save is untold and `every` has passed since the last message. + fn attempted(&mut self, saved: bool, now: Instant) -> bool { + self.untold |= saved; + let due = self .last_told - .is_some_and(|last| now.duration_since(last) < self.every) - { - self.untold = true; - return false; + .is_none_or(|last| now.duration_since(last) >= self.every); + if self.untold && due { + self.last_told = Some(now); + self.untold = false; + return true; } - self.last_told = Some(now); - self.untold = false; - true + false } /// The pass ended: true when a save is still untold. @@ -170,13 +171,17 @@ fn spawn_guarded( pub fn spawn_follower(tracker: Arc, fallback_riot_id: String, tx: Sender) { let champions = tracker.clone(); spawn_guarded(tx.clone(), Msg::Crashed, move |tx| { - let _ = champions.refresh_champions(); + let refreshed = champions.refresh_champions(); let _ = tx.try_send(Msg::Champions); + // Offline, the catalog call failed and so would every portrait request. + if refreshed.is_err() { + return; + } // The tall card portraits after the square ones, which the Statistiques table uses. They // show as they arrive, without a restart, the page reloading at most once a second. let mut throttle = Throttle::new(PORTRAITS_TOLD_EVERY); - let _ = champions.refresh_card_portraits(&mut || { - if throttle.saved(Instant::now()) { + let _ = champions.refresh_card_portraits(&mut |saved| { + if throttle.attempted(saved, Instant::now()) { let _ = tx.try_send(Msg::Champions); } }); @@ -282,12 +287,20 @@ pub fn spawn_refresh(tracker: Arc, tx: Sender) { }); } +#[cfg(test)] +thread_local! { + /// The scopes computed on this thread, to check what a change makes the page compute. + pub static COMPUTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + /// The statistics of `puuid` for `scope`, with the error as the page shows it. pub fn compute_statistics( tracker: &Tracker, puuid: &str, scope: &Scope, ) -> Result { + #[cfg(test)] + COMPUTED.with(|computed| computed.borrow_mut().push(scope.clone())); tracker .statistics(puuid, scope) .map_err(|e| format!("Statistiques indisponibles : {e}")) @@ -431,27 +444,39 @@ mod tests { } #[test] - fn saved_portraits_are_told_at_most_once_a_second_and_the_last_ones_at_the_end() { + fn saved_portraits_are_told_once_a_second_after_any_attempt_and_the_last_ones_at_the_end() { let start = Instant::now(); let at = |ms: u64| start + Duration::from_millis(ms); let mut throttle = Throttle::new(Duration::from_secs(1)); - assert!(throttle.saved(at(0)), "the first save is told at once"); - assert!(!throttle.saved(at(300))); - assert!(!throttle.saved(at(999))); - assert!(throttle.saved(at(1000))); - assert!(!throttle.saved(at(1500))); - // The save at 1.5 s is told when the pass ends. - assert!(throttle.finished()); - - // The last save was told: nothing more at the end. - let mut throttle = Throttle::new(Duration::from_secs(1)); - assert!(throttle.saved(at(0))); - assert!(!throttle.saved(at(10))); - assert!(throttle.saved(at(2000))); + assert!( + throttle.attempted(true, at(0)), + "the first save is told at once" + ); + assert!(!throttle.attempted(true, at(300))); + assert!(!throttle.attempted(true, at(999))); + assert!(throttle.attempted(true, at(1000))); + assert!(!throttle.attempted(true, at(1500))); + // A failed attempt tells nothing before the second is over, then the save at 1.5 s is. + assert!(!throttle.attempted(false, at(1900))); + assert!(throttle.attempted(false, at(2000))); + assert!( + !throttle.attempted(false, at(5000)), + "nothing is untold any more" + ); assert!(!throttle.finished()); + // The last save was told late or never: the end of the pass tells it. + let mut throttle = Throttle::new(Duration::from_secs(1)); + assert!(throttle.attempted(true, at(0))); + assert!(!throttle.attempted(true, at(10))); + assert!(!throttle.attempted(false, at(20))); + assert!(throttle.finished()); + // Nothing saved, nothing told. - assert!(!Throttle::new(Duration::from_secs(1)).finished()); + let mut throttle = Throttle::new(Duration::from_secs(1)); + assert!(!throttle.attempted(false, at(0))); + assert!(!throttle.attempted(false, at(5000))); + assert!(!throttle.finished()); } #[test] diff --git a/crates/core/src/champions.rs b/crates/core/src/champions.rs index 38f587b..09790a9 100644 --- a/crates/core/src/champions.rs +++ b/crates/core/src/champions.rs @@ -244,9 +244,11 @@ impl Tracker { /// Downloads the tall card portraits missing from the portraits dir's `cards` folder, /// cropped and shrunk to the card's size (see `process_card_portrait`). A failed - /// download or an unreadable image is skipped and retried by the next pass. `on_saved` - /// is called after each portrait is saved. Meant to run after `refresh_champions`. - pub fn refresh_card_portraits(&self, on_saved: &mut dyn FnMut()) -> Result<(), Error> { + /// download of one champion (not found, an unreadable image) is skipped and retried by the + /// next pass; a network error stops the pass, as every other request would fail as well. + /// `on_attempt` is called after each download attempt, with whether a portrait was saved. + /// Meant to run after `refresh_champions`. + pub fn refresh_card_portraits(&self, on_attempt: &mut dyn FnMut(bool)) -> Result<(), Error> { let Some((source, portraits_dir)) = &self.champions else { return Ok(()); }; @@ -259,19 +261,29 @@ impl Tracker { if path.exists() || !champion.key.chars().all(|c| c.is_ascii_alphanumeric()) { continue; } - let Ok(art) = source.card_portrait(&champion.key) else { - continue; + let art = match source.card_portrait(&champion.key) { + Ok(art) => art, + Err(SourceError::Network(_)) => { + on_attempt(false); + break; + } + Err(_) => { + on_attempt(false); + continue; + } }; let Ok(card) = process_card_portrait(&art) else { + on_attempt(false); continue; }; // Written under another name first so a cut write is never taken for a portrait. let partial = path.with_extension("part"); - if std::fs::write(&partial, card).is_ok() && std::fs::rename(&partial, &path).is_ok() { - on_saved(); - } else { + let saved = + std::fs::write(&partial, card).is_ok() && std::fs::rename(&partial, &path).is_ok(); + if !saved { let _ = std::fs::remove_file(&partial); } + on_attempt(saved); } Ok(()) } diff --git a/crates/core/src/statistics.rs b/crates/core/src/statistics.rs index d0ce7de..5309b31 100644 --- a/crates/core/src/statistics.rs +++ b/crates/core/src/statistics.rs @@ -1,8 +1,9 @@ //! Challenge figures and champion statistics, computed on demand from stored Matches. use std::cmp::Ordering; use std::collections::{BTreeMap, HashMap, HashSet}; +use std::ffi::{OsStr, OsString}; use std::ops::Range; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use crate::champions::{Champion, card_portrait_path}; use crate::date::Date; @@ -403,6 +404,18 @@ pub(crate) fn compute( } } +/// The names of the files in `dir`; none when it is missing or unreadable. +fn file_names(dir: &Path) -> HashSet { + let Ok(entries) = std::fs::read_dir(dir) else { + return HashSet::new(); + }; + entries + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) + .map(|entry| entry.file_name()) + .collect() +} + impl Tracker { /// Replaces the Season table; Matches are assigned to Seasons on demand, so already /// stored Matches move accordingly. @@ -446,11 +459,17 @@ impl Tracker { } } if let Some((_, dir)) = &self.champions { + // One read of each folder rather than a file check per champion and per portrait. + let squares = file_names(dir); + let cards = file_names(&dir.join("cards")); for row in &mut stats.rows { - let path = dir.join(format!("{}.png", row.champion.key)); - row.portrait = path.is_file().then_some(path); + let name = format!("{}.png", row.champion.key); + row.portrait = squares.contains(OsStr::new(&name)).then(|| dir.join(name)); let card = card_portrait_path(dir, &row.champion.key); - row.card_portrait = card.is_file().then_some(card); + row.card_portrait = card + .file_name() + .is_some_and(|name| cards.contains(name)) + .then_some(card); } } Ok(stats) diff --git a/crates/core/tests/champions.rs b/crates/core/tests/champions.rs index e612dc0..8dd0804 100644 --- a/crates/core/tests/champions.rs +++ b/crates/core/tests/champions.rs @@ -170,6 +170,29 @@ fn portraits_are_downloaded_and_exposed_and_a_failed_one_is_left_out() { assert!(!portraits.join("Jinx.part").exists()); } +#[test] +fn only_files_count_as_portraits() { + let dir = tempfile::tempdir().unwrap(); + let tracker = reopen(dir.path(), FakeChampions::new("1.0", &CATALOG)); + tracker.refresh_champions().unwrap(); + let portraits = dir.path().join("portraits"); + std::fs::remove_file(portraits.join("Jinx.png")).unwrap(); + std::fs::create_dir(portraits.join("Jinx.png")).unwrap(); + + let stats = statistics(&tracker); + + let jinx = stats + .rows + .iter() + .find(|r| r.champion.key == "Jinx") + .unwrap(); + assert_eq!(jinx.portrait, None); + assert_eq!( + stats.rows.iter().filter(|r| r.portrait.is_some()).count(), + 5 + ); +} + fn cards_dir(dir: &std::path::Path) -> std::path::PathBuf { dir.join("portraits").join("cards") } @@ -198,7 +221,9 @@ fn a_missing_card_portrait_is_downloaded_once_then_read_from_disk() { ); let mut saved = 0; - tracker.refresh_card_portraits(&mut || saved += 1).unwrap(); + tracker + .refresh_card_portraits(&mut |ok| saved += usize::from(ok)) + .unwrap(); assert_eq!((saved, calls.load(Ordering::SeqCst)), (6, 6)); let stats = statistics(&tracker); @@ -212,7 +237,7 @@ fn a_missing_card_portrait_is_downloaded_once_then_read_from_disk() { let mut saved_again = 0; tracker - .refresh_card_portraits(&mut || saved_again += 1) + .refresh_card_portraits(&mut |ok| saved_again += usize::from(ok)) .unwrap(); assert_eq!((saved_again, calls.load(Ordering::SeqCst)), (0, 6)); } @@ -228,7 +253,9 @@ fn a_failed_card_download_leaves_no_file_and_the_next_pass_resumes() { failure.store(true, Ordering::SeqCst); let mut saved = 0; - tracker.refresh_card_portraits(&mut || saved += 1).unwrap(); + tracker + .refresh_card_portraits(&mut |ok| saved += usize::from(ok)) + .unwrap(); assert_eq!(saved, 0); assert!(card_files(dir.path()).is_empty()); @@ -240,11 +267,14 @@ fn a_failed_card_download_leaves_no_file_and_the_next_pass_resumes() { ); failure.store(false, Ordering::SeqCst); - tracker.refresh_card_portraits(&mut || saved += 1).unwrap(); + tracker + .refresh_card_portraits(&mut |ok| saved += usize::from(ok)) + .unwrap(); assert_eq!(saved, 6); assert_eq!(card_files(dir.path()).len(), 6); - assert_eq!(calls.load(Ordering::SeqCst), 12); + // One request failed the first pass; the second asked for the six. + assert_eq!(calls.load(Ordering::SeqCst), 7); assert!( statistics(&tracker) .rows @@ -253,6 +283,43 @@ fn a_failed_card_download_leaves_no_file_and_the_next_pass_resumes() { ); } +#[test] +fn a_network_error_stops_the_card_pass_after_one_request() { + let dir = tempfile::tempdir().unwrap(); + let source = FakeChampions::new("1.0", &CATALOG); + let failure = source.card_failure(); + let calls = source.card_counter(); + let tracker = reopen(dir.path(), source); + tracker.refresh_champions().unwrap(); + failure.store(true, Ordering::SeqCst); + + let mut attempts = Vec::new(); + tracker + .refresh_card_portraits(&mut |ok| attempts.push(ok)) + .unwrap(); + + assert_eq!(calls.load(Ordering::SeqCst), 1); + assert_eq!(attempts, [false]); +} + +#[test] +fn each_card_attempt_tells_whether_a_portrait_was_saved() { + let dir = tempfile::tempdir().unwrap(); + let tracker = reopen( + dir.path(), + FakeChampions::new("1.0", &CATALOG).without_portrait("Jinx"), + ); + tracker.refresh_champions().unwrap(); + + let mut attempts = Vec::new(); + tracker + .refresh_card_portraits(&mut |ok| attempts.push(ok)) + .unwrap(); + + assert_eq!(attempts.len(), 6); + assert_eq!(attempts.iter().filter(|ok| **ok).count(), 5); +} + #[test] fn a_card_portrait_that_cannot_be_read_is_skipped_without_a_file() { let dir = tempfile::tempdir().unwrap(); @@ -263,7 +330,9 @@ fn a_card_portrait_that_cannot_be_read_is_skipped_without_a_file() { tracker.refresh_champions().unwrap(); let mut saved = 0; - tracker.refresh_card_portraits(&mut || saved += 1).unwrap(); + tracker + .refresh_card_portraits(&mut |ok| saved += usize::from(ok)) + .unwrap(); assert_eq!(saved, 0); assert!(card_files(dir.path()).is_empty()); @@ -279,7 +348,9 @@ fn one_failed_card_portrait_does_not_stop_the_others() { tracker.refresh_champions().unwrap(); let mut saved = 0; - tracker.refresh_card_portraits(&mut || saved += 1).unwrap(); + tracker + .refresh_card_portraits(&mut |ok| saved += usize::from(ok)) + .unwrap(); assert_eq!(saved, 5); assert!(!card_files(dir.path()).contains(&"Jinx.jpg".to_string())); @@ -297,7 +368,7 @@ fn refreshing_card_portraits_without_a_champion_source_does_nothing() { let dir = tempfile::tempdir().unwrap(); let tracker = open_tracker(dir.path(), &[]); - tracker.refresh_card_portraits(&mut || {}).unwrap(); + tracker.refresh_card_portraits(&mut |_| {}).unwrap(); assert!(!dir.path().join("portraits").exists()); } diff --git a/crates/core/tests/common/mod.rs b/crates/core/tests/common/mod.rs index 0e3a944..070650d 100644 --- a/crates/core/tests/common/mod.rs +++ b/crates/core/tests/common/mod.rs @@ -407,7 +407,7 @@ pub struct FakeChampions { catalog_calls: Arc, /// What every card portrait download delivers. card_art: Vec, - /// The card portrait downloads fail while this is set. + /// The card portrait downloads fail with a network error while this is set. card_failure: Arc, card_calls: Arc, } @@ -511,9 +511,12 @@ impl ChampionSource for FakeChampions { fn card_portrait(&self, key: &str) -> Result, SourceError> { self.card_calls.fetch_add(1, Ordering::SeqCst); self.check()?; - if self.card_failure.load(Ordering::SeqCst) || self.no_portrait.iter().any(|k| k == key) { + if self.card_failure.load(Ordering::SeqCst) { return Err(SourceError::Network("coupé".into())); } + if self.no_portrait.iter().any(|k| k == key) { + return Err(SourceError::NotFound); + } Ok(self.card_art.clone()) } }