Compute statistics on a background worker instead of deferring them (#29)
CI / core (pull_request) Successful in 37s
CI / core (push) Successful in 45s

Reloads triggered by the workers no longer wait for the window to be
shown: the statistics and Match count are computed on a spawn_guarded
thread (below normal priority) and applied as soon as they arrive,
visible or not, so a restored window is up to date at once and the UI
thread computes nothing during an import. The Accounts are still read
on the UI thread; the old statistics stay shown until the new ones land.

One job runs at a time (RefreshGate); a generation number, bumped when
statistics are computed or the viewed Account changes, drops results
overtaken by a newer request or a user's selection. The job reports its
own panic as an error result, so another worker's crash never discards
it. User selections still recompute synchronously.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit was merged in pull request #36.
This commit is contained in:
nessarandClaude Opus 5.5 authored and nessar committed 2026-11-17 19:59:43 +01:00
1 parent 33343546a5
commit c9f5b264e6
2 files changed
+191 -34

No files matched your search

+95 -27
View File
@@ -20,7 +20,7 @@ use gpui_kit::*;
use crate::champion_table::ChampionTable; use crate::champion_table::ChampionTable;
use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, riot_id, sync_line}; use crate::text::{CLIENT_ABSENT, decimal, official_differs, official_note, riot_id, sync_line};
use crate::worker::{Msg, RefreshGate, spawn_refresh}; use crate::worker::{Msg, RefreshGate, spawn_refresh, spawn_statistics};
const ALL_SEASONS: &str = "Toutes les Saisons"; const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats"; const ALL_FORMATS: &str = "Tous les Formats";
@@ -62,15 +62,16 @@ pub struct StatsPage {
last_active: Option<Account>, last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated. /// The Account the user picked instead of following the one being updated.
pinned: Option<String>, pinned: Option<String>,
/// The Account whose statistics are in `stats`. /// The Account of the last requested statistics.
shown: Option<String>, shown: Option<String>,
progress: Option<SyncProgress>, progress: Option<SyncProgress>,
refresh: RefreshGate, refresh: RefreshGate,
stats_job: RefreshGate,
stats_generation: u64,
/// Until the follower's first round ends. /// Until the follower's first round ends.
pending_round: bool, pending_round: bool,
crashed: bool, crashed: bool,
last_reload: Instant, last_reload: Instant,
reload_when_shown: bool,
current_season: Option<String>, current_season: Option<String>,
season: SeasonScope, season: SeasonScope,
format: Option<Format>, format: Option<Format>,
@@ -146,13 +147,6 @@ impl StatsPage {
cx.new(|cx| TableState::new(ChampionTable::new(), window, cx).col_movable(false)); cx.new(|cx| TableState::new(ChampionTable::new(), window, cx).col_movable(false));
let subscriptions = vec![ let subscriptions = vec![
cx.observe_window_visibility(window, |this, visibility, window, cx| {
if visibility.is_visible() && this.reload_when_shown {
this.reload_when_shown = false;
this.reload(window, cx);
cx.notify();
}
}),
cx.subscribe_in( cx.subscribe_in(
&account_select, &account_select,
window, window,
@@ -222,10 +216,11 @@ impl StatsPage {
shown: None, shown: None,
progress: None, progress: None,
refresh: RefreshGate::default(), refresh: RefreshGate::default(),
stats_job: RefreshGate::default(),
stats_generation: 0,
pending_round: following, pending_round: following,
crashed: false, crashed: false,
last_reload: Instant::now(), last_reload: Instant::now(),
reload_when_shown: false,
current_season, current_season,
season, season,
format: None, format: None,
@@ -299,10 +294,10 @@ impl StatsPage {
Msg::Progress(progress) => { Msg::Progress(progress) => {
self.progress = Some(progress); self.progress = Some(progress);
if self.last_reload.elapsed() >= RELOAD_EVERY { if self.last_reload.elapsed() >= RELOAD_EVERY {
self.reload_if_shown(window, cx); self.reload_in_background(window, cx);
} }
} }
Msg::Champions => self.reload_if_shown(window, cx), Msg::Champions => self.reload_in_background(window, cx),
Msg::Round { status, reload } => { Msg::Round { status, reload } => {
// A follower round that changes nothing shown must not rebuild the page (they keep coming). // A follower round that changes nothing shown must not rebuild the page (they keep coming).
let unchanged = status == self.status let unchanged = status == self.status
@@ -318,19 +313,34 @@ impl StatsPage {
self.progress = None; self.progress = None;
self.crashed = false; self.crashed = false;
if reload { if reload {
self.reload_if_shown(window, cx); self.reload_in_background(window, cx);
} }
} }
Msg::Refreshed(status) => { Msg::Refreshed(status) => {
self.status = status; self.status = status;
self.progress = None; self.progress = None;
self.crashed = false; self.crashed = false;
self.reload_if_shown(window, cx); self.reload_in_background(window, cx);
// A request made while this one ran (a key saved meanwhile) is served now. // A request made while this one ran (a key saved meanwhile) is served now.
if self.refresh.finished() { if self.refresh.finished() {
spawn_refresh(self.tracker.clone(), self.tx.clone()); spawn_refresh(self.tracker.clone(), self.tx.clone());
} }
} }
Msg::Statistics {
generation,
stats,
stored,
} => {
if generation == self.stats_generation {
self.stats_error = stats.as_ref().err().cloned();
self.stats = stats.ok();
self.stored = stored;
self.show_statistics(window, cx);
}
if self.stats_job.finished() {
self.recompute_in_background(true, window, cx);
}
}
Msg::Crashed => { Msg::Crashed => {
self.refresh.reset(); self.refresh.reset();
self.pending_round = false; self.pending_round = false;
@@ -341,19 +351,22 @@ impl StatsPage {
cx.notify(); cx.notify();
} }
/// A worker's reload, deferred while GPUI reports the window hidden (minimised or not shown; /// A worker's reload: the Accounts now, the statistics on a below-normal worker, so neither a
/// on Windows a covered window still counts as visible), then run as soon as it is shown again /// visible nor a hidden window waits for them (rule #1).
/// (rule #1, budget 3). fn reload_in_background(&mut self, window: &mut Window, cx: &mut Context<Self>) {
fn reload_if_shown(&mut self, window: &mut Window, cx: &mut Context<Self>) { self.reload_accounts(window, cx);
if window.is_visible() { let start_job = self.stats_job.request();
self.reload(window, cx); self.recompute_in_background(start_job, window, cx);
} else {
self.reload_when_shown = true;
}
} }
/// Re-reads the Accounts, then the statistics of the one shown. /// Re-reads the Accounts, then the statistics of the one shown.
fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) { fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.reload_accounts(window, cx);
self.recompute(window, cx);
}
/// Re-reads the Accounts and selects the one shown.
fn reload_accounts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.accounts = self.tracker.accounts().unwrap_or_default(); self.accounts = self.tracker.accounts().unwrap_or_default();
self.last_active = self.tracker.last_active_account().ok().flatten(); self.last_active = self.tracker.last_active_account().ok().flatten();
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) { if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
@@ -380,11 +393,17 @@ impl StatsPage {
select.set_selected_value(puuid, window, cx); select.set_selected_value(puuid, window, cx);
} }
}); });
self.recompute(window, cx);
} }
/// Recomputes the statistics for the current scope; never called while rendering. /// Settles the scope of the next statistics. Earlier results become stale when they are
fn recompute(&mut self, window: &mut Window, cx: &mut Context<Self>) { /// computed again (`computing`) or when the viewed Account changed; a request merely queued
/// behind a running job keeps that job's result for the same scope.
fn prepare_statistics(
&mut self,
computing: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<String> {
self.last_reload = Instant::now(); self.last_reload = Instant::now();
if matches!(self.season, SeasonScope::AllSeasons) if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed) && !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
@@ -392,6 +411,9 @@ impl StatsPage {
self.filter = StateFilter::All; self.filter = StateFilter::All;
} }
let viewed = self.viewed().map(|a| a.puuid.clone()); let viewed = self.viewed().map(|a| a.puuid.clone());
if computing || viewed != self.shown {
self.stats_generation += 1;
}
if viewed != self.shown { if viewed != self.shown {
// Another Account may not have played the selected Format. // Another Account may not have played the selected Format.
self.shown = viewed.clone(); self.shown = viewed.clone();
@@ -401,6 +423,47 @@ impl StatsPage {
}); });
} }
} }
viewed
}
/// Requests the statistics from a worker (`start_job`: none is running), or shows none when no
/// Account is viewed.
fn recompute_in_background(
&mut self,
start_job: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
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,
};
// A below-normal worker keeps hidden and visible windows responsive (rule #1).
spawn_statistics(
self.tracker.clone(),
puuid,
scope,
self.stats_generation,
self.tx.clone(),
);
}
} else {
if start_job {
self.stats_job.reset();
}
self.stats = None;
self.stats_error = None;
self.stored = None;
self.show_statistics(window, cx);
}
}
/// Recomputes the statistics for the current scope; never called while rendering.
fn recompute(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let viewed = self.prepare_statistics(true, window, cx);
self.stats = None; self.stats = None;
self.stats_error = None; self.stats_error = None;
self.stored = None; self.stored = None;
@@ -415,6 +478,11 @@ impl StatsPage {
} }
self.stored = self.tracker.match_count(puuid).ok(); self.stored = self.tracker.match_count(puuid).ok();
} }
self.show_statistics(window, cx);
}
/// Shows `stats`: the Format choices and the table.
fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let mut names = vec![SharedString::from(ALL_FORMATS)]; let mut names = vec![SharedString::from(ALL_FORMATS)];
names.extend( names.extend(
self.stats self.stats
+96 -7
View File
@@ -1,12 +1,12 @@
//! Background threads: following the game client, and the refresh button. //! Background threads: following the game client, refreshing and computing statistics.
//! Both talk to the page through `Msg`. //! They talk to the page through `Msg`.
use std::panic::{AssertUnwindSafe, catch_unwind}; use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc; use std::sync::Arc;
use std::thread; use std::thread;
use std::time::{SystemTime, UNIX_EPOCH}; use std::time::{SystemTime, UNIX_EPOCH};
use arena_tracker_core::{Status, SyncProgress, Tracker}; use arena_tracker_core::{Scope, Statistics, Status, SyncProgress, Tracker};
use gpui_kit::base::async_util::Sender; use gpui_kit::base::async_util::Sender;
pub enum Msg { pub enum Msg {
@@ -18,12 +18,17 @@ pub enum Msg {
Round { status: Status, reload: bool }, Round { status: Status, reload: bool },
/// A refresh ended. /// A refresh ended.
Refreshed(Status), Refreshed(Status),
/// Statistics for a requested scope were computed.
Statistics {
generation: u64,
stats: Result<Statistics, String>,
stored: Option<usize>,
},
/// A worker thread panicked. /// A worker thread panicked.
Crashed, Crashed,
} }
/// At most one refresh thread at a time. A request made while one runs is served once, when it /// At most one job at a time. A request made while one runs is served once, when it reports back.
/// reports back: the sync it was waiting for may have started before the reason for it.
#[derive(Default)] #[derive(Default)]
pub struct RefreshGate { pub struct RefreshGate {
running: bool, running: bool,
@@ -35,7 +40,7 @@ impl RefreshGate {
self.running self.running
} }
/// True when a refresh thread must start now. /// True when a job must start now.
pub fn request(&mut self) -> bool { pub fn request(&mut self) -> bool {
if self.running { if self.running {
self.queued = true; self.queued = true;
@@ -45,7 +50,7 @@ impl RefreshGate {
true true
} }
/// The running refresh reported back; true when the queued one must start now. /// The running job reported back; true when the queued one must start now.
pub fn finished(&mut self) -> bool { pub fn finished(&mut self) -> bool {
self.running = std::mem::take(&mut self.queued); self.running = std::mem::take(&mut self.queued);
self.running self.running
@@ -135,8 +140,42 @@ pub fn spawn_refresh(tracker: Arc<Tracker>, tx: Sender<Msg>) {
}); });
} }
/// Computes the statistics of `puuid` for `scope` on a below-normal worker.
pub fn spawn_statistics(
tracker: Arc<Tracker>,
puuid: String,
scope: Scope,
generation: u64,
tx: Sender<Msg>,
) {
spawn_guarded(tx, move |tx| {
// A panic is reported as this job's result, not as `Crashed`: the page's statistics job
// must end with a result whatever happens, and a crash banner is for the other workers.
let (stats, stored) = catch_unwind(AssertUnwindSafe(|| {
let stats = tracker
.statistics(&puuid, &scope)
.map_err(|e| format!("Statistiques indisponibles : {e}"));
(stats, tracker.match_count(&puuid).ok())
}))
.unwrap_or_else(|_| {
(
Err("Statistiques indisponibles : erreur interne".into()),
None,
)
});
let _ = tx.try_send(Msg::Statistics {
generation,
stats,
stored,
});
});
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::path::Path;
use arena_tracker_core::{RiotApi, SeasonScope};
use gpui_kit::base::async_util::unbounded; use gpui_kit::base::async_util::unbounded;
use super::*; use super::*;
@@ -154,6 +193,56 @@ mod tests {
assert!(gpui_kit::block_on(rx.recv()).is_err()); assert!(gpui_kit::block_on(rx.recv()).is_err());
} }
#[test]
fn statistics_workers_deliver_the_generation_count_and_errors() {
let tracker = Arc::new(
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
);
let (tx, rx) = unbounded();
spawn_statistics(
tracker.clone(),
"account".into(),
Scope {
season: SeasonScope::AllSeasons,
format: None,
},
42,
tx.clone(),
);
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::Statistics {
generation: 42,
stats: Ok(stats),
stored: Some(0),
}) if stats.rows.is_empty() && stats.challenge.is_none()
));
spawn_statistics(
tracker,
"account".into(),
Scope {
season: SeasonScope::Season("missing".into()),
format: None,
},
43,
tx,
);
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::Statistics {
generation: 43,
stats: Err(error),
stored: Some(0),
}) if error.starts_with("Statistiques indisponibles : ")
));
}
#[test] #[test]
fn a_request_while_a_refresh_runs_waits_for_it_and_is_served_once() { fn a_request_while_a_refresh_runs_waits_for_it_and_is_served_once() {
let mut gate = RefreshGate::default(); let mut gate = RefreshGate::default();