From c9f5b264e6d696316a72587d4e6e0c7227138d75 Mon Sep 17 00:00:00 2001
From: Nessar
Date: Tue, 17 Nov 2026 19:57:42 +0100
Subject: [PATCH] Compute statistics on a background worker instead of
deferring them (#29)
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
---
crates/app/src/stats_page.rs | 122 +++++++++++++++++++++++++++--------
crates/app/src/worker.rs | 103 +++++++++++++++++++++++++++--
2 files changed, 191 insertions(+), 34 deletions(-)
diff --git a/crates/app/src/stats_page.rs b/crates/app/src/stats_page.rs
index d8671c4..f6047f2 100644
--- a/crates/app/src/stats_page.rs
+++ b/crates/app/src/stats_page.rs
@@ -20,7 +20,7 @@ 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};
+use crate::worker::{Msg, RefreshGate, spawn_refresh, spawn_statistics};
const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats";
@@ -62,15 +62,16 @@ pub struct StatsPage {
last_active: Option,
/// The Account the user picked instead of following the one being updated.
pinned: Option,
- /// The Account whose statistics are in `stats`.
+ /// The Account of the last requested statistics.
shown: Option,
progress: Option,
refresh: RefreshGate,
+ stats_job: RefreshGate,
+ stats_generation: u64,
/// Until the follower's first round ends.
pending_round: bool,
crashed: bool,
last_reload: Instant,
- reload_when_shown: bool,
current_season: Option,
season: SeasonScope,
format: Option,
@@ -146,13 +147,6 @@ impl StatsPage {
cx.new(|cx| TableState::new(ChampionTable::new(), window, cx).col_movable(false));
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(
&account_select,
window,
@@ -222,10 +216,11 @@ impl StatsPage {
shown: None,
progress: None,
refresh: RefreshGate::default(),
+ stats_job: RefreshGate::default(),
+ stats_generation: 0,
pending_round: following,
crashed: false,
last_reload: Instant::now(),
- reload_when_shown: false,
current_season,
season,
format: None,
@@ -299,10 +294,10 @@ impl StatsPage {
Msg::Progress(progress) => {
self.progress = Some(progress);
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 } => {
// A follower round that changes nothing shown must not rebuild the page (they keep coming).
let unchanged = status == self.status
@@ -318,19 +313,34 @@ impl StatsPage {
self.progress = None;
self.crashed = false;
if reload {
- self.reload_if_shown(window, cx);
+ self.reload_in_background(window, cx);
}
}
Msg::Refreshed(status) => {
self.status = status;
self.progress = None;
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.
if self.refresh.finished() {
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 => {
self.refresh.reset();
self.pending_round = false;
@@ -341,19 +351,22 @@ impl StatsPage {
cx.notify();
}
- /// A worker's reload, deferred while GPUI reports the window hidden (minimised or not shown;
- /// on Windows a covered window still counts as visible), then run as soon as it is shown again
- /// (rule #1, budget 3).
- fn reload_if_shown(&mut self, window: &mut Window, cx: &mut Context) {
- if window.is_visible() {
- self.reload(window, cx);
- } else {
- self.reload_when_shown = true;
- }
+ /// A worker's reload: the Accounts now, the statistics on a below-normal worker, so neither a
+ /// visible nor a hidden window waits for them (rule #1).
+ fn reload_in_background(&mut self, window: &mut Window, cx: &mut Context) {
+ self.reload_accounts(window, cx);
+ let start_job = self.stats_job.request();
+ self.recompute_in_background(start_job, window, cx);
}
/// Re-reads the Accounts, then the statistics of the one shown.
fn reload(&mut self, window: &mut Window, cx: &mut Context) {
+ 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.accounts = self.tracker.accounts().unwrap_or_default();
self.last_active = self.tracker.last_active_account().ok().flatten();
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);
}
});
- self.recompute(window, cx);
}
- /// Recomputes the statistics for the current scope; never called while rendering.
- fn recompute(&mut self, window: &mut Window, cx: &mut Context) {
+ /// Settles the scope of the next statistics. Earlier results become stale when they are
+ /// 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,
+ ) -> Option {
self.last_reload = Instant::now();
if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
@@ -392,6 +411,9 @@ impl StatsPage {
self.filter = StateFilter::All;
}
let viewed = self.viewed().map(|a| a.puuid.clone());
+ if computing || viewed != self.shown {
+ self.stats_generation += 1;
+ }
if viewed != self.shown {
// Another Account may not have played the selected Format.
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,
+ ) {
+ 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) {
+ let viewed = self.prepare_statistics(true, window, cx);
self.stats = None;
self.stats_error = None;
self.stored = None;
@@ -415,6 +478,11 @@ impl StatsPage {
}
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) {
let mut names = vec![SharedString::from(ALL_FORMATS)];
names.extend(
self.stats
diff --git a/crates/app/src/worker.rs b/crates/app/src/worker.rs
index e4fd675..f5fb2aa 100644
--- a/crates/app/src/worker.rs
+++ b/crates/app/src/worker.rs
@@ -1,12 +1,12 @@
-//! Background threads: following the game client, and the refresh button.
-//! Both talk to the page through `Msg`.
+//! Background threads: following the game client, refreshing and computing statistics.
+//! They talk to the page through `Msg`.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::thread;
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;
pub enum Msg {
@@ -18,12 +18,17 @@ pub enum Msg {
Round { status: Status, reload: bool },
/// A refresh ended.
Refreshed(Status),
+ /// Statistics for a requested scope were computed.
+ Statistics {
+ generation: u64,
+ stats: Result,
+ stored: Option,
+ },
/// A worker thread panicked.
Crashed,
}
-/// At most one refresh thread at a time. A request made while one runs is served once, when it
-/// reports back: the sync it was waiting for may have started before the reason for it.
+/// At most one job at a time. A request made while one runs is served once, when it reports back.
#[derive(Default)]
pub struct RefreshGate {
running: bool,
@@ -35,7 +40,7 @@ impl RefreshGate {
self.running
}
- /// True when a refresh thread must start now.
+ /// True when a job must start now.
pub fn request(&mut self) -> bool {
if self.running {
self.queued = true;
@@ -45,7 +50,7 @@ impl RefreshGate {
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 {
self.running = std::mem::take(&mut self.queued);
self.running
@@ -135,8 +140,42 @@ pub fn spawn_refresh(tracker: Arc, tx: Sender) {
});
}
+/// Computes the statistics of `puuid` for `scope` on a below-normal worker.
+pub fn spawn_statistics(
+ tracker: Arc,
+ puuid: String,
+ scope: Scope,
+ generation: u64,
+ tx: Sender,
+) {
+ 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)]
mod tests {
+ use std::path::Path;
+
+ use arena_tracker_core::{RiotApi, SeasonScope};
use gpui_kit::base::async_util::unbounded;
use super::*;
@@ -154,6 +193,56 @@ mod tests {
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]
fn a_request_while_a_refresh_runs_waits_for_it_and_is_served_once() {
let mut gate = RefreshGate::default();