diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..1b5ec8b --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..6e42efe --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 sccache-dash contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..3f481b7 --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +# sccache-dash + +A small Linux program in the manner of Syncthing: one binary that watches the local +[sccache](https://github.com/mozilla/sccache) compiler cache, remembers what it did, and serves +a dashboard for it at . It listens on this machine only. + +It asks sccache for its counters every 10 seconds, works out hit rates, time saved and what looks +wrong, and sends the page one `View` to draw (the contract is `crates/api`). + +## Install + +``` +just build # builds the page (trunk) and then the server +sccache-dash # serves http://127.0.0.1:8226 and opens it +sccache-dash install # the same, as a systemd user service that starts at login +sccache-dash uninstall +``` + +`sccache-dash [--port N] [--no-open]` serves. `install` writes +`~/.config/systemd/user/sccache-dash.service` with the absolute path of the binary and the `PATH` +of the shell that ran it, so that `sccache` is found; the service never opens a browser. + +`SCCACHE_DASH_SCCACHE` names the sccache command when it is not simply `sccache` on `PATH`. + +Until the page has been built (`crates/ui/dist`), the server serves a placeholder saying so; its +API answers either way. + +## Routes + +| Route | What it does | +| --- | --- | +| `GET /api/view?range=1h\|24h\|7d\|30d\|reset` | one `View`: totals, the period before, timing, time saved, languages, buckets, problems, a summary | +| `GET /api/export` | sccache's current stats exactly as `sccache --show-stats --stats-format json` prints them, as a download | +| `POST /api/zero` | runs `sccache --zero-stats`; the saved history is kept | +| `GET /` | the page | + +`/api/zero` is refused unless the request's `Host` is localhost and, when it has an `Origin`, +that origin is this server, so a web page elsewhere cannot zero the stats. + +## Where history lives + +`$XDG_DATA_HOME/sccache-dash/history.jsonl` (`~/.local/share/...` by default): one compact JSON +line per reading, oldest first, at most one a minute and only when sccache's counters changed, +plus one every ten minutes so that time with the service running can be told from time it was +not. A reading is a few hundred bytes. Lines older than 30 days are deleted at startup and once +a day. Deleting the file loses the history and nothing else. + +A counter that goes down means sccache reset its counters (`--zero-stats`, or its server +restarted): the range counts start again from zero there and the chart marks the spot. The first +reading ever is a baseline and counts for nothing. + +## Notes on sccache + +While sccache's server is running, being asked for its stats every 10 seconds keeps it from its +10-minute idle shutdown. When it is not running, `sccache --show-stats` does not start it (it +prints empty counters) and neither does this program; the next compile starts it, as usual. + +## Licence + +MIT or Apache-2.0, at your choice (`LICENSE-MIT`, `LICENSE-APACHE`). diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml new file mode 100644 index 0000000..1a44c78 --- /dev/null +++ b/crates/server/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "sccache-dash" +description = "Records sccache's counters and serves a dashboard for them on localhost" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +sccache-dash-api = { path = "../api" } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tiny_http = "0.12" +wait-timeout = "0.2" +dirs = "6" +include_dir = "0.7" + +[dev-dependencies] +tempfile = "3" diff --git a/crates/server/build.rs b/crates/server/build.rs new file mode 100644 index 0000000..1ab3603 --- /dev/null +++ b/crates/server/build.rs @@ -0,0 +1,37 @@ +//! Puts the page into the binary. The page is what `trunk build --release` writes to +//! `crates/ui/dist`; until it has been built, a placeholder page stands in for it. + +use std::path::Path; + +const PLACEHOLDER: &str = " + +sccache-dash + +

The sccache dashboard page is not built

+

