Files
arena-tracker/crates/app/src/worker.rs
T

323 lines
10 KiB
Rust

//! 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::{
ChampSelect, ClientError, Scope, Statistics, Status, SyncProgress, Tracker,
};
use gpui_kit::base::async_util::Sender;
pub type Selection = Option<Result<(String, ChampSelect), ClientError>>;
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,
},
/// 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(tx: Sender<Msg>, on_panic: Msg, body: impl FnOnce(&Sender<Msg>) + 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 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<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 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;
for () in rounds {
let changed = history.follow_client(now_ms(), fallback, &mut |progress| {
let _ = tx.try_send(Msg::Progress(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 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();
}
});
}
/// 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);
}
}