//! What the service knows right now, and how it is kept up to date. use std::ffi::{OsStr, OsString}; use std::io::{ErrorKind, Read}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::thread; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use sccache_dash_api::{Range, View}; use serde_json::Value; use wait_timeout::ChildExt; use crate::history::{self, Reading}; use crate::stats::{self, Counters, Snapshot}; use crate::view; /// How often sccache is asked for its counters. pub const POLL: Duration = Duration::from_secs(10); /// A line is saved when the counters change, and at least this often besides, so that time /// with the service running can be told from time it was not. pub const HEARTBEAT_SECS: i64 = 600; /// Never more than one saved line per minute. pub const MIN_LINE_SECS: i64 = 60; /// A sccache command that takes longer than this counts as failed. const COMMAND_TIMEOUT: Duration = Duration::from_secs(20); const PRUNE_EVERY: Duration = Duration::from_secs(86_400); pub struct Config { /// The sccache command the service runs. pub sccache: OsString, /// Where the history is saved. pub history: PathBuf, } impl Config { /// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset); the history /// lives in `$XDG_DATA_HOME/sccache-dash`. pub fn from_env() -> Result { let sccache = std::env::var_os("SCCACHE_DASH_SCCACHE").unwrap_or_else(|| "sccache".into()); let dir = dirs::data_dir() .ok_or("cannot find the data directory ($XDG_DATA_HOME, or ~/.local/share)")?; Ok(Config { sccache, history: dir.join("sccache-dash").join("history.jsonl"), }) } } pub fn unix_now() -> i64 { SystemTime::now() .duration_since(UNIX_EPOCH) .map_or(0, |d| d.as_secs() as i64) } /// What happened between two consecutive saved readings, dated when the later one was taken. pub struct Interval { pub end: i64, /// sccache's counters went back to zero in this interval. pub reset: bool, pub delta: Counters, } /// The last reading sccache answered. pub struct Live { pub at: i64, pub snapshot: Snapshot, /// sccache's output, exactly as it printed it. pub raw_text: String, } #[derive(Default)] pub struct State { /// The saved readings, oldest first. pub readings: Vec, /// One per reading after the first. pub intervals: Vec, pub live: Option, /// sccache's output of the last good reading, as JSON. pub raw: Option, pub client_version: Option, /// Why there is no live reading. pub error: Option, /// Whether a failure to save has already been reported. pub warned: bool, } impl State { /// Adds a reading to the end of the history, with what changed since the one before it. pub fn push(&mut self, reading: Reading) { if let Some(last) = self.readings.last() { let (delta, reset) = reading.c.since(&last.c); self.intervals.push(Interval { end: reading.t, reset, delta, }); } self.readings.push(reading); } /// Works out again what changed between the saved readings, after they were pruned. pub fn relink(&mut self) { self.intervals = self .readings .windows(2) .map(|w| { let (delta, reset) = w[1].c.since(&w[0].c); Interval { end: w[1].t, reset, delta, } }) .collect(); } } pub struct App { pub cfg: Config, state: Mutex, pruned: Mutex, } impl App { /// Loads the saved history, deleting what is older than 30 days. pub fn new(cfg: Config, now: i64) -> Result { let mut state = State { readings: history::load(&cfg.history), ..State::default() }; history::prune(&mut state.readings, &cfg.history, now) .map_err(|e| format!("cannot prune {}: {e}", cfg.history.display()))?; state.relink(); let pruned = Mutex::new(Instant::now()); Ok(App { cfg, state: Mutex::new(state), pruned, }) } pub fn lock(&self) -> MutexGuard<'_, State> { self.state.lock().unwrap_or_else(PoisonError::into_inner) } pub fn view(&self, range: Range) -> View { view::build(&self.lock(), range, unix_now()) } pub fn poll(&self) { self.poll_at(unix_now()); } /// Asks sccache for its counters and version, and saves a line when one is due. pub fn poll_at(&self, now: i64) { let version = run(&self.cfg.sccache, &["--version"]) .ok() .and_then(|text| { text.split_whitespace() .find(|w| w.starts_with(|c: char| c.is_ascii_digit())) .map(str::to_owned) }); let read = run( &self.cfg.sccache, &["--show-stats", "--stats-format", "json"], ) .and_then(|text| stats::parse(&text).map(|snapshot| (text, snapshot))); let mut state = self.lock(); state.client_version = version; match read { Ok((text, snapshot)) => { let live = Live { at: now, snapshot, raw_text: text, }; state.raw = serde_json::from_str(&live.raw_text).ok(); let due = match state.readings.last() { None => true, Some(last) => { last.c != live.snapshot.counters || now - last.t >= HEARTBEAT_SECS } }; let too_soon = state .readings .last() .is_some_and(|last| now - last.t < MIN_LINE_SECS); state.error = None; state.live = Some(live); if due && !too_soon { self.save(&mut state, now); } } Err(e) => { state.error = Some(e); state.live = None; state.raw = None; } } } fn save(&self, state: &mut State, now: i64) { let reading = Reading { t: now, c: state .live .as_ref() .map_or_else(Counters::default, |l| l.snapshot.counters.clone()), }; match history::append(&self.cfg.history, &reading) { Ok(()) => state.push(reading), Err(e) => { if !state.warned { state.warned = true; eprintln!( "sccache-dash: cannot save history to {}: {e}", self.cfg.history.display() ); } } } } /// Runs `sccache --zero-stats`; the saved history stays as it is. pub fn zero(&self) -> Result<(), String> { run(&self.cfg.sccache, &["--zero-stats"])?; self.poll(); Ok(()) } /// Asks sccache for its counters every [`POLL`] and prunes the history once a day, until /// the process ends. pub fn keep_updated(self: Arc) { thread::spawn(move || loop { self.poll(); let mut pruned = self.pruned.lock().unwrap_or_else(PoisonError::into_inner); if pruned.elapsed() >= PRUNE_EVERY { *pruned = Instant::now(); let mut state = self.lock(); match history::prune(&mut state.readings, &self.cfg.history, unix_now()) { Ok(_) => state.relink(), Err(e) if !state.warned => { state.warned = true; eprintln!( "sccache-dash: cannot prune {}: {e}", self.cfg.history.display() ); } Err(_) => {} } } thread::sleep(POLL); }); } } /// Runs sccache and returns what it printed; `Err` says why when it is missing, fails or hangs. fn run(sccache: &OsStr, args: &[&str]) -> Result { let mut child = Command::new(sccache) .args(args) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() .map_err(|e| match e.kind() { ErrorKind::NotFound => format!( "`{} {}`: command not found", sccache.to_string_lossy(), args.join(" ") ), _ => format!("`{} {}`: {e}", sccache.to_string_lossy(), args.join(" ")), })?; let named = format!("`{} {}`", sccache.to_string_lossy(), args.join(" ")); match child.wait_timeout(COMMAND_TIMEOUT) { Ok(Some(status)) if status.success() => {} Ok(Some(status)) => return Err(format!("{named} exited with {status}")), Ok(None) => { let _ = child.kill(); let _ = child.wait(); return Err(format!( "{named} did not answer within {} seconds", COMMAND_TIMEOUT.as_secs() )); } Err(e) => return Err(format!("{named}: {e}")), } let mut text = String::new(); if let Some(mut out) = child.stdout.take() { out.read_to_string(&mut text) .map_err(|e| format!("{named}: {e}"))?; } Ok(text) }