The server is running and its API answers, but the page +that draws it is missing. Run just build in the repository (it runs +trunk build --release in crates/ui) and start sccache-dash again. +"; + +fn main() { + let crates = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()) + .parent() + .expect("crates/server has a parent") + .to_path_buf(); + let dist = crates.join("ui").join("dist"); + // Checked on every build, so the page is picked up as soon as `trunk build` has made it. + println!( + "cargo:rerun-if-changed={}", + dist.join("index.html").display() + ); + + let site = if dist.join("index.html").is_file() { + dist + } else { + let out = Path::new(&std::env::var("OUT_DIR").unwrap()).join("site"); + std::fs::create_dir_all(&out).unwrap(); + std::fs::write(out.join("index.html"), PLACEHOLDER).unwrap(); + out + }; + println!("cargo:rustc-env=DASH_SITE={}", site.display()); +} diff --git a/crates/server/src/app.rs b/crates/server/src/app.rs new file mode 100644 index 0000000..b265a1e --- /dev/null +++ b/crates/server/src/app.rs @@ -0,0 +1,295 @@ +//! 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) +} diff --git a/crates/server/src/history.rs b/crates/server/src/history.rs new file mode 100644 index 0000000..b63cc75 --- /dev/null +++ b/crates/server/src/history.rs @@ -0,0 +1,184 @@ +//! The saved history: one compact JSON line per reading, oldest first. + +use std::fs::OpenOptions; +use std::io::{self, Write}; +use std::path::Path; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::stats::Counters; + +/// Readings older than this are deleted. +pub const KEEP_DAYS: i64 = 30; + +/// sccache's counters at one moment. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Reading { + /// Unix seconds. + pub t: i64, + #[serde(default)] + pub c: Counters, +} + +/// The saved readings; a line that cannot be read is skipped, not fatal. +pub fn load(path: &Path) -> Vec { + std::fs::read_to_string(path) + .unwrap_or_default() + .lines() + .filter_map(read_line) + .collect() +} + +/// One saved line. A counter the line does not have (it was written by another version of this +/// program) reads as zero rather than making the whole line unreadable. +fn read_line(line: &str) -> Option { + let mut value: Value = serde_json::from_str(line).ok()?; + let defaults = serde_json::to_value(Counters::default()).ok()?; + if let Some(counters) = value.get_mut("c") { + fill_in(counters, &defaults); + } + serde_json::from_value(value).ok() +} + +/// Adds the keys of `defaults` that `value` lacks, recursively. +fn fill_in(value: &mut Value, defaults: &Value) { + let (Some(value), Some(defaults)) = (value.as_object_mut(), defaults.as_object()) else { + return; + }; + for (key, default) in defaults { + match value.get_mut(key) { + None => { + value.insert(key.clone(), default.clone()); + } + Some(found) => fill_in(found, default), + } + } +} + +/// Adds one line to the end. +pub fn append(path: &Path, reading: &Reading) -> io::Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let mut line = serde_json::to_string(reading)?; + line.push('\n'); + OpenOptions::new() + .create(true) + .append(true) + .open(path)? + .write_all(line.as_bytes()) +} + +/// Deletes the readings older than [`KEEP_DAYS`], rewriting the file, and says how many went. +pub fn prune(readings: &mut Vec, path: &Path, now: i64) -> io::Result { + let cutoff = now - KEEP_DAYS * 86_400; + let keep = readings.iter().filter(|r| r.t >= cutoff).count(); + let removed = readings.len() - keep; + if removed == 0 { + return Ok(0); + } + readings.drain(..removed); + let mut text = String::new(); + for r in readings.iter() { + text.push_str(&serde_json::to_string(r)?); + text.push('\n'); + } + let tmp = path.with_extension("jsonl.tmp"); + std::fs::write(&tmp, text)?; + std::fs::rename(&tmp, path)?; + Ok(removed) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn reading(t: i64, requests: u64) -> Reading { + Reading { + t, + c: Counters { + totals: sccache_dash_api::Totals { + requests, + ..Default::default() + }, + ..Counters::default() + }, + } + } + + #[test] + fn old_lines_are_deleted_at_startup() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("history.jsonl"); + let (day, now) = (86_400, 1_764_000_000); + for (t, n) in [ + (now - 31 * day, 1), + (now - 30 * day + 3600, 2), + (now - 3600, 3), + (now, 4), + ] { + append(&path, &reading(t, n)).unwrap(); + } + + let mut readings = load(&path); + assert_eq!(readings.len(), 4); + assert_eq!(prune(&mut readings, &path, now).unwrap(), 1); + assert_eq!( + readings, + vec![ + reading(now - 30 * day + 3600, 2), + reading(now - 3600, 3), + reading(now, 4) + ] + ); + let text = std::fs::read_to_string(&path).unwrap(); + let lines: Vec<_> = text.lines().collect(); + assert_eq!(lines.len(), 3, "the file itself was rewritten"); + assert!(lines[0].contains("\"requests\":2")); + assert!( + !path.with_extension("jsonl.tmp").exists(), + "the temporary file is gone" + ); + + assert_eq!( + prune(&mut readings, &path, now).unwrap(), + 0, + "nothing more to delete" + ); + } + + #[test] + fn a_missing_or_damaged_file_is_not_fatal() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("nested").join("history.jsonl"); + assert!(load(&path).is_empty(), "no file yet"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write( + &path, + "{\"t\":1,\"c\":{\"totals\":{\"requests\":7}}}\nnot json\n{\"t\":2}\n", + ) + .unwrap(); + let readings = load(&path); + assert_eq!(readings.len(), 2, "the unreadable line is skipped"); + assert_eq!(readings[0].c.totals.requests, 7); + assert_eq!( + readings[1], + Reading { + t: 2, + c: Counters::default() + }, + "missing counters read as zero" + ); + assert_eq!( + prune(&mut readings.clone(), &path, 1_764_000_000).unwrap(), + 2, + "both are older than 30 days" + ); + assert_eq!( + std::fs::read_to_string(&path).unwrap(), + "", + "and the file is emptied" + ); + } +} diff --git a/crates/server/src/http.rs b/crates/server/src/http.rs new file mode 100644 index 0000000..b074fd9 --- /dev/null +++ b/crates/server/src/http.rs @@ -0,0 +1,235 @@ +//! The HTTP side: three routes and the page's files, on 127.0.0.1 only. + +use std::io::Cursor; +use std::net::SocketAddr; +use std::sync::Arc; +use std::thread; + +use include_dir::{include_dir, Dir}; +use sccache_dash_api::Range; +use serde_json::Value; +use tiny_http::{Header, Request, Response, Server}; + +use crate::app::App; +use crate::pretty; + +/// The page as `trunk build` wrote it to crates/ui/dist, or a placeholder saying it is not built +/// (the build script names the folder in `DASH_SITE`). +static SITE: Dir<'_> = include_dir!("$DASH_SITE"); + +type Reply = Response>>; + +/// Serves until the process ends. +pub fn serve(app: Arc, port: u16) -> Result<(), String> { + answer(listen(port)?, app); + Ok(()) +} + +/// Binds 127.0.0.1 and nothing else; port 0 picks a free one. +pub fn listen(port: u16) -> Result { + Server::http(SocketAddr::from(([127, 0, 0, 1], port))) + .map_err(|e| format!("cannot listen on 127.0.0.1:{port}: {e}")) +} + +/// The port a listening server answers on. +pub fn port_of(server: &Server) -> u16 { + server.server_addr().to_ip().map_or(0, |a| a.port()) +} + +/// Answers requests until the process ends. +pub fn answer(server: Server, app: Arc) { + let port = port_of(&server); + for mut request in server.incoming_requests() { + let app = Arc::clone(&app); + thread::spawn(move || { + let response = handle(&app, port, &mut request); + let _ = request.respond(response); + }); + } +} + +fn handle(app: &App, port: u16, req: &mut Request) -> Reply { + let url = req.url(); + let (path, query) = url.split_once('?').unwrap_or((url, "")); + match (req.method().as_str(), path) { + ("GET", "/api/view") => match range_of(query) { + Some(range) => reply( + 200, + "application/json", + serde_json::to_vec(&app.view(range)).unwrap_or_default(), + ) + .with_header(header("Cache-Control", "no-store")), + None => text(400, "unknown range: use 1h, 24h, 7d, 30d or reset"), + }, + ("GET" | "HEAD", "/api/export") => export(app), + ("POST", "/api/zero") => zero(app, port, req), + (_, "/api/zero") => text(405, "use POST"), + ("GET" | "HEAD", _) => site_file(path), + _ => text(404, "not found"), + } +} + +/// `range=24h` in the query string. +fn range_of(query: &str) -> Option { + let value = query.split('&').find_map(|p| p.strip_prefix("range="))?; + serde_json::from_value(Value::String(value.to_owned())).ok() +} + +/// sccache's output exactly as it printed it, as a download. +fn export(app: &App) -> Reply { + let state = app.lock(); + match &state.live { + Some(live) => reply(200, "application/json", live.raw_text.clone().into_bytes()) + .with_header(header( + "Content-Disposition", + &format!( + "attachment; filename=\"sccache-stats-{}.json\"", + pretty::stamp(live.at) + ), + )), + None => text( + 502, + &format!( + "sccache did not answer: {}", + state.error.as_deref().unwrap_or("no reading yet") + ), + ), + } +} + +/// Runs `sccache --zero-stats`. Only this machine's own dashboard may ask for that. +fn zero(app: &App, port: u16, req: &Request) -> Reply { + if !from_own_page(req, port) { + return text( + 403, + "refused: only the dashboard's own page, on this machine, may zero the stats", + ); + } + match app.zero() { + Ok(()) => text( + 200, + "sccache's counters were zeroed; the saved history is kept", + ), + Err(e) => text(502, &format!("could not zero the stats: {e}")), + } +} + +/// Whether a request comes from the dashboard itself: its `Host` is localhost, and when a web +/// page sent it (it carries an `Origin`) that page is this server. A page anywhere else must +/// not be able to zero the stats, and neither may a host name that merely resolves here. +fn from_own_page(req: &Request, port: u16) -> bool { + let header = |name: &'static str| { + req.headers() + .iter() + .find(|h| h.field.equiv(name)) + .map(|h| h.value.as_str()) + }; + // `name` or `name:port`, with a port made of digits and nothing else. + let host_is_local = |host: &str| { + let mut parts = host.splitn(2, ':'); + let name = parts.next().unwrap_or_default(); + let port = parts.next().unwrap_or(""); + (name.eq_ignore_ascii_case("127.0.0.1") || name.eq_ignore_ascii_case("localhost")) + && port.bytes().all(|b| b.is_ascii_digit()) + }; + let own_origins = [ + format!("http://127.0.0.1:{port}"), + format!("http://localhost:{port}"), + ]; + header("Host").is_some_and(host_is_local) + && header("Origin").is_none_or(|origin| own_origins.iter().any(|own| own == origin)) +} + +/// A file of the page; `/` is its index. +fn site_file(path: &str) -> Reply { + let name = path.trim_start_matches('/'); + let name = if name.is_empty() { "index.html" } else { name }; + match SITE.get_file(name) { + Some(file) => reply(200, content_type(name), file.contents().to_vec()), + None => text(404, "not found"), + } +} + +/// Content types by file extension, as the page's own files need them. +fn content_type(path: &str) -> &'static str { + match path.rsplit_once('.').map(|(_, ext)| ext) { + Some("html") => "text/html; charset=utf-8", + Some("js" | "mjs") => "text/javascript; charset=utf-8", + Some("wasm") => "application/wasm", + Some("css") => "text/css; charset=utf-8", + Some("json" | "map") => "application/json", + Some("svg") => "image/svg+xml", + Some("png") => "image/png", + Some("jpg" | "jpeg") => "image/jpeg", + Some("gif") => "image/gif", + Some("webp") => "image/webp", + Some("ico") => "image/x-icon", + Some("woff") => "font/woff", + Some("woff2") => "font/woff2", + Some("ttf") => "font/ttf", + Some("otf") => "font/otf", + Some("txt" | "md") => "text/plain; charset=utf-8", + _ => "application/octet-stream", + } +} + +fn header(name: &'static str, value: &str) -> Header { + Header::from_bytes(name.as_bytes(), value.as_bytes()).expect("a header made of plain ASCII") +} + +fn reply(code: u16, content_type: &str, body: Vec) -> Reply { + Response::from_data(body) + .with_status_code(code) + .with_header(header("Content-Type", content_type)) +} + +fn text(code: u16, body: &str) -> Reply { + reply(code, "text/plain; charset=utf-8", body.as_bytes().to_vec()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_page_or_its_placeholder_is_in_the_binary() { + assert!( + SITE.get_file("index.html").is_some(), + "`/` must answer with a page" + ); + assert!( + SITE.get_file("../Cargo.toml").is_none(), + "nothing outside the page is served" + ); + assert!(SITE.get_file("no-such-file").is_none()); + } + + #[test] + fn content_types_are_what_browsers_need() { + assert_eq!(content_type("index.html"), "text/html; charset=utf-8"); + assert_eq!( + content_type("app-a1b2c3.js"), + "text/javascript; charset=utf-8" + ); + assert_eq!(content_type("app-a1b2c3.wasm"), "application/wasm"); + assert_eq!(content_type("app.css"), "text/css; charset=utf-8"); + assert_eq!(content_type("icons/sccache.svg"), "image/svg+xml"); + assert_eq!(content_type("data"), "application/octet-stream"); + } + + #[test] + fn the_range_comes_from_the_query_string() { + for (query, expected) in [ + ("range=1h", Some(Range::Hour)), + ("range=24h", Some(Range::Day)), + ("range=7d", Some(Range::Week)), + ("range=30d", Some(Range::Month)), + ("range=reset", Some(Range::SinceReset)), + ("other=1&range=24h", Some(Range::Day)), + ("", None), + ("range=all", None), + ] { + assert_eq!(range_of(query), expected, "{query:?}"); + } + } +} diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs new file mode 100644 index 0000000..f5c7a43 --- /dev/null +++ b/crates/server/src/lib.rs @@ -0,0 +1,10 @@ +//! The server half of sccache-dash: it asks sccache for its counters, keeps their history and +//! serves the page that draws them. + +pub mod app; +pub mod history; +pub mod http; +pub mod pretty; +pub mod stats; +pub mod systemd; +pub mod view; diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs new file mode 100644 index 0000000..2b828a7 --- /dev/null +++ b/crates/server/src/main.rs @@ -0,0 +1,163 @@ +//! `sccache-dash`: serves the dashboard, or installs itself as a user service. + +use std::process::{Command as Process, Stdio}; +use std::sync::Arc; + +use sccache_dash::app::{unix_now, App, Config}; +use sccache_dash::{http, systemd}; + +const USAGE: &str = "\ +sccache-dash [--port N] [--no-open] serve the dashboard on http://127.0.0.1:8226 and open it +sccache-dash install start it at login, as a systemd user service +sccache-dash uninstall remove that service again"; + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if let Err(e) = run(&args) { + eprintln!("sccache-dash: {e}"); + std::process::exit(1); + } +} + +fn run(args: &[String]) -> Result<(), String> { + match parse(args)? { + Command::Help => println!("{USAGE}"), + Command::Install => systemd::install()?, + Command::Uninstall => systemd::uninstall()?, + Command::Serve { port, open } => serve(port, open)?, + } + Ok(()) +} + +/// What the command line asks for. +#[derive(Debug)] +enum Command { + Serve { port: u16, open: bool }, + Install, + Uninstall, + Help, +} + +fn parse(args: &[String]) -> Result { + let mut serve = Command::Serve { + port: sccache_dash_api::DEFAULT_PORT, + open: true, + }; + let mut i = 0; + while let Some(arg) = args.get(i) { + i += 1; + match arg.as_str() { + "--no-open" => { + if let Command::Serve { open, .. } = &mut serve { + *open = false; + } + } + "--help" | "-h" => return Ok(Command::Help), + "install" => return Ok(Command::Install), + "uninstall" => return Ok(Command::Uninstall), + a if a == "--port" || a.starts_with("--port=") => { + let value = match a.strip_prefix("--port=") { + Some(value) => value.to_owned(), + None => { + i += 1; + args.get(i - 1) + .ok_or("--port needs a number, as in --port 8226")? + .clone() + } + }; + let port = value + .parse() + .map_err(|_| format!("`{value}` is not a port number"))?; + if let Command::Serve { port: p, .. } = &mut serve { + *p = port; + } + } + a => return Err(format!("unknown argument `{a}`\n\n{USAGE}")), + } + } + Ok(serve) +} + +fn serve(port: u16, open: bool) -> Result<(), String> { + let app = Arc::new(App::new(Config::from_env()?, unix_now())?); + let server = http::listen(port)?; + let port = http::port_of(&server); + let url = format!("http://127.0.0.1:{port}"); + println!( + "sccache-dash: serving {url}, history in {}", + app.cfg.history.display() + ); + app.clone().keep_updated(); + if open { + // Left to finish on its own: a browser that will not open is not worth stopping for. + let browser = Process::new("xdg-open") + .arg(&url) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn(); + if let Ok(mut browser) = browser { + std::thread::spawn(move || { + let _ = browser.wait(); + }); + } + } + http::answer(server, app); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse_args(args: &[&str]) -> Result { + parse(&args.iter().map(|a| a.to_string()).collect::>()) + } + + #[test] + fn the_command_line() { + assert!(matches!( + parse_args(&[]), + Ok(Command::Serve { + port: 8226, + open: true + }) + )); + assert!(matches!( + parse_args(&["--port", "18226"]), + Ok(Command::Serve { + port: 18226, + open: true + }) + )); + assert!(matches!( + parse_args(&["--port=9000", "--no-open"]), + Ok(Command::Serve { + port: 9000, + open: false + }) + )); + assert!(matches!( + parse_args(&["--no-open", "--port", "1"]), + Ok(Command::Serve { + port: 1, + open: false + }) + )); + assert!(matches!(parse_args(&["install"]), Ok(Command::Install))); + assert!(matches!(parse_args(&["uninstall"]), Ok(Command::Uninstall))); + assert!(matches!(parse_args(&["--help"]), Ok(Command::Help))); + assert!(parse_args(&["18226"]) + .unwrap_err() + .starts_with("unknown argument `18226`")); + assert!(parse_args(&["--port"]) + .unwrap_err() + .contains("--port needs a number")); + assert!(parse_args(&["--port", "x"]) + .unwrap_err() + .contains("`x` is not a port number")); + assert!(parse_args(&["--port", "70000"]) + .unwrap_err() + .contains("is not a port number")); + } +} diff --git a/crates/server/src/pretty.rs b/crates/server/src/pretty.rs new file mode 100644 index 0000000..204b18d --- /dev/null +++ b/crates/server/src/pretty.rs @@ -0,0 +1,135 @@ +//! How numbers, times and sizes are written for people. + +/// `2815` as "2,815". +pub fn thousands(n: u64) -> String { + let digits = n.to_string(); + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + for (i, c) in digits.chars().enumerate() { + if i > 0 && (digits.len() - i).is_multiple_of(3) { + out.push(','); + } + out.push(c); + } + out +} + +/// A share as a percentage with one decimal, dropping a needless ".0": `0.076` as "7.6", `1.0` as "100". +pub fn pct(share: f64) -> String { + let s = format!("{:.1}", share * 100.0); + s.strip_suffix(".0").unwrap_or(&s).to_owned() +} + +/// Seconds rounded down to minutes, the way the summary says them: "3h 05m", "48m", "<1m". +pub fn hours_and_minutes(secs: f64) -> String { + let mins = (secs / 60.0).floor() as u64; + match mins { + 0 => "<1m".to_owned(), + 1..=59 => format!("{mins}m"), + _ => format!("{}h {:02}m", mins / 60, mins % 60), + } +} + +/// A short length of time: "210 ms", "0.9 s", "7.8 s", "20 min". +pub fn short(secs: f64) -> String { + if secs < 1.0 { + format!("{:.0} ms", secs * 1000.0) + } else if secs < 600.0 { + let s = format!("{secs:.1}"); + format!("{} s", s.strip_suffix(".0").unwrap_or(&s)) + } else { + format!("{:.0} min", secs / 60.0) + } +} + +/// Two sizes as one phrase: sccache's 10G limit reads "10.0 of 10.0 GB", and sizes in different +/// units read "900.0 MB of 10.0 GB". +pub fn bytes_of(size: u64, max: u64) -> String { + let (a, au) = amount(size); + let (b, bu) = amount(max); + if au == bu { + format!("{a} of {b} {au}") + } else { + format!("{a} {au} of {b} {bu}") + } +} + +fn amount(b: u64) -> (String, &'static str) { + const K: f64 = 1024.0; + let b = b as f64; + if b >= K * K * K * K { + (format!("{:.1}", b / (K * K * K * K)), "TB") + } else if b >= K * K * K { + (format!("{:.1}", b / (K * K * K)), "GB") + } else if b >= K * K { + (format!("{:.1}", b / (K * K)), "MB") + } else { + (format!("{b:.0}"), "KB") + } +} + +/// Unix seconds as a file-name-friendly UTC time: `0` as "19700101-000000". +pub fn stamp(secs: i64) -> String { + let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400)); + // Days since 1970-01-01 to a date, by Howard Hinnant's algorithm. + let z = days + 719_468; + let (era, doe) = (z.div_euclid(146_097), z.rem_euclid(146_097)); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(m <= 2); + format!( + "{y:04}{m:02}{d:02}-{:02}{:02}{:02}", + rem / 3600, + rem % 3600 / 60, + rem % 60 + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn numbers_as_written() { + assert_eq!(thousands(0), "0"); + assert_eq!(thousands(2815), "2,815"); + assert_eq!(thousands(1_234_567), "1,234,567"); + assert_eq!(pct(0.076), "7.6"); + assert_eq!(pct(0.5018), "50.2"); + assert_eq!(pct(1.0), "100"); + } + + #[test] + fn times_as_written() { + assert_eq!(hours_and_minutes(11100.0), "3h 05m"); + assert_eq!(hours_and_minutes(48.4 * 60.0), "48m"); + assert_eq!(hours_and_minutes(20.0), "<1m"); + assert_eq!(short(0.21), "210 ms"); + assert_eq!(short(0.9), "900 ms"); + assert_eq!(short(10.0), "10 s"); + assert_eq!(short(60.0), "60 s"); + assert_eq!(short(1200.0), "20 min"); + } + + #[test] + fn sizes_and_dates_as_written() { + assert_eq!( + bytes_of(10 * 1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024), + "10.0 of 10.0 GB" + ); + assert_eq!(bytes_of(1024 * 1024, 1024 * 1024), "1.0 of 1.0 MB"); + assert_eq!(bytes_of(10_726_353_131, 10_737_418_240), "10.0 of 10.0 GB"); + assert_eq!( + bytes_of(9 * 1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024), + "9.0 of 10.0 GB" + ); + assert_eq!( + bytes_of(900 * 1024 * 1024, 10 * 1024 * 1024 * 1024), + "900.0 MB of 10.0 GB" + ); + assert_eq!(stamp(0), "19700101-000000"); + assert_eq!(stamp(1_764_000_000), "20251124-160000"); // what `date -u -d @1764000000` says + } +} diff --git a/crates/server/src/stats.rs b/crates/server/src/stats.rs new file mode 100644 index 0000000..afc9164 --- /dev/null +++ b/crates/server/src/stats.rs @@ -0,0 +1,579 @@ +//! sccache's counters: reading them out of its JSON and telling two readings apart. + +use std::collections::BTreeMap; + +use sccache_dash_api::{Extra, Totals}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::pretty; + +/// Positions in [`Counters::ns`]. +pub const HIT_READ: usize = 0; +pub const CACHE_WRITE: usize = 1; +pub const COMPILE: usize = 2; + +/// sccache's counters at one moment. Each only grows, until sccache resets them. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Counters { + #[serde(default)] + pub totals: Totals, + /// Compiler runs: misses, plus compiles that could not be cached or failed. + #[serde(default)] + pub compilations: u64, + /// Nanoseconds spent reading hits, writing cache entries and running compilers. + #[serde(default)] + pub ns: [u64; 3], + /// (language, [hits, misses, errors]) by name, for languages that have counted something. + #[serde(default)] + pub langs: Vec<(String, [u64; 3])>, + /// (reason, count) by name, for reasons that have counted something. + #[serde(default)] + pub not_cached: Vec<(String, u64)>, +} + +impl Counters { + /// What happened between `older` and `self`, and whether sccache reset its counters in between. + /// + /// A counter that went down can only mean sccache zeroed its counters (a new server, or + /// `--zero-stats`), and it zeroes all of them at once: every difference is then the new value. + pub fn since(&self, older: &Counters) -> (Counters, bool) { + let mut reset = false; + let mut sub = |a: u64, b: u64| { + if b < a { + reset = true; + } + b.saturating_sub(a) + }; + let (a, b) = (&older.totals, &self.totals); + let totals = Totals { + requests: sub(a.requests, b.requests), + executed: sub(a.executed, b.executed), + hits: sub(a.hits, b.hits), + misses: sub(a.misses, b.misses), + not_cacheable: sub(a.not_cacheable, b.not_cacheable), + unsupported_compiler: sub(a.unsupported_compiler, b.unsupported_compiler), + not_compile: sub(a.not_compile, b.not_compile), + timeouts: sub(a.timeouts, b.timeouts), + read_errors: sub(a.read_errors, b.read_errors), + write_errors: sub(a.write_errors, b.write_errors), + other_errors: sub(a.other_errors, b.other_errors), + compile_fails: sub(a.compile_fails, b.compile_fails), + forced_recaches: sub(a.forced_recaches, b.forced_recaches), + cache_writes: sub(a.cache_writes, b.cache_writes), + }; + let compilations = sub(older.compilations, self.compilations); + let mut ns = [0; 3]; + for (d, (a, b)) in ns.iter_mut().zip(older.ns.iter().zip(self.ns.iter())) { + *d = sub(*a, *b); + } + let langs = self + .langs + .iter() + .filter_map(|(name, v)| { + let o = older + .langs + .iter() + .find(|(k, _)| k == name) + .map_or([0; 3], |(_, o)| *o); + let mut d = [0; 3]; + for (d, (a, b)) in d.iter_mut().zip(o.iter().zip(v.iter())) { + *d = sub(*a, *b); + } + (d != [0; 3]).then(|| (name.clone(), d)) + }) + .collect(); + let not_cached = self + .not_cached + .iter() + .filter_map(|(name, v)| { + let o = older + .not_cached + .iter() + .find(|(k, _)| k == name) + .map_or(0, |(_, o)| *o); + let d = sub(o, *v); + (d > 0).then(|| (name.clone(), d)) + }) + .collect(); + let diff = Counters { + totals, + compilations, + ns, + langs, + not_cached, + }; + (if reset { self.clone() } else { diff }, reset) + } + + /// Adds another set of counters into this one. + pub fn add(&mut self, other: &Counters) { + macro_rules! sum { + ($($f:ident),* $(,)?) => { $( self.totals.$f += other.totals.$f; )* }; + } + sum!( + requests, + executed, + hits, + misses, + not_cacheable, + unsupported_compiler, + not_compile, + timeouts, + read_errors, + write_errors, + other_errors, + compile_fails, + forced_recaches, + cache_writes, + ); + self.compilations += other.compilations; + for (n, x) in self.ns.iter_mut().zip(other.ns.iter()) { + *n += x; + } + for (name, v) in &other.langs { + match self.langs.iter_mut().find(|(k, _)| k == name) { + Some((_, have)) => { + for (h, x) in have.iter_mut().zip(v.iter()) { + *h += x; + } + } + None => self.langs.push((name.clone(), *v)), + } + } + for (name, v) in &other.not_cached { + match self.not_cached.iter_mut().find(|(k, _)| k == name) { + Some((_, have)) => *have += v, + None => self.not_cached.push((name.clone(), *v)), + } + } + } +} + +/// One level of a multi-level cache, as sccache 0.18 reports it in `stats.multi_level`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Level { + pub name: String, + pub location: String, + pub hits: u64, + pub misses: u64, + pub writes: u64, + pub write_failures: u64, + pub backfills_from: u64, + pub backfills_to: u64, + pub hit_ns: u64, + pub write_ns: u64, +} + +/// What one run of `sccache --show-stats --stats-format json` said. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Snapshot { + pub counters: Counters, + pub version: Option, + pub cache_location: Option, + pub cache_size: Option, + pub max_cache_size: Option, + pub multi_level: Vec, + /// (server, compiles) by server, sorted by server. + pub dist_compiles: Vec<(String, u64)>, + pub dist_errors: u64, +} + +/// Reads sccache's JSON. Unknown fields are ignored and missing ones read as zero, so a new +/// sccache cannot break this; only output that is not JSON with a `stats` object is an error. +pub fn parse(text: &str) -> Result { + let root: Value = + serde_json::from_str(text).map_err(|e| format!("sccache's output is not JSON ({e})"))?; + let stats = root + .get("stats") + .ok_or("sccache's output has no \"stats\" object")?; + + let (hits, misses, errors) = ( + counts(stats, "cache_hits"), + counts(stats, "cache_misses"), + counts(stats, "cache_errors"), + ); + let mut by_lang: BTreeMap<&str, [u64; 3]> = BTreeMap::new(); + for (map, i) in [(&hits, 0), (&misses, 1), (&errors, 2)] { + for (name, n) in map { + by_lang.entry(name.as_str()).or_default()[i] = *n; + } + } + let n = |field: &str| num(stats.get(field)); + let totals = Totals { + requests: n("compile_requests"), + executed: n("requests_executed"), + hits: hits.values().sum(), + misses: misses.values().sum(), + not_cacheable: n("requests_not_cacheable"), + unsupported_compiler: n("requests_unsupported_compiler"), + not_compile: n("requests_not_compile"), + timeouts: n("cache_timeouts"), + read_errors: n("cache_read_errors"), + write_errors: n("cache_write_errors"), + other_errors: errors.values().sum(), + compile_fails: n("compile_fails"), + forced_recaches: n("forced_recaches"), + cache_writes: n("cache_writes"), + }; + let counters = Counters { + totals, + compilations: n("compilations"), + ns: [ + nanos(stats.get("cache_read_hit_duration")), + nanos(stats.get("cache_write_duration")), + nanos(stats.get("compiler_write_duration")), + ], + langs: by_lang + .into_iter() + .map(|(name, v)| (name.to_owned(), v)) + .collect(), + not_cached: pairs(stats.get("not_cached")).into_iter().collect(), + }; + let text = |field: &str| root.get(field).and_then(Value::as_str).map(str::to_owned); + let multi_level = stats + .get("multi_level") + .and_then(Value::as_array) + .map(|levels| { + levels + .iter() + .filter_map(|l| { + let s = |f: &str| Some(l.get(f)?.as_str()?.to_owned()); + Some(Level { + name: s("name")?, + location: s("location")?, + hits: num(l.get("hits")), + misses: num(l.get("misses")), + writes: num(l.get("writes")), + write_failures: num(l.get("write_failures")), + backfills_from: num(l.get("backfills_from")), + backfills_to: num(l.get("backfills_to")), + hit_ns: nanos(l.get("hit_duration")), + write_ns: nanos(l.get("write_duration")), + }) + }) + .collect() + }) + .unwrap_or_default(); + Ok(Snapshot { + counters, + version: text("version"), + cache_location: text("cache_location"), + cache_size: root.get("cache_size").and_then(Value::as_u64), + max_cache_size: root.get("max_cache_size").and_then(Value::as_u64), + multi_level, + dist_compiles: pairs(stats.get("dist_compiles")) + .into_iter() + .filter(|(_, n)| *n > 0) + .collect(), + dist_errors: n("dist_errors"), + }) +} + +/// A number as sccache writes it; anything else reads as zero. +fn num(v: Option<&Value>) -> u64 { + v.and_then(Value::as_u64).unwrap_or(0) +} + +/// `{"secs": 1, "nanos": 2}` as nanoseconds. +fn nanos(v: Option<&Value>) -> u64 { + let o = v.and_then(Value::as_object); + let get = |k: &str| { + o.and_then(|o| o.get(k)) + .and_then(Value::as_u64) + .unwrap_or(0) + }; + get("secs") * 1_000_000_000 + get("nanos") +} + +/// A JSON object of counts as a sorted map. +fn pairs(v: Option<&Value>) -> BTreeMap { + v.and_then(Value::as_object) + .map(|o| { + o.iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_u64()?))) + .collect() + }) + .unwrap_or_default() +} + +/// `{"counts": {...}}` as a sorted map. +fn counts(parent: &Value, field: &str) -> BTreeMap { + pairs(parent.get(field).and_then(|f| f.get("counts"))) +} + +/// The tables for what sccache reports beyond the usual counters, empty when it reports nothing. +pub fn extras(s: &Snapshot) -> Vec { + let mut out = Vec::new(); + if !s.multi_level.is_empty() { + let rows = s + .multi_level + .iter() + .map(|l| { + let per = |total: u64, n: u64| (n > 0).then(|| total as f64 / n as f64 / 1e9); + ( + format!("{} \u{2014} {}", l.name, l.location), + format!( + "{} hits \u{b7} {} misses \u{b7} {} writes, {} failed \u{b7} backfilled {} in, {} out \u{b7} avg hit read {} \u{b7} avg write {}", + pretty::thousands(l.hits), + pretty::thousands(l.misses), + pretty::thousands(l.writes), + pretty::thousands(l.write_failures), + pretty::thousands(l.backfills_from), + pretty::thousands(l.backfills_to), + per(l.hit_ns, l.hits).map_or_else(|| "\u{2014}".to_owned(), pretty::short), + per(l.write_ns, l.writes).map_or_else(|| "\u{2014}".to_owned(), pretty::short), + ), + ) + }) + .collect(); + out.push(Extra { + title: "Multi-level cache".to_owned(), + rows, + }); + } + if !s.dist_compiles.is_empty() || s.dist_errors > 0 { + let mut rows: Vec<_> = s + .dist_compiles + .iter() + .map(|(server, n)| (server.clone(), pretty::thousands(*n))) + .collect(); + rows.push(( + "Errors (re-run locally)".to_owned(), + pretty::thousands(s.dist_errors), + )); + out.push(Extra { + title: "Distributed compiles".to_owned(), + rows, + }); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json"); + const MULTILEVEL: &str = include_str!("../../../fixtures/sample-multilevel.json"); + const DIST: &str = include_str!("../../../fixtures/sample-dist.json"); + + fn counters(requests: u64, hits: u64, misses: u64) -> Counters { + Counters { + totals: Totals { + requests, + hits, + misses, + ..Totals::default() + }, + compilations: misses, + langs: vec![("Rust".to_owned(), [hits, misses, 0])], + ..Counters::default() + } + } + + #[test] + fn live_output_is_read_as_it_is() { + let s = parse(LIVE).unwrap(); + assert_eq!( + s.counters.totals, + Totals { + requests: 7351, + executed: 6495, + hits: 3197, + misses: 3256, + not_cacheable: 829, + not_compile: 27, + other_errors: 0, + compile_fails: 39, + cache_writes: 3256, + ..Totals::default() + } + ); + assert_eq!(s.counters.compilations, 3256); + assert_eq!( + s.counters.ns, + [2_190_691_578, 8_758_680_079, 25_343_119_040_435] + ); + assert_eq!( + s.counters.langs, + vec![ + ("Assembler".to_owned(), [886, 0, 0]), + ("C/C++".to_owned(), [2082, 0, 0]), + ("Rust".to_owned(), [229, 3256, 0]), + ] + ); + assert_eq!(s.counters.not_cached.len(), 7); + assert_eq!(s.counters.not_cached[0], ("-".to_owned(), 35)); + assert_eq!(s.version.as_deref(), Some("0.18.0")); + assert_eq!( + s.cache_location.as_deref(), + Some("Local disk: \"/home/swaits/.cache/sccache\"") + ); + assert_eq!( + (s.cache_size, s.max_cache_size), + (Some(10_726_353_131), Some(10_737_418_240)) + ); + assert!(s.multi_level.is_empty() && s.dist_compiles.is_empty() && s.dist_errors == 0); + assert!( + extras(&s).is_empty(), + "nothing extra is reported, so there are no extra tables" + ); + } + + #[test] + fn a_saved_line_is_small() { + let reading = crate::history::Reading { + t: 1_764_000_000, + c: parse(LIVE).unwrap().counters, + }; + let line = serde_json::to_string(&reading).unwrap(); + assert!(line.len() < 1024, "{} bytes: {line}", line.len()); + assert!( + line.starts_with("{\"t\":1764000000,\"c\":{\"totals\":{\"requests\":7351"), + "{line}" + ); + assert!(line.ends_with("[\"multiple input files\",3]]}}"), "{line}"); + assert_eq!( + serde_json::from_str::(&line).unwrap(), + reading + ); + } + + #[test] + fn unknown_and_missing_fields_do_not_break_it() { + let s = parse( + "{\"stats\":{\"compile_requests\":\"many\",\"cache_hits\":{\"counts\":{\"Rust\":-1}},\"new_field\":1},\"extra\":2}", + ) + .unwrap(); + assert_eq!(s.counters, Counters::default()); + assert_eq!(parse("{\"stats\":{}}").unwrap(), Snapshot::default()); + assert_eq!( + parse("{\"stats\":null,\"version\":\"1.0\"}") + .unwrap() + .version + .as_deref(), + Some("1.0") + ); + assert!(parse("not json").is_err()); + assert!(parse("{\"error\":\"no server\"}").is_err()); + } + + #[test] + fn differences_are_what_grew() { + let (older, newer) = (counters(100, 60, 40), counters(130, 80, 50)); + let (diff, reset) = newer.since(&older); + assert_eq!(diff.totals.requests, 30); + assert_eq!(diff.totals.hits, 20); + assert_eq!(diff.totals.misses, 10); + assert_eq!(diff.langs, vec![("Rust".to_owned(), [20, 10, 0])]); + assert!(!reset); + let (same, _) = newer.since(&newer); + assert!(same.totals == Totals::default() && same.langs.is_empty()); + } + + #[test] + fn a_counter_going_down_zeroes_the_whole_reading() { + let mut older = counters(100, 60, 40); + older.not_cached.push(("crate-type".to_owned(), 9)); + older.ns[COMPILE] = 400; + let mut newer = counters(130, 5, 0); + newer.not_cached.push(("crate-type".to_owned(), 2)); + newer.not_cached.push(("-o".to_owned(), 1)); + newer.ns[COMPILE] = 7; + let (diff, reset) = newer.since(&older); + assert!( + reset, + "hits went down, so the counters were zeroed in between" + ); + assert_eq!( + diff, newer, + "every difference is the new value, even where the counter grew" + ); + } + + #[test] + fn sums_merge_languages_and_reasons() { + let mut a = counters(10, 4, 6); + a.not_cached.push(("crate-type".to_owned(), 1)); + let mut b = counters(1, 1, 0); + b.compilations = 0; + b.langs = vec![ + ("C/C++".to_owned(), [1, 0, 0]), + ("Rust".to_owned(), [0, 0, 2]), + ]; + b.not_cached.push(("crate-type".to_owned(), 2)); + b.not_cached.push(("incremental".to_owned(), 1)); + a.add(&b); + assert_eq!(a.totals.requests, 11); + assert_eq!(a.totals.hits, 5); + assert_eq!(a.compilations, 6); + assert_eq!( + a.langs, + vec![ + ("Rust".to_owned(), [4, 6, 2]), + ("C/C++".to_owned(), [1, 0, 0]) + ] + ); + assert_eq!( + a.not_cached, + vec![("crate-type".to_owned(), 3), ("incremental".to_owned(), 1)] + ); + } + + #[test] + fn multilevel_sample_becomes_a_table() { + let s = parse(MULTILEVEL).unwrap(); + assert_eq!(s.multi_level.len(), 2); + assert_eq!(s.multi_level[1].name, "L1 (s3)"); + assert_eq!(s.multi_level[0].hit_ns, 1_500_000_000); + assert_eq!(s.multi_level[1].write_ns, 36_500_000_000); + let extras = extras(&s); + assert_eq!(extras.len(), 1); + assert_eq!(extras[0].title, "Multi-level cache"); + assert_eq!(extras[0].rows.len(), 2); + assert_eq!( + extras[0].rows[0].0, + "L0 (disk) \u{2014} Local disk: \"/home/me/.cache/sccache\"" + ); + assert_eq!( + extras[0].rows[0].1, + "1,500 hits \u{b7} 1,000 misses \u{b7} 1,400 writes, 2 failed \u{b7} backfilled 300 in, 0 out \u{b7} avg hit read 1 ms \u{b7} avg write 2 ms" + ); + } + + #[test] + fn dist_sample_becomes_a_table() { + let s = parse(DIST).unwrap(); + assert_eq!( + s.dist_compiles, + vec![ + ("10.0.0.11:4226".to_owned(), 402), + ("10.0.0.12:4226".to_owned(), 379), + ("buildbox.local:4228".to_owned(), 9), + ] + ); + assert_eq!(s.dist_errors, 7); + let extras = extras(&s); + assert_eq!(extras.len(), 1); + assert_eq!(extras[0].title, "Distributed compiles"); + assert_eq!( + extras[0].rows[2], + ("buildbox.local:4228".to_owned(), "9".to_owned()) + ); + assert_eq!( + extras[0].rows[3], + ("Errors (re-run locally)".to_owned(), "7".to_owned()) + ); + } + + #[test] + fn only_dist_errors_still_makes_a_table() { + let mut s = parse(DIST).unwrap(); + s.dist_compiles.clear(); + assert_eq!( + extras(&s)[0].rows, + vec![("Errors (re-run locally)".to_owned(), "7".to_owned())] + ); + } +} diff --git a/crates/server/src/systemd.rs b/crates/server/src/systemd.rs new file mode 100644 index 0000000..96c1bc2 --- /dev/null +++ b/crates/server/src/systemd.rs @@ -0,0 +1,130 @@ +//! Living in systemd: the unit file, and installing or removing it. + +use std::path::PathBuf; +use std::process::Command; + +use sccache_dash_api::DEFAULT_PORT; + +pub const UNIT: &str = "sccache-dash.service"; + +/// The unit file that runs this program from login on, without opening a browser. +pub fn unit_file(exe: &str, path: &str) -> String { + format!( + "[Unit]\n\ + Description=sccache-dash, a dashboard for sccache's cache at http://127.0.0.1:{DEFAULT_PORT}\n\ + \n\ + [Service]\n\ + ExecStart={} --no-open\n\ + Environment={}\n\ + Restart=on-failure\n\ + RestartSec=5\n\ + \n\ + [Install]\n\ + WantedBy=default.target\n", + quote(exe), + quote(&format!("PATH={path}")), + ) +} + +/// Quotes a value the way systemd unit files read it; `%` would otherwise start a specifier. +fn quote(value: &str) -> String { + format!( + "\"{}\"", + value + .replace('\\', "\\\\") + .replace('"', "\\\"") + .replace('%', "%%") + ) +} + +fn unit_path() -> Result { + let config = dirs::config_dir() + .ok_or("cannot find the config directory ($XDG_CONFIG_HOME, or ~/.config)")?; + Ok(config.join("systemd").join("user").join(UNIT)) +} + +fn systemctl(args: &[&str]) -> Result<(), String> { + let output = Command::new("systemctl") + .args(args) + .output() + .map_err(|e| format!("cannot run systemctl: {e}"))?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned(); + let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned(); + Err(format!( + "systemctl {} failed: {}", + args.join(" "), + [stdout, stderr].join(" ").trim() + )) +} + +/// Writes the unit file for the program as it is running right now, then starts it. +pub fn install() -> Result<(), String> { + let exe = + std::env::current_exe().map_err(|e| format!("cannot find where this program is: {e}"))?; + let path = std::env::var("PATH").unwrap_or_default(); + let unit = unit_path()?; + if let Some(dir) = unit.parent() { + std::fs::create_dir_all(dir) + .map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + } + std::fs::write(&unit, unit_file(&exe.to_string_lossy(), &path)) + .map_err(|e| format!("cannot write {}: {e}", unit.display()))?; + systemctl(&["--user", "daemon-reload"])?; + systemctl(&["--user", "enable", "--now", UNIT])?; + println!( + "Installed {}. The dashboard is at http://127.0.0.1:{DEFAULT_PORT}", + unit.display() + ); + Ok(()) +} + +/// Stops the service and deletes the unit file. +pub fn uninstall() -> Result<(), String> { + let unit = unit_path()?; + if unit.exists() { + systemctl(&["--user", "disable", "--now", UNIT])?; + std::fs::remove_file(&unit) + .map_err(|e| format!("cannot remove {}: {e}", unit.display()))?; + } else { + println!("{} is not installed; nothing to remove.", unit.display()); + } + systemctl(&["--user", "daemon-reload"]) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_unit_runs_this_binary_without_a_browser_and_with_the_shell_s_path() { + let unit = unit_file("/home/me/bin/sccache-dash", "/usr/bin:/home/me/.cargo/bin"); + assert_eq!( + unit, + "[Unit]\n\ + Description=sccache-dash, a dashboard for sccache's cache at http://127.0.0.1:8226\n\ + \n\ + [Service]\n\ + ExecStart=\"/home/me/bin/sccache-dash\" --no-open\n\ + Environment=\"PATH=/usr/bin:/home/me/.cargo/bin\"\n\ + Restart=on-failure\n\ + RestartSec=5\n\ + \n\ + [Install]\n\ + WantedBy=default.target\n" + ); + assert!(unit_file("/a b/sccache-dash", "/x") + .contains("ExecStart=\"/a b/sccache-dash\" --no-open\n")); + assert!( + unit_file("/x", "/a%b\"c").contains("Environment=\"PATH=/a%%b\\\"c\"\n"), + "% and quotes cannot change what systemd reads" + ); + assert!( + unit_file("relative/sccache-dash", "/x") + .contains("ExecStart=\"relative/sccache-dash\""), + "quoting is the caller's path, verbatim" + ); + } +} diff --git a/crates/server/src/view.rs b/crates/server/src/view.rs new file mode 100644 index 0000000..eaf04a4 --- /dev/null +++ b/crates/server/src/view.rs @@ -0,0 +1,1289 @@ +//! Turning the saved readings into the one `View` the page draws. + +use std::collections::BTreeMap; + +use sccache_dash_api::{ + Bucket, Language, Problem, Range, Server, Severity, Status, TimeSaved, Timing, View, +}; +use serde_json::Value; + +use crate::app::{State, HEARTBEAT_SECS}; +use crate::pretty; +use crate::stats::{self, Counters, CACHE_WRITE, COMPILE, HIT_READ}; + +/// Where each problem starts, all in one place so they can be turned together. +pub mod levels { + use std::time::Duration; + + /// A language is reported when fewer than this many of every hundred compiles hit... + pub const LOW_HIT_RATE_PERCENT: u64 = 40; + /// ...and it has at least this many hits and misses. + pub const LOW_HIT_RATE_COMPILES: u64 = 50; + /// Timeouts are reported when more than this many of every hundred executed compiles timed out. + pub const TIMEOUT_PERCENT: u64 = 1; + /// The cache is reported when it holds this many hundredths of its limit. + pub const CACHE_FULL_PERCENT: u64 = 90; + /// Compiles recorded this recently mean sccache is running. + pub const RUNNING_WINDOW: Duration = Duration::from_secs(5 * 60); + /// The chart has at most this many buckets. + pub const BUCKETS: i64 = 120; +} + +/// The length of each range, in seconds. +fn length(range: Range) -> i64 { + match range { + Range::Hour => 3600, + Range::Day => 86_400, + Range::Week => 7 * 86_400, + Range::Month | Range::SinceReset => 30 * 86_400, + } +} + +/// What happened between two consecutive readings, dated when the later one was taken. +struct Span<'a> { + end: i64, + reset: bool, + delta: &'a Counters, +} + +/// Visits every interval that is known: the saved ones, then the one up to the live reading. +fn each_span(st: &State, mut f: impl FnMut(Span<'_>)) { + for i in &st.intervals { + f(Span { + end: i.end, + reset: i.reset, + delta: &i.delta, + }); + } + if let (Some(live), Some(last)) = (&st.live, st.readings.last()) { + let (delta, reset) = live.snapshot.counters.since(&last.c); + f(Span { + end: live.at, + reset, + delta: &delta, + }); + } +} + +/// The sum of the intervals recorded from `from` (inclusive) to `to` (exclusive); `None` when +/// nothing was recorded in that time. +fn sum_between(st: &State, from: i64, to: i64) -> Option { + let mut sum: Option = None; + each_span(st, |s| { + if s.end >= from && s.end < to { + sum.get_or_insert_with(Counters::default).add(s.delta); + } + }); + sum +} + +/// What a compile of each language takes, learned from every saved interval in which all the +/// misses were of that one language. +#[derive(Default)] +struct Learned(BTreeMap); + +impl Learned { + fn from_history(st: &State) -> Learned { + let mut learned = Learned::default(); + each_span(st, |s| { + if s.delta.totals.misses == 0 { + return; + } + let mut with_misses = s.delta.langs.iter().filter(|(_, v)| v[1] > 0); + let Some((name, _)) = with_misses.next() else { + return; + }; + if with_misses.next().is_some() { + return; + } + let seen = learned.0.entry(name.clone()).or_default(); + seen.0 += s.delta.ns[COMPILE]; + seen.1 += s.delta.compilations; + }); + learned + } + + /// (average build time in seconds, compiles it was learned from). + fn build_time(&self, lang: &str) -> Option<(f64, u64)> { + let (ns, n) = self.0.get(lang).filter(|(_, n)| *n > 0)?; + Some((*ns as f64 / *n as f64 / 1e9, *n)) + } +} + +/// The rough, deliberately low saving: a hit counts only when the build time of its language +/// is known. Also returns the average time a hit took to read, which the chart needs. +fn time_saved(c: &Counters, learned: &Learned) -> (TimeSaved, f64) { + let t = &c.totals; + let hit_read = if t.hits > 0 { + c.ns[HIT_READ] as f64 / t.hits as f64 / 1e9 + } else { + 0.0 + }; + let (mut seconds, mut left_out, mut used, mut unknown) = (0.0, 0, Vec::new(), Vec::new()); + for (name, v) in &c.langs { + if v[0] == 0 { + continue; + } + match learned.build_time(name) { + Some((build, compiles)) => { + seconds += v[0] as f64 * (build - hit_read).max(0.0); + used.push(format!( + "{} {} (from {} compiles)", + name, + pretty::short(build), + pretty::thousands(compiles) + )); + } + None => { + left_out += v[0]; + unknown.push((v[0], name)); + } + } + } + let note = if t.hits == 0 { + "There were no hits in this range, so nothing was saved.".to_owned() + } else if used.is_empty() { + format!( + "Nothing is counted: no build time has been learned yet, which takes saved minutes in which every miss was a compile of one language. {} hits left out.", + pretty::thousands(left_out) + ) + } else { + let mut note = format!( + "Learned build times: {}. A hit saves that minus the {} average cache read.", + used.join(", "), + pretty::short(hit_read) + ); + if left_out > 0 { + unknown.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1))); + let names: Vec = unknown + .iter() + .map(|(hits, name)| format!("{} {name}", pretty::thousands(*hits))) + .collect(); + note.push_str(&format!( + " Left out: {} hits ({}), no build time learned for them yet.", + pretty::thousands(left_out), + names.join(", ") + )); + } + note + }; + ( + TimeSaved { + seconds, + hits_left_out: left_out, + note, + }, + hit_read, + ) +} + +/// The chart: at most [`levels::BUCKETS`] buckets from `from` up to and including `to`, each +/// holding what was recorded up to the moment it was noticed. +fn buckets(st: &State, from: i64, to: i64, learned: &Learned, hit_read: f64) -> Vec { + let span = (to - from).max(1); + let len = (span + levels::BUCKETS - 1) / levels::BUCKETS; + let count = ((span + len - 1) / len) as usize; + // The last bucket takes the moment `to` itself, which is always a reading. + let bucket_of = |t: i64| (((t - from) / len) as usize).min(count - 1); + let mut out: Vec = (0..count as i64) + .map(|i| Bucket { + start: from + i * len, + gap: true, + ..Bucket::default() + }) + .collect(); + each_span(st, |s| { + if s.end < from || s.end > to { + return; + } + let b = &mut out[bucket_of(s.end)]; + let t = &s.delta.totals; + b.reset |= s.reset; + b.hits += t.hits; + b.misses += t.misses; + b.other += t.not_cacheable + t.unsupported_compiler + t.not_compile; + b.errors += t.errors(); + for (name, v) in &s.delta.langs { + match b.languages.iter_mut().find(|(k, _, _)| k == name) { + Some((_, hits, misses)) => { + *hits += v[0]; + *misses += v[1]; + } + None => b.languages.push((name.clone(), v[0], v[1])), + } + b.saved_seconds += v[0] as f64 + * learned + .build_time(name) + .map_or(0.0, |(build, _)| (build - hit_read).max(0.0)); + } + }); + + // A bucket is open when a reading falls in it, or when it lies between two readings less + // than ten minutes apart: the service was running then, just nothing changed. + let mut times: Vec = st + .readings + .iter() + .map(|r| r.t) + .filter(|&t| t >= from && t <= to) + .collect(); + times.extend( + st.live + .iter() + .map(|l| l.at) + .filter(|&t| t >= from && t <= to), + ); + for &t in × { + out[bucket_of(t)].gap = false; + } + for w in times.windows(2) { + if w[1] - w[0] <= HEARTBEAT_SECS { + for b in &mut out[bucket_of(w[0])..bucket_of(w[1])] { + b.gap = false; + } + } + } + for b in &mut out { + b.languages.sort_by(|a, b| a.0.cmp(&b.0)); + } + out +} + +fn problems(c: &Counters, server: &Server) -> Vec { + let t = &c.totals; + let (mut errors, mut warnings) = (Vec::new(), Vec::new()); + let problem = |severity, title: String, detail: String| Problem { + severity, + title, + detail, + }; + + if server.status == Status::NotRunning { + errors.push(problem( + Severity::Error, + "sccache is not running".to_owned(), + format!( + "sccache could not be asked for its counters ({}), so compiles may not be cached at all; check that it is installed and run `sccache --show-stats` yourself to see what it says.", + server.error.as_deref().unwrap_or("no answer") + ), + )); + } + let n = t.errors(); + if n > 0 { + errors.push(problem( + Severity::Error, + format!("{n} cache error{}", if n == 1 { "" } else { "s" }), + format!( + "The cache could not be read or written {n} time{} in this range ({} read, {} write, {} other) and those compiles ran from scratch; check that the disk holding the cache has room and sccache may write to it.", + if n == 1 { "" } else { "s" }, + pretty::thousands(t.read_errors), + pretty::thousands(t.write_errors), + pretty::thousands(t.other_errors) + ), + )); + } + if t.executed > 0 + && u128::from(t.timeouts) * 100 + > u128::from(t.executed) * u128::from(levels::TIMEOUT_PERCENT) + { + warnings.push(problem( + Severity::Warning, + format!("Timeouts {}%", pretty::pct(t.timeouts as f64 / t.executed as f64)), + format!( + "The cache took too long to answer on {} of {} compiles, more than {}%, and each was then built from scratch; if the cache is on the network check that connection, or give sccache a longer timeout for it.", + pretty::thousands(t.timeouts), + pretty::thousands(t.executed), + levels::TIMEOUT_PERCENT + ), + )); + } + let mut low: Vec<(&String, u64, u64)> = c + .langs + .iter() + .filter(|(_, v)| { + let n = v[0] + v[1]; + n >= levels::LOW_HIT_RATE_COMPILES + && u128::from(v[0]) * 100 < u128::from(n) * u128::from(levels::LOW_HIT_RATE_PERCENT) + }) + .map(|(name, v)| (name, v[0], v[0] + v[1])) + .collect(); + low.sort_by(|a, b| (a.1 * b.2).cmp(&(b.1 * a.2)).then_with(|| a.0.cmp(b.0))); + for (name, hits, n) in low { + warnings.push(problem( + Severity::Warning, + format!("{name} hit rate {}%", pretty::pct(hits as f64 / n as f64)), + format!( + "Only {}% of {} {name} compiles came from the cache, so most were rebuilt; a different toolchain, compiler flags or environment makes sccache miss, so compare those between two builds.", + pretty::pct(hits as f64 / n as f64), + pretty::thousands(n) + ), + )); + } + if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) { + if max > 0 + && u128::from(size) * 100 >= u128::from(max) * u128::from(levels::CACHE_FULL_PERCENT) + { + warnings.push(problem( + Severity::Warning, + format!("Cache {}% full", pretty::pct(size as f64 / max as f64)), + format!( + "The cache holds {}, close to its limit; when it is full sccache deletes its oldest entries to make room, which costs hits, so raise the limit (`SCCACHE_CACHE_SIZE`, for example `50G`) if the disk has room.", + pretty::bytes_of(size, max) + ), + )); + } + } + if let (Some(running), Some(command)) = (&server.version, &server.client_version) { + if running != command { + warnings.push(problem( + Severity::Warning, + "sccache versions differ".to_owned(), + format!( + "The running sccache server is {running} but the `sccache` command is {command}, which can make compiles fail; run `sccache --stop-server` so the next compile starts the new version." + ), + )); + } + } + errors.extend(warnings); + errors +} + +/// The text "Copy Summary" puts on the clipboard. +pub fn summary(view: &View) -> String { + let t = &view.totals; + let range = match view.range { + Some(Range::Hour) => "last hour", + Some(Range::Day) => "last 24 hours", + Some(Range::Week) => "last 7 days", + Some(Range::Month) => "last 30 days", + _ => "since last reset", + }; + let hit_rate = match t.hit_rate() { + Some(r) => format!( + "{}% ({} of {} compiles from cache)", + pretty::pct(r), + pretty::thousands(t.hits), + pretty::thousands(t.hits + t.misses) + ), + None => "\u{2014} (no cacheable compiles)".to_owned(), + }; + let by_language: Vec = view + .languages + .iter() + .map(|l| { + let n = l.hits + l.misses; + let rate = if n == 0 { + "\u{2014}".to_owned() + } else { + format!("{}%", pretty::pct(l.hits as f64 / n as f64)) + }; + format!("{} {rate}", l.name) + }) + .collect(); + let mut s = format!( + "**sccache, {range}**\n\ + - Hit rate: {hit_rate}\n\ + - By language: {}\n\ + - Not cacheable: {} \u{b7} Errors: {} \u{b7} Timeouts: {}\n", + if by_language.is_empty() { + "(none)".to_owned() + } else { + by_language.join(", ") + }, + pretty::thousands(t.not_cacheable + t.unsupported_compiler + t.not_compile), + pretty::thousands(t.errors()), + pretty::thousands(t.timeouts), + ); + if view.time_saved.seconds > 0.0 { + s += &format!( + "- Time saved: ~{} (rough)\n", + pretty::hours_and_minutes(view.time_saved.seconds) + ); + } + let kind = view + .server + .cache_location + .as_deref() + .and_then(|l| l.split(':').next()) + .map_or_else(|| "unknown location".to_owned(), |k| k.to_lowercase()); + let sizes = match (view.server.cache_size, view.server.max_cache_size) { + (Some(size), Some(max)) => pretty::bytes_of(size, max), + _ => "size unknown".to_owned(), + }; + s += &format!( + "- Cache: {kind}, {sizes} \u{b7} sccache {}\n", + view.server.version.as_deref().unwrap_or("unknown version") + ); + s +} + +/// Makes the view for one range from what is known now. +pub fn build(st: &State, range: Range, now: i64) -> View { + let live = st.live.as_ref(); + let learned = Learned::from_history(st); + + // What the range counts, and when its chart starts. + let (counters, previous, from) = match range { + Range::SinceReset => { + // The counters as they are, charted since they were last zeroed. + let mut from = live + .map_or(now, |l| l.at) + .min(st.readings.first().map_or(now, |r| r.t)); + each_span(st, |s| { + if s.reset { + from = s.end; + } + }); + ( + live.map_or_else(Counters::default, |l| l.snapshot.counters.clone()), + None, + from, + ) + } + _ => { + let length = length(range); + ( + sum_between(st, now - length, now + 1).unwrap_or_default(), + sum_between(st, now - 2 * length, now - length), + now - length, + ) + } + }; + let t = &counters.totals; + let per = |total_ns: u64, n: u64| (n > 0).then(|| total_ns as f64 / n as f64 / 1e6); + let timing = Timing { + avg_hit_read_ms: per(counters.ns[HIT_READ], t.hits), + avg_cache_write_ms: per(counters.ns[CACHE_WRITE], t.cache_writes), + avg_compile_ms: per(counters.ns[COMPILE], counters.compilations), + }; + let (time_saved, hit_read) = time_saved(&counters, &learned); + let mut languages: Vec = counters + .langs + .iter() + .map(|(name, v)| Language { + name: name.clone(), + hits: v[0], + misses: v[1], + errors: v[2], + }) + .collect(); + languages.sort_by(|a, b| { + (b.hits + b.misses) + .cmp(&(a.hits + a.misses)) + .then_with(|| a.name.cmp(&b.name)) + }); + let mut not_cached = counters.not_cached.clone(); + not_cached.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + + let window = levels::RUNNING_WINDOW.as_secs() as i64; + let mut changed_recently = false; + each_span(st, |s| { + changed_recently |= s.end > now - window && s.end <= now && s.delta.totals.requests > 0; + }); + let server = Server { + status: match live { + None => Status::NotRunning, + Some(_) if changed_recently => Status::Running, + Some(_) => Status::Idle, + }, + version: live.and_then(|l| l.snapshot.version.clone()), + client_version: st.client_version.clone(), + cache_location: live.and_then(|l| l.snapshot.cache_location.clone()), + cache_size: live.and_then(|l| l.snapshot.cache_size), + max_cache_size: live.and_then(|l| l.snapshot.max_cache_size), + error: st.error.clone(), + }; + let mut view = View { + range: Some(range), + generated_at: now, + problems: problems(&counters, &server), + server, + totals: counters.totals, + previous: previous.map(|p| p.totals), + timing, + time_saved, + languages, + not_cached, + buckets: buckets(st, from, now, &learned, hit_read), + extras: live.map_or_else(Vec::new, |l| stats::extras(&l.snapshot)), + raw: st.raw.clone().unwrap_or(Value::Null), + summary_markdown: String::new(), + }; + view.summary_markdown = summary(&view); + view +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::app::Live; + use crate::history::Reading; + use sccache_dash_api::Totals; + + const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json"); + + /// A reading with these totals, all of it Rust, taking 1 s per hit read, 1 s per cache + /// write and 60 s per compile. + fn reading(t: i64, requests: u64, hits: u64, misses: u64) -> Reading { + Reading { + t, + c: Counters { + totals: Totals { + requests, + hits, + misses, + cache_writes: misses, + ..Totals::default() + }, + compilations: misses, + ns: [ + hits * 1_000_000_000, + misses * 1_000_000_000, + misses * 60_000_000_000, + ], + langs: vec![("Rust".to_owned(), [hits, misses, 0])], + ..Counters::default() + }, + } + } + + fn state(readings: Vec, live: Option<(i64, &str)>) -> State { + let mut st = State::default(); + for r in readings { + st.push(r); + } + if let Some((at, text)) = live { + let snapshot = stats::parse(text).unwrap(); + st.raw = serde_json::from_str(text).ok(); + st.live = Some(Live { + at, + snapshot, + raw_text: text.to_owned(), + }); + } + st + } + + /// The readings, with a live reading at `at` that saw nothing change since the last of them. + fn quiet_since(readings: Vec, at: i64) -> State { + let snapshot = stats::Snapshot { + counters: readings + .last() + .map_or_else(Counters::default, |r| r.c.clone()), + ..stats::Snapshot::default() + }; + let mut st = state(readings, None); + st.live = Some(Live { + at, + snapshot, + raw_text: String::new(), + }); + st + } + + /// A view of the live output with `edit` applied and sccache's command at `client`. It starts + /// with nothing to report: a cache a tenth of its limit and one language with a perfect rate, + /// so that only what `edit` changes is a problem. + fn seen(edit: impl FnOnce(&mut stats::Snapshot), client: &str) -> View { + let mut snapshot = stats::parse(LIVE).unwrap(); + snapshot.cache_size = Some(1024 * 1024 * 1024); + snapshot.counters.langs = vec![("C/C++".to_owned(), [2082, 0, 0])]; + edit(&mut snapshot); + let st = State { + live: Some(Live { + at: 100, + raw_text: LIVE.to_owned(), + snapshot, + }), + client_version: Some(client.to_owned()), + ..State::default() + }; + build(&st, Range::SinceReset, 100) + } + + fn titles(view: &View) -> Vec<&str> { + view.problems.iter().map(|p| p.title.as_str()).collect() + } + + #[test] + fn totals_are_what_changed_between_the_readings_inside_the_range() { + let st = quiet_since( + vec![ + reading(0, 100, 50, 50), + reading(60, 130, 62, 68), + reading(120, 160, 74, 86), + reading(180, 200, 90, 110), + ], + 200, + ); + let v = build(&st, Range::Hour, 200); + assert_eq!( + v.totals, + Totals { + requests: 100, + hits: 40, + misses: 60, + cache_writes: 60, + ..Totals::default() + } + ); + assert_eq!(v.previous, None, "nothing was recorded in the hour before"); + assert_eq!( + v.languages, + vec![Language { + name: "Rust".to_owned(), + hits: 40, + misses: 60, + errors: 0 + }] + ); + assert_eq!( + v.timing, + Timing { + avg_hit_read_ms: Some(1000.0), + avg_cache_write_ms: Some(1000.0), + avg_compile_ms: Some(60000.0) + } + ); + assert_eq!( + ( + v.buckets.len(), + v.buckets.iter().map(|b| b.hits).sum::() + ), + (120, 40) + ); + assert_eq!(v.buckets.iter().map(|b| b.other).sum::(), 0); + assert_eq!( + (v.server.status, v.range), + (Status::Running, Some(Range::Hour)), + "the last change was 20 s ago" + ); + } + + #[test] + fn previous_is_the_period_of_the_same_length_before() { + let st = state( + vec![ + reading(0, 0, 0, 0), + reading(1000, 5, 0, 5), + reading(2000, 10, 0, 10), + reading(3000, 15, 0, 15), + reading(5000, 17, 0, 17), + reading(6000, 19, 0, 19), + reading(7000, 21, 0, 21), + ], + None, + ); + let v = build(&st, Range::Hour, 8000); + assert_eq!( + v.totals.requests, 6, + "the three intervals ending in the last hour" + ); + assert_eq!( + v.previous.map(|p| p.requests), + Some(15), + "the three in the hour before" + ); + let v = build(&st, Range::Day, 8000); + assert_eq!(v.totals.requests, 21); + assert_eq!(v.previous, None, "nothing was saved before that day"); + } + + #[test] + fn the_first_reading_ever_counts_for_nothing() { + let st = state( + vec![reading(0, 100, 60, 40), reading(60, 130, 80, 50)], + None, + ); + let v = build(&st, Range::Week, 100); + assert_eq!( + v.totals.requests, 30, + "only what came after the first reading" + ); + assert_eq!((v.totals.hits, v.totals.misses), (20, 10)); + + let fresh = state(vec![], Some((100, LIVE))); + let v = build(&fresh, Range::Week, 100); + assert_eq!( + v.totals, + Totals::default(), + "a first live reading is a baseline too" + ); + assert_eq!(v.buckets.iter().map(|b| b.hits).sum::(), 0); + assert_eq!(v.server.status, Status::Idle); + } + + #[test] + fn a_reset_in_the_middle_starts_the_count_again() { + // requests 100 -> 130, then sccache was zeroed and went 10 -> 25 + let st = state( + vec![ + reading(0, 100, 60, 40), + reading(600, 130, 80, 50), + reading(1200, 10, 3, 7), + reading(1800, 25, 9, 16), + ], + None, + ); + let v = build(&st, Range::Hour, 1900); + assert_eq!( + v.totals.requests, 55, + "30 before the reset, then 10 + 15 from zero" + ); + assert_eq!( + (v.totals.hits, v.totals.misses), + (29, 26), + "20 + 3 + 6 hits, 10 + 7 + 9 misses" + ); + let flagged: Vec<&Bucket> = v.buckets.iter().filter(|b| b.reset).collect(); + assert_eq!( + flagged.len(), + 1, + "exactly one bucket is marked reset, not {:?}", + v.buckets + .iter() + .filter(|b| b.reset) + .map(|b| b.start) + .collect::>() + ); + let b = flagged[0]; + assert!( + (b.start..b.start + 30).contains(&1200), + "the one holding the reading at 1200" + ); + assert!((b.hits, b.misses) == (3, 7)); + assert_eq!( + v.buckets.iter().map(|b| b.hits).sum::(), + 29, + "the chart adds up to the totals" + ); + } + + #[test] + fn the_reset_range_shows_the_live_counters_since_they_were_zeroed() { + let st = state( + vec![ + reading(0, 100, 60, 40), + reading(600, 130, 80, 50), + reading(1200, 10, 1, 7), + ], + Some((1800, LIVE)), + ); + let v = build(&st, Range::SinceReset, 1800); + let live = stats::parse(LIVE).unwrap().counters; + assert_eq!(v.totals, live.totals, "as they are, not summed"); + assert_eq!(v.previous, None); + assert_eq!( + v.timing.avg_hit_read_ms, + Some(2_190_691_578.0 / 3197.0 / 1e6) + ); + let starts: Vec = v.buckets.iter().map(|b| b.start).collect(); + assert_eq!((starts.len(), starts[0], starts[119]), (120, 1200, 1795)); + assert!(v.buckets[0].reset, "the chart starts at the reset"); + assert_eq!( + (v.buckets[0].hits, v.buckets[119].hits, v.buckets[119].reset), + (1, 3196, false) + ); + assert_eq!( + v.buckets.iter().map(|b| b.hits).sum::(), + live.totals.hits, + "3 at the reset, then the rest at the live reading" + ); + assert!( + v.buckets.iter().all(|b| !b.gap), + "a reading at each end, ten minutes apart at most" + ); + assert_eq!( + v.languages[0], + Language { + name: "Rust".to_owned(), + hits: 229, + misses: 3256, + errors: 0 + } + ); + assert_eq!( + v.not_cached[0], + ("crate-type".to_owned(), 621), + "largest reason first" + ); + assert_eq!(v.raw, serde_json::from_str::(LIVE).unwrap()); + } + + #[test] + fn gaps_show_where_nothing_was_recorded() { + // readings at 0 and 60, then the service was off until 4000 + let st = state( + vec![ + reading(0, 0, 0, 0), + reading(60, 1, 1, 0), + reading(4000, 2, 1, 1), + reading(4020, 3, 1, 2), + ], + None, + ); + let v = build(&st, Range::Hour, 4100); + assert_eq!( + v.totals.requests, 2, + "the interval ending at 60 is before the range" + ); + let open: Vec = v + .buckets + .iter() + .filter(|b| !b.gap) + .map(|b| b.start) + .collect(); + assert_eq!( + open, + vec![3980, 4010], + "only the two buckets with a reading in them" + ); + assert_eq!( + ( + v.buckets[116].misses, + v.buckets[117].misses, + v.buckets[118].misses + ), + (1, 1, 0), + "what changed while the service was off counts when it was noticed" + ); + + // between readings less than ten minutes apart the service was running, just idle + let st = state( + vec![ + reading(0, 0, 0, 0), + reading(300, 1, 1, 0), + reading(600, 2, 2, 0), + ], + None, + ); + let v = build(&st, Range::Hour, 610); + assert_eq!( + v.buckets.iter().filter(|b| b.gap).count(), + 99, + "one open stretch from the reading at 0 to the one at 600" + ); + } + + /// Three saved minutes that each saw one Rust miss of 60 s, then a live reading with hits + /// in three languages and half a second per hit read. + fn taught() -> State { + let taught = |t: i64, misses: u64| Reading { + t, + c: Counters { + totals: Totals { + requests: misses, + misses, + cache_writes: misses, + ..Totals::default() + }, + compilations: misses, + ns: [0, 0, misses * 60_000_000_000], + langs: vec![("Rust".to_owned(), [0, misses, 0])], + ..Counters::default() + }, + }; + let mut c = stats::parse(LIVE).unwrap().counters; + c.langs = vec![ + ("Assembler".to_owned(), [733, 0, 0]), + ("C/C++".to_owned(), [2082, 0, 0]), + ("Rust".to_owned(), [229, 3, 0]), + ]; + c.totals = Totals { + requests: 3047, + hits: 3044, + misses: 3, + cache_writes: 3, + ..Totals::default() + }; + c.compilations = 3; + c.ns = [3_044 * 500_000_000, 3_000_000_000, 3 * 60_000_000_000]; + let snapshot = stats::Snapshot { + counters: c, + ..stats::parse(LIVE).unwrap() + }; + let mut st = state( + vec![taught(0, 0), taught(60, 1), taught(120, 2), taught(180, 3)], + None, + ); + st.live = Some(Live { + at: 240, + snapshot, + raw_text: String::new(), + }); + st + } + + #[test] + fn time_saved_counts_only_languages_whose_build_time_is_known() { + let v = build(&taught(), Range::Week, 240); + // Rust hits save 60 s minus the 0.5 s average hit read; C/C++ and Assembler are left out + let ts = &v.time_saved; + assert_eq!(ts.seconds, 229.0 * 59.5); + assert_eq!(ts.hits_left_out, 2082 + 733); + assert_eq!( + ts.note, + "Learned build times: Rust 60 s (from 3 compiles). A hit saves that minus the 500 ms average cache read. Left out: 2,815 hits (2,082 C/C++, 733 Assembler), no build time learned for them yet." + ); + assert_eq!(v.timing.avg_hit_read_ms, Some(500.0)); + assert_eq!( + v.timing.avg_compile_ms, + Some(60000.0), + "three compiles of 60 s" + ); + let saved: f64 = v.buckets.iter().map(|b| b.saved_seconds).sum(); + assert_eq!(saved, ts.seconds, "the chart adds up to the saving"); + assert_eq!( + v.buckets[119].saved_seconds, ts.seconds, + "all of it in the bucket of the live reading" + ); + } + + #[test] + fn time_saved_is_zero_and_explained_when_nothing_is_learned() { + let assembler = |hits: u64| Counters { + totals: Totals { + requests: hits, + hits, + ..Totals::default() + }, + ns: [hits * 1_000_000_000, 0, 0], + langs: vec![("Assembler".to_owned(), [hits, 0, 0])], + ..Counters::default() + }; + let snapshot = stats::Snapshot { + counters: assembler(3187), + ..stats::Snapshot::default() + }; + let mut st = state( + vec![ + reading(0, 0, 0, 0), + Reading { + t: 60, + c: assembler(10), + }, + ], + None, + ); + st.live = Some(Live { + at: 120, + snapshot, + raw_text: String::new(), + }); + let ts = build(&st, Range::Day, 120).time_saved; + assert_eq!( + (ts.seconds, ts.hits_left_out), + (0.0, 10 + 3177), + "10 hits in the saved reading, 3,177 more in the live one" + ); + assert!( + ts.note + .starts_with("Nothing is counted: no build time has been learned yet"), + "{}", + ts.note + ); + assert!(ts.note.ends_with("3,187 hits left out."), "{}", ts.note); + + let only_misses = build(&state(vec![reading(0, 0, 0, 5)], None), Range::Day, 60).time_saved; + assert_eq!( + ( + only_misses.seconds, + only_misses.hits_left_out, + only_misses.note.as_str() + ), + ( + 0.0, + 0, + "There were no hits in this range, so nothing was saved." + ) + ); + } + + #[test] + fn both_hit_rates_and_the_summary_text() { + let v = build(&taught(), Range::Day, 240); + assert_eq!( + v.totals.hit_rate(), + Some(3044.0 / 3047.0), + "hits out of cacheable compiles" + ); + assert_eq!( + v.totals.hit_rate_of_all(), + Some(3044.0 / 3047.0), + "here every request was a cacheable compile" + ); + let mixed = Totals { + requests: 100, + executed: 80, + hits: 40, + misses: 40, + not_cacheable: 20, + ..Totals::default() + }; + assert_eq!( + (mixed.hit_rate(), mixed.hit_rate_of_all()), + (Some(0.5), Some(0.4)), + "the second counts every compiler call" + ); + assert_eq!( + v.summary_markdown, + "**sccache, last 24 hours**\n\ + - Hit rate: 99.9% (3,044 of 3,047 compiles from cache)\n\ + - By language: C/C++ 100%, Assembler 100%, Rust 98.7%\n\ + - Not cacheable: 0 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\ + - Time saved: ~3h 47m (rough)\n\ + - Cache: local disk, 10.0 of 10.0 GB \u{b7} sccache 0.18.0\n" + ); + assert!(build(&taught(), Range::Hour, 240) + .summary_markdown + .starts_with("**sccache, last hour**\n")); + assert!(build(&taught(), Range::Week, 240) + .summary_markdown + .starts_with("**sccache, last 7 days**\n")); + assert!(build(&taught(), Range::Month, 240) + .summary_markdown + .starts_with("**sccache, last 30 days**\n")); + + let st = State { + live: Some(Live { + at: 100, + raw_text: LIVE.to_owned(), + snapshot: stats::parse(LIVE).unwrap(), + }), + client_version: Some("0.18.0".to_owned()), + ..State::default() + }; + assert_eq!( + build(&st, Range::SinceReset, 100).summary_markdown, + "**sccache, since last reset**\n\ + - Hit rate: 49.5% (3,197 of 6,453 compiles from cache)\n\ + - By language: Rust 6.6%, C/C++ 100%, Assembler 100%\n\ + - Not cacheable: 856 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\ + - Cache: local disk, 10.0 of 10.0 GB \u{b7} sccache 0.18.0\n", + "nothing is learned, so there is no time-saved line" + ); + assert_eq!( + titles(&seen(|_| {}, "0.18.0")), + Vec::<&str>::new(), + "and the untouched starting point has no problems" + ); + let empty = build(&State::default(), Range::Hour, 0); + assert_eq!( + empty.summary_markdown, + "**sccache, last hour**\n\ + - Hit rate: \u{2014} (no cacheable compiles)\n\ + - By language: (none)\n\ + - Not cacheable: 0 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\ + - Cache: unknown location, size unknown \u{b7} sccache unknown version\n" + ); + } + + #[test] + fn every_problem_and_its_level() { + const GIB: u64 = 1024 * 1024 * 1024; + let v = seen(|s| s.cache_size = Some(9 * GIB), "0.18.0"); + assert_eq!( + titles(&v), + ["Cache 90% full"], + "exactly 90% of the 10 GiB limit is a problem" + ); + assert_eq!(v.problems[0].severity, Severity::Warning); + assert!(v.problems[0] + .detail + .starts_with("The cache holds 9.0 of 10.0 GB, close to its limit;")); + assert!( + seen(|s| s.cache_size = Some(9 * GIB - 1), "0.18.0") + .problems + .is_empty(), + "one byte under is not" + ); + assert!( + seen(|s| s.max_cache_size = None, "0.18.0") + .problems + .is_empty(), + "nor is an unknown limit" + ); + assert_eq!( + titles(&seen(|s| s.cache_size = Some(10 * GIB), "0.18.0")), + ["Cache 100% full"] + ); + + let over = |timeouts| { + seen( + |s| { + s.counters.totals.executed = 1000; + s.counters.totals.timeouts = timeouts; + }, + "0.18.0", + ) + }; + assert_eq!( + titles(&over(11)), + ["Timeouts 1.1%"], + "11 of 1,000 executed compiles" + ); + assert!(over(10).problems.is_empty(), "exactly 1% is not over 1%"); + assert!( + seen(|s| s.counters.totals.timeouts = 50, "0.18.0") + .problems + .is_empty(), + "50 of 6,495 is not either" + ); + + let rate = |langs: Vec<(&str, [u64; 3])>| { + seen( + |s| s.counters.langs = langs.into_iter().map(|(n, v)| (n.to_owned(), v)).collect(), + "0.18.0", + ) + }; + assert_eq!( + titles(&rate(vec![("Rust", [4, 46, 0])])), + ["Rust hit rate 8%"] + ); + assert!(rate(vec![("Rust", [4, 46, 0])]).problems[0] + .detail + .starts_with("Only 8% of 50 Rust compiles came from the cache, so most were rebuilt;")); + assert!( + rate(vec![("Rust", [19, 30, 0])]).problems.is_empty(), + "49 compiles is too few to say" + ); + assert!( + rate(vec![("Rust", [20, 30, 0])]).problems.is_empty(), + "40% is not under 40%" + ); + assert!( + rate(vec![("Rust", [49, 1, 0])]).problems.is_empty(), + "a high hit rate is fine" + ); + assert_eq!( + titles(&rate(vec![("C", [1, 49, 0]), ("Rust", [4, 46, 0])])), + ["C hit rate 2%", "Rust hit rate 8%"], + "worst first" + ); + + let v = seen(|s| s.counters.totals.read_errors = 1, "0.18.0"); + assert_eq!( + (v.problems[0].severity, v.problems[0].title.as_str()), + (Severity::Error, "1 cache error") + ); + assert!(v.problems[0].detail.contains( + "1 time in this range (1 read, 0 write, 0 other) and those compiles ran from scratch;" + )); + assert_eq!( + titles(&seen(|s| s.counters.totals.write_errors = 2, "0.18.0")), + ["2 cache errors"] + ); + assert_eq!( + titles(&seen(|s| s.counters.totals.other_errors = 3, "0.18.0")), + ["3 cache errors"], + "per-language cache errors count too" + ); + + let v = seen(|_| {}, "0.19.0"); + assert_eq!( + ( + v.problems.len(), + v.problems[0].severity, + v.problems[0].title.as_str() + ), + (1, Severity::Warning, "sccache versions differ") + ); + assert!(v.problems[0] + .detail + .contains("The running sccache server is 0.18.0 but the `sccache` command is 0.19.0")); + + let off = State { + error: Some("`sccache --show-stats --stats-format json`: command not found".to_owned()), + ..State::default() + }; + let v = build(&off, Range::Hour, 100); + assert_eq!(v.server.status, Status::NotRunning); + assert_eq!( + v.server.error.as_deref(), + Some("`sccache --show-stats --stats-format json`: command not found") + ); + assert_eq!( + ( + v.problems.len(), + v.problems[0].severity, + v.problems[0].title.as_str() + ), + (1, Severity::Error, "sccache is not running") + ); + assert!(v.problems[0] + .detail + .contains("run `sccache --show-stats` yourself to see what it says.")); + + let all = seen( + |s| { + s.cache_size = Some(10 * GIB); + s.counters.totals.timeouts = 300; + s.counters.totals.read_errors = 4; + s.counters.langs = vec![("Rust".to_owned(), [4, 46, 0])]; + }, + "0.19.1", + ); + assert_eq!( + all.problems + .iter() + .map(|p| (p.severity, p.title.as_str())) + .collect::>(), + vec![ + (Severity::Error, "4 cache errors"), + (Severity::Warning, "Timeouts 4.6%"), + (Severity::Warning, "Rust hit rate 8%"), + (Severity::Warning, "Cache 100% full"), + (Severity::Warning, "sccache versions differ"), + ], + "most serious first" + ); + assert!( + all.problems + .iter() + .all(|p| p.detail.split(". ").count() == 1 && p.detail.ends_with('.')), + "each detail is one sentence: {:?}", + all.problems + ); + } + + #[test] + fn running_means_compiles_in_the_last_five_minutes() { + let readings = vec![reading(0, 0, 0, 0), reading(1000, 5, 0, 5)]; + assert_eq!( + build(&quiet_since(readings.clone(), 1200), Range::Hour, 1200) + .server + .status, + Status::Running, + "a compile 200 s ago" + ); + assert_eq!( + build(&quiet_since(readings, 1300), Range::Hour, 1300) + .server + .status, + Status::Idle, + "the last compile was 300 s ago" + ); + assert_eq!( + build(&state(vec![reading(0, 0, 0, 5)], None), Range::Hour, 100) + .server + .status, + Status::NotRunning, + "no live reading at all" + ); + + let c = stats::parse(LIVE).unwrap().counters; + let mut changed = c.clone(); + changed.totals.requests -= 3; + let quiet = state(vec![Reading { t: 0, c }], Some((1100, LIVE))); + assert_eq!( + build(&quiet, Range::Hour, 1100).server.status, + Status::Idle, + "nothing changed since the last reading" + ); + let busy = state(vec![Reading { t: 0, c: changed }], Some((1100, LIVE))); + assert_eq!( + build(&busy, Range::Hour, 1100).server.status, + Status::Running, + "the live reading saw three compiles" + ); + } +} diff --git a/crates/server/tests/http.rs b/crates/server/tests/http.rs new file mode 100644 index 0000000..6e67cc5 --- /dev/null +++ b/crates/server/tests/http.rs @@ -0,0 +1,310 @@ +//! The server as seen from a socket, with a stand-in for sccache so that the real one is never touched. + +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream}; +use std::os::unix::fs::PermissionsExt; +use std::path::PathBuf; +use std::sync::Arc; +use std::thread; + +use sccache_dash::app::{unix_now, App, Config}; +use sccache_dash::stats; +use sccache_dash::view; +use sccache_dash_api::{Range, Status, Totals, View}; + +const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json"); +const ZEROED: &str = "{\"stats\":{\"compile_requests\":0,\"cache_hits\":{\"counts\":{},\"adv_counts\":{}},\"cache_misses\":{\"counts\":{},\"adv_counts\":{}},\"cache_errors\":{\"counts\":{},\"adv_counts\":{}}},\"version\":\"0.18.0\"}"; +const NOW: i64 = 1_764_000_000; + +/// A script that answers like sccache: it prints a fixture for `--show-stats` and swaps in +/// `ZEROED` when asked to zero the stats. Every call is logged. +struct Fake { + _dir: tempfile::TempDir, + script: PathBuf, + log: PathBuf, + history: PathBuf, +} + +impl Fake { + fn new() -> Fake { + let dir = tempfile::tempdir().unwrap(); + let script = dir.path().join("sccache"); + std::fs::write( + &script, + r#"#!/bin/sh +printf '%s\n' "$*" >> "$0.log" +case "$1" in + --version) echo 'sccache 0.18.0' ;; + --zero-stats) cp "$0.zeroed" "$0.out" ;; + *) cat "$0.out" ;; +esac +"#, + ) + .unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + std::fs::write(dir.path().join("sccache.out"), LIVE).unwrap(); + std::fs::write(dir.path().join("sccache.zeroed"), ZEROED).unwrap(); + Fake { + script, + log: dir.path().join("sccache.log"), + history: dir.path().join("data").join("history.jsonl"), + _dir: dir, + } + } + + /// The arguments of every call so far, one entry per call. + fn calls(&self) -> Vec { + std::fs::read_to_string(&self.log) + .unwrap_or_default() + .lines() + .map(str::to_owned) + .collect() + } +} + +/// A server on a free port, polled once, answering in the background. +fn start(fake: &Fake) -> (Arc, SocketAddr) { + let cfg = Config { + sccache: fake.script.clone().into(), + history: fake.history.clone(), + }; + let app = Arc::new(App::new(cfg, NOW).unwrap()); + app.poll_at(NOW); + let server = tiny_http::Server::http("127.0.0.1:0").unwrap(); + let addr = server.server_addr().to_ip().unwrap(); + let answering = Arc::clone(&app); + thread::spawn(move || sccache_dash::http::answer(server, answering)); + (app, addr) +} + +/// Sends one raw request (`{port}` stands for the server's port) and returns the whole response. +fn send(addr: SocketAddr, request: &str) -> String { + let request = request.replace("{port}", &addr.port().to_string()); + let mut stream = TcpStream::connect(addr).unwrap(); + stream.write_all(request.as_bytes()).unwrap(); + let mut response = String::new(); + stream.read_to_string(&mut response).unwrap(); + response +} + +const GET: &str = " HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n"; + +/// `POST /api/zero` with the given `Host` and `Origin` headers; returns the status and the response. +fn zero(addr: SocketAddr, host: Option<&str>, origin: Option<&str>) -> (u16, String) { + let mut request = String::from("POST /api/zero HTTP/1.1\r\n"); + for (name, value) in [("Host:", host), ("Origin:", origin)] { + if let Some(value) = value { + request.push_str(&format!("{name} {value}\r\n")); + } + } + request.push_str("Content-Length: 0\r\nConnection: close\r\n\r\n"); + let response = send(addr, &request); + let code = response + .split_whitespace() + .nth(1) + .and_then(|c| c.parse().ok()); + (code.unwrap_or(0), response) +} + +#[test] +fn zero_is_refused_for_a_foreign_origin_or_host() { + let fake = Fake::new(); + let (app, addr) = start(&fake); + + // A page anywhere else, in any shape: a bare host, another port, or "null". + for origin in [ + "https://evil.example", + "http://127.0.0.1:1", + "http://localhost.evil.example:{port}", + "null", + ] { + let (code, response) = zero(addr, Some("127.0.0.1:{port}"), Some(origin)); + assert_eq!( + (code, response.contains("refused")), + (403, true), + "Origin {origin}" + ); + } + // A host name that merely leads here (DNS rebinding) or is not plainly localhost. + for host in [ + "evil.example:{port}", + "127.0.0.1.evil.example:{port}", + "localhost:{port}@evil.example", + "[::1]:{port}", + ] { + let (code, _) = zero(addr, Some(host), None); + assert_eq!(code, 403, "Host {host}"); + } + let (code, _) = zero(addr, None, None); + assert_eq!(code, 403, "no Host at all"); + + assert!( + !fake.calls().iter().any(|c| c == "--zero-stats"), + "sccache was never asked to zero: {:?}", + fake.calls() + ); + assert_eq!(app.lock().readings.len(), 1, "and the history is as it was"); +} + +#[test] +fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() { + let fake = Fake::new(); + let (app, addr) = start(&fake); + assert_eq!( + app.lock().readings.len(), + 1, + "the first reading is saved as the baseline" + ); + + let (code, response) = zero( + addr, + Some("127.0.0.1:{port}"), + Some("http://127.0.0.1:{port}"), + ); + assert_eq!( + (code, response.contains("the saved history is kept")), + (200, true), + "{response}" + ); + assert_eq!( + zero(addr, Some("localhost:{port}"), None).0, + 200, + "no Origin, as from curl" + ); + + let calls = fake.calls(); + assert_eq!(calls.iter().filter(|c| *c == "--zero-stats").count(), 2); + assert_eq!( + calls.last().unwrap(), + "--show-stats --stats-format json", + "the counters are read again right after zeroing" + ); + + let state = app.lock(); + assert_eq!( + state.readings.len(), + 2, + "the baseline is kept and a line was added for the reset" + ); + assert_eq!(state.intervals.len(), 1); + assert!( + state.intervals[0].reset, + "the zeroing shows in the history as a reset" + ); + let v = view::build(&state, Range::SinceReset, unix_now()); + assert_eq!( + v.totals, + Totals::default(), + "sccache's counters read zero now" + ); + assert!(v.buckets[0].reset); +} + +#[test] +fn view_export_and_the_page_answer() { + let fake = Fake::new(); + let (_app, addr) = start(&fake); + + let response = send(addr, &format!("GET /api/view?range=reset{GET}")); + assert!( + response.starts_with("HTTP/1.1 200 OK\r\n") + && response.contains("Content-Type: application/json\r\n"), + "{response}" + ); + let body = response.split("\r\n\r\n").nth(1).unwrap(); + let v: View = serde_json::from_str(body).unwrap(); + assert_eq!(v.totals, stats::parse(LIVE).unwrap().counters.totals); + assert_eq!( + (v.range, v.server.status), + (Some(Range::SinceReset), Status::Idle) + ); + assert_eq!( + ( + v.server.version.as_deref(), + v.server.client_version.as_deref() + ), + (Some("0.18.0"), Some("0.18.0")) + ); + assert!(v + .summary_markdown + .starts_with("**sccache, since last reset**\n")); + + let response = send(addr, &format!("GET /api/export{GET}")); + assert!( + response.contains("Content-Type: application/json\r\n"), + "{response}" + ); + assert!( + response.contains(&format!( + "Content-Disposition: attachment; filename=\"sccache-stats-{}.json\"", + sccache_dash::pretty::stamp(NOW) + )), + "{response}" + ); + assert!(response.ends_with(LIVE), "exactly as sccache printed it"); + + let response = send(addr, &format!("GET /{GET}")); + assert!( + response.starts_with("HTTP/1.1 200 OK\r\n") + && response.contains("Content-Type: text/html; charset=utf-8\r\n"), + "{response}" + ); + assert!(send(addr, &format!("HEAD /{GET}")).starts_with("HTTP/1.1 200 OK\r\n")); + + assert!(send(addr, &format!("GET /api/view?range=bogus{GET}")).starts_with("HTTP/1.1 400")); + assert!( + send(addr, &format!("GET /api/view{GET}")).starts_with("HTTP/1.1 400"), + "no range at all" + ); + assert!(send(addr, &format!("GET /../Cargo.toml{GET}")).starts_with("HTTP/1.1 404")); + assert!(send(addr, &format!("GET /no-such-file.wasm{GET}")).starts_with("HTTP/1.1 404")); + assert!(send(addr, &format!("PUT /api/zero{GET}")).starts_with("HTTP/1.1 405")); +} + +#[test] +fn lines_are_saved_when_counters_change_and_at_most_once_a_minute() { + let fake = Fake::new(); + let cfg = Config { + sccache: fake.script.clone().into(), + history: fake.history.clone(), + }; + let app = App::new(cfg, NOW).unwrap(); + let lines = |app: &App| app.lock().readings.len(); + + app.poll_at(NOW); + assert_eq!(lines(&app), 1, "the first reading is the baseline"); + app.poll_at(NOW + 10); + assert_eq!(lines(&app), 1, "nothing changed"); + + std::fs::write( + fake._dir.path().join("sccache.out"), + LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"), + ) + .unwrap(); + app.poll_at(NOW + 30); + assert_eq!( + lines(&app), + 1, + "changed, but less than a minute after the last line" + ); + app.poll_at(NOW + 60); + assert_eq!( + lines(&app), + 2, + "a minute after the last line, the change is saved" + ); + assert_eq!(app.lock().intervals[0].delta.totals.requests, 1); + + app.poll_at(NOW + 60 + sccache_dash::app::HEARTBEAT_SECS - 1); + assert_eq!(lines(&app), 2, "unchanged, and not yet ten minutes"); + app.poll_at(NOW + 60 + sccache_dash::app::HEARTBEAT_SECS); + assert_eq!( + lines(&app), + 3, + "every ten minutes a line marks that the service is running" + ); + assert!( + app.lock().intervals[1].delta.totals == Totals::default(), + "the heartbeat line records no change" + ); +} diff --git a/fixtures/sample-dist.json b/fixtures/sample-dist.json new file mode 100644 index 0000000..ca86992 --- /dev/null +++ b/fixtures/sample-dist.json @@ -0,0 +1 @@ +{"stats":{"compile_requests":820,"requests_unsupported_compiler":0,"requests_not_compile":2,"requests_not_cacheable":18,"requests_executed":800,"cache_errors":{"counts":{},"adv_counts":{}},"cache_hits":{"counts":{"C/C++":3},"adv_counts":{"c [gcc]":3}},"cache_misses":{"counts":{"C/C++":797},"adv_counts":{"c [gcc]":797}},"cache_timeouts":0,"cache_read_errors":0,"non_cacheable_compilations":0,"forced_recaches":0,"cache_write_errors":0,"cache_writes":797,"cache_write_duration":{"secs":9,"nanos":0},"cache_read_hit_duration":{"secs":0,"nanos":3000000},"compilations":797,"compiler_write_duration":{"secs":1200,"nanos":0},"compile_fails":0,"not_cached":{},"dist_compiles":{"10.0.0.12:4226":379,"buildbox.local:4228":9,"10.0.0.11:4226":402},"dist_errors":7,"multi_level":null},"cache_location":"Local disk: \"/home/me/.cache/sccache\"","cache_size":107374182,"max_cache_size":1073741824,"use_preprocessor_cache_mode":false,"version":"0.18.0","basedirs":[]} diff --git a/fixtures/sample-multilevel.json b/fixtures/sample-multilevel.json new file mode 100644 index 0000000..630d77f --- /dev/null +++ b/fixtures/sample-multilevel.json @@ -0,0 +1 @@ +{"stats":{"compile_requests":5000,"requests_unsupported_compiler":0,"requests_not_compile":12,"requests_not_cacheable":150,"requests_executed":4838,"cache_errors":{"counts":{},"adv_counts":{}},"cache_hits":{"counts":{"C/C++":2100,"Rust":400},"adv_counts":{"c [gcc]":2100,"rust":400}},"cache_misses":{"counts":{"Rust":2300,"C/C++":38},"adv_counts":{"rust":2300,"c [gcc]":38}},"cache_timeouts":12,"cache_read_errors":0,"non_cacheable_compilations":0,"forced_recaches":0,"cache_write_errors":5,"cache_writes":2338,"cache_write_duration":{"secs":40,"nanos":0},"cache_read_hit_duration":{"secs":0,"nanos":600000000},"compilations":2338,"compiler_write_duration":{"secs":18000,"nanos":0},"compile_fails":0,"not_cached":{"crate-type":150},"dist_compiles":{},"dist_errors":0,"multi_level":[{"name":"L0 (disk)","location":"Local disk: \"/home/me/.cache/sccache\"","hits":1500,"misses":1000,"writes":1400,"write_failures":2,"backfills_from":300,"backfills_to":0,"hit_duration":{"secs":1,"nanos":500000000},"write_duration":{"secs":2,"nanos":500000000}},{"name":"L1 (s3)","location":"s3, name: bucket, prefix: /p/","hits":1000,"misses":1800,"writes":900,"write_failures":0,"backfills_from":0,"backfills_to":300,"hit_duration":{"secs":6,"nanos":0},"write_duration":{"secs":36,"nanos":500000000}}]},"cache_location":"Multi-level: \"L0 (disk)\" + \"L1 (s3)\"","cache_size":1234567890,"max_cache_size":10737418240,"use_preprocessor_cache_mode":true,"version":"0.18.0","basedirs":[]} diff --git a/justfile b/justfile new file mode 100644 index 0000000..2c57a22 --- /dev/null +++ b/justfile @@ -0,0 +1,10 @@ +# Build the page first, then the server with the page inside it. +build: + cd crates/ui && trunk build --release + cargo build --release -p sccache-dash + +test: + cargo test -p sccache-dash -p sccache-dash-api + +run: + cargo run -p sccache-dash