Files
arena-tracker/crates/app/src/worker.rs
T
nessarandClaude Opus 5.5 8e12abf7f4
CI / core (pull_request) Successful in 35s
CI / core (push) Successful in 1m16s
Choose the update channel and download authenticated updates (#58)
The settings offer Stable or Bêta. The choice is saved only once made;
until then the installed version's channel applies, so the beta
installer follows Bêta. Updates never change a saved choice.

Each launch, and each channel change, runs one check on a below-normal
thread. It lists the channel's Releases through the public Gitea API
(betas are pre-releases) and takes the highest version above the
installed one. The package is downloaded into
%LOCALAPPDATA%\arena-tracker\updates\partial, verified with
verify_release, then kept as <channel>-<version>; another channel's
package is removed before any network access. Only then does a green
title-bar button show « Mise à jour prête » and open the settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:25 +01:00

372 lines
12 KiB
Rust

//! Background threads: following the game client, refreshing, computing statistics and
//! downloading updates. They talk to the page through `Msg`, and to the settings through
//! `UpdateChecked`.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use arena_tracker_core::{
ChampSelect, ClientEvent, Scope, Statistics, Status, SyncProgress, Tracker, UpdateChannel,
};
use gpui_kit::base::async_util::Sender;
/// The signed-in Riot ID and its pick, or none outside an Arena champ select.
pub type LiveChampSelect = Option<(String, ChampSelect)>;
pub enum Msg {
ChampSelect(LiveChampSelect),
/// 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,
},
/// A refresh ended.
Refreshed(Status),
/// Statistics for a requested scope were computed.
Statistics {
generation: u64,
stats: Result<Statistics, String>,
stored: Option<usize>,
},
/// A worker thread panicked.
Crashed,
/// The refresh worker panicked.
RefreshCrashed,
}
/// 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,
queued: bool,
}
impl RefreshGate {
pub fn running(&self) -> bool {
self.running
}
/// True when a job must start now.
pub fn request(&mut self) -> bool {
if self.running {
self.queued = true;
return false;
}
self.running = true;
true
}
/// 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
}
/// A thread panicked: nothing is known to run any more.
pub fn reset(&mut self) {
*self = RefreshGate::default();
}
}
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
#[cfg(windows)]
const THREAD_PRIORITY_BELOW_NORMAL: i32 = -1;
#[cfg(windows)]
#[link(name = "kernel32")]
unsafe extern "system" {
fn GetCurrentThread() -> *mut core::ffi::c_void;
fn SetThreadPriority(thread: *mut core::ffi::c_void, priority: i32) -> i32;
#[cfg(test)]
fn GetThreadPriority(thread: *mut core::ffi::c_void) -> i32;
}
/// Lowers the calling thread's priority: background work must not take CPU from the game or the
/// UI (rule #1, budget 5). Best effort: on failure the work still runs.
// shortcut: ureq starts a short DNS thread per request (the core's agents set a timeout) and it
// runs at normal priority; resolve on the calling thread if those threads ever show up in a profile.
fn lower_priority() {
#[cfg(windows)]
unsafe {
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
}
}
/// Runs `body` on its own thread; a panic is reported instead of leaving the page waiting.
fn spawn_guarded<T: Send + 'static>(
tx: Sender<T>,
on_panic: T,
body: impl FnOnce(&Sender<T>) + Send + 'static,
) {
thread::spawn(move || {
lower_priority();
if catch_unwind(AssertUnwindSafe(|| body(&tx))).is_err() {
let _ = tx.try_send(on_panic);
}
});
}
/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds
/// 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.
pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sender<Msg>) {
let champions = tracker.clone();
spawn_guarded(tx.clone(), Msg::Crashed, move |tx| {
let _ = champions.refresh_champions();
let _ = tx.try_send(Msg::Champions);
});
// 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 {
// 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 = history.follow_client_with(now_ms(), fallback, &snapshot, &mut progress);
if tx
.try_send(Msg::Round {
status: history.status(),
reload: changed || first,
})
.is_err()
{
break;
}
first = false;
}
});
spawn_guarded(tx, Msg::Crashed, move |tx| {
let mut previous = None;
let mut snapshot = tracker.client_snapshot();
let mut needs_snapshot = true;
while !tx.is_closed() {
// 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(()),
Err(std::sync::mpsc::TrySendError::Disconnected(()))
) {
break;
}
}
match tracker.champ_select_with(&snapshot) {
Ok(champ_select) if champ_select != previous => {
if tx.try_send(Msg::ChampSelect(champ_select.clone())).is_err() {
break;
}
previous = champ_select;
}
Ok(_) => {}
// A failed read is not the champ select ending: keep what the page shows.
Err(_) => {}
}
// 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();
}
}
});
}
/// What an update check for `channel` kept ready: the version, if any.
pub struct UpdateChecked {
pub channel: UpdateChannel,
pub ready: Option<String>,
}
/// Downloads and authenticates the newest release of `channel`, as one below-normal thread.
pub fn spawn_update_check(channel: UpdateChannel, tx: Sender<UpdateChecked>) {
let crashed = UpdateChecked {
channel,
ready: None,
};
spawn_guarded(tx, crashed, move |tx| {
let ready = crate::release::download_update(channel);
let _ = tx.try_send(UpdateChecked { channel, ready });
});
}
/// The refresh button: one sync of the Account being kept up to date.
pub fn spawn_refresh(tracker: Arc<Tracker>, tx: Sender<Msg>) {
spawn_guarded(tx, Msg::RefreshCrashed, move |tx| {
// A failure is recorded in the status, which the page shows as a banner.
let _ = tracker.refresh(&mut |progress| {
let _ = tx.try_send(Msg::Progress(progress));
});
let _ = tx.try_send(Msg::Refreshed(tracker.status()));
});
}
/// 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, Msg::Crashed, 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::*;
#[test]
fn guarded_workers_deliver_messages_and_report_panics() {
let (tx, rx) = unbounded();
spawn_guarded(tx.clone(), Msg::Crashed, |tx| {
let _ = tx.try_send(Msg::Champions);
});
assert!(matches!(gpui_kit::block_on(rx.recv()), Ok(Msg::Champions)));
spawn_guarded(tx, Msg::RefreshCrashed, |_| panic!("worker panic"));
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::RefreshCrashed)
));
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();
assert!(gate.request());
assert!(gate.running());
assert!(!gate.request());
assert!(!gate.request());
// The running one ends: one queued refresh starts, however many were asked.
assert!(gate.finished());
assert!(gate.running());
assert!(!gate.finished());
assert!(!gate.running());
assert!(gate.request());
}
#[test]
fn a_crash_forgets_the_queue() {
let mut gate = RefreshGate::default();
assert!(gate.request());
assert!(!gate.request());
gate.reset();
assert!(!gate.running());
assert!(!gate.finished());
}
#[cfg(windows)]
#[test]
fn guarded_threads_run_below_normal_priority() {
let (tx, _rx) = unbounded();
let (priority_tx, priority_rx) = std::sync::mpsc::channel();
spawn_guarded(tx, Msg::Crashed, move |_| {
let priority = unsafe { GetThreadPriority(GetCurrentThread()) };
priority_tx.send(priority).unwrap();
});
assert_eq!(priority_rx.recv().unwrap(), THREAD_PRIORITY_BELOW_NORMAL);
}
}