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..407c2b5 --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# 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.db` (`~/.local/share/...` by default): one SQLite file. Its +`readings` table holds one row a minute at most, and only when sccache's counters changed; each +row is the difference since the row before it, so a range total is one indexed query. Per-language +counts and not-cacheable reasons sit in their own tables, and `build_obs` holds what the polls saw +of how long a build of each language takes. A stretch without rows is a gap. Rows older than 30 +days are deleted at startup and once a day. Deleting the file loses the history and nothing else. + +The five views (one per range) are made after every poll and kept in memory, so a request never +waits for the database. + +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..f19863b --- /dev/null +++ b/crates/server/Cargo.toml @@ -0,0 +1,19 @@ +[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" +rusqlite = { version = "0.37", features = ["bundled"] } +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..78d967b --- /dev/null +++ b/crates/server/src/app.rs @@ -0,0 +1,283 @@ +//! 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::mpsc::{channel, Receiver, Sender}; +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::{History, Tracker}; +use crate::stats::{self, Snapshot}; +use crate::view; + +/// How often sccache is asked for its counters. +pub const POLL: Duration = Duration::from_secs(10); +/// 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); +/// The ranges a view is kept for, in the order they are cached. +pub const RANGES: [Range; 5] = [ + Range::Hour, + Range::Day, + Range::Week, + Range::Month, + Range::SinceReset, +]; + +pub struct Config { + /// The sccache command the service runs. + pub sccache: OsString, + /// The SQLite file the history is saved in. + pub history: PathBuf, +} + +impl Config { + /// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset); the history + /// lives in `$XDG_DATA_HOME/sccache-dash/history.db`. + 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.db"), + }) + } +} + +pub fn unix_now() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs() as i64) +} + +/// 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 { + 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, + /// What the previous poll and the last saved row saw. + pub tracker: Tracker, + /// One view per range of [`RANGES`], made after every poll. + pub views: Vec, + /// How long making those views took at the last poll. + pub views_took: Duration, + /// Whether a failure to save, and the first timing, have already been reported. + pub reported: bool, +} + +pub struct App { + pub cfg: Config, + state: Mutex, + /// Wakes the polling task, as `/api/zero` needs: only that task holds the database. + wake: (Sender<()>, Mutex>>), +} + +impl App { + pub fn new(cfg: Config) -> App { + let (send, receive) = channel(); + App { + cfg, + state: Mutex::new(State::default()), + wake: (send, Mutex::new(Some(receive))), + } + } + + pub fn lock(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// The view made for `range` at the last poll. A request never touches the database. + pub fn view(&self, range: Range) -> View { + let state = self.lock(); + match state.views.get(index(range)) { + Some(view) => view.clone(), + None => View { + range: Some(range), + ..View::default() + }, + } + } + + /// Opens the history for the polling task: what is too old is deleted, and what the + /// previous run remembered is taken over. + pub fn open_history(&self, now: i64) -> Result { + let file = self.cfg.history.display().to_string(); + let history = + History::open(&self.cfg.history).map_err(|e| format!("cannot open {file}: {e}"))?; + history + .prune(now) + .map_err(|e| format!("cannot prune {file}: {e}"))?; + self.lock().tracker = history.tracker(); + Ok(history) + } + + pub fn poll(&self, history: &History) { + self.poll_at(history, unix_now()); + } + + /// Asks sccache for its counters and version, records what changed, and makes the views. + pub fn poll_at(&self, history: &History, 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)) => { + state.error = None; + state.raw = serde_json::from_str(&text).ok(); + state.live = Some(Live { + at: now, + snapshot, + raw_text: text, + }); + } + Err(e) => { + state.error = Some(e); + state.live = None; + state.raw = None; + } + } + let file = self.cfg.history.display().to_string(); + if let Some(counters) = state.live.as_ref().map(|l| l.snapshot.counters.clone()) { + match history.record(&mut state.tracker, &counters, now) { + Ok(()) => {} + Err(e) if !state.reported => { + state.reported = true; + eprintln!("sccache-dash: cannot save history to {file}: {e}"); + } + Err(_) => {} + } + } + let started = Instant::now(); + state.views = view::all(history, &state, now); + state.views_took = started.elapsed(); + if !state.reported { + state.reported = true; + eprintln!( + "sccache-dash: {} rows of history in {}; the five views take {:.2} ms per poll", + history.row_count().unwrap_or(0), + file, + state.views_took.as_secs_f64() * 1e3 + ); + } + } + + /// Runs `sccache --zero-stats`; the saved history stays as it is. + pub fn zero(&self) -> Result<(), String> { + run(&self.cfg.sccache, &["--zero-stats"])?; + // The counters are read again right away by the polling task, which owns the database. + let _ = self.wake.0.send(()); + Ok(()) + } + + /// Polls sccache every [`POLL`] (sooner when woken) and prunes the history once a day, + /// until the process ends. This task alone holds the database. + pub fn keep_updated(self: Arc) { + thread::spawn(move || { + let history = match self.open_history(unix_now()) { + Ok(history) => history, + Err(e) => { + eprintln!("sccache-dash: {e}"); + std::process::exit(1); + } + }; + let wake = self + .wake + .1 + .lock() + .unwrap_or_else(PoisonError::into_inner) + .take(); + let mut pruned = Instant::now(); + loop { + self.poll(&history); + if pruned.elapsed() >= PRUNE_EVERY { + pruned = Instant::now(); + if let Err(e) = history.prune(unix_now()) { + eprintln!( + "sccache-dash: cannot prune {}: {e}", + self.cfg.history.display() + ); + } + } + match &wake { + Some(receiver) => { + let _ = receiver.recv_timeout(POLL); + } + None => thread::sleep(POLL), + } + } + }); + } +} + +/// Where a range's view is kept. +fn index(range: Range) -> usize { + RANGES.iter().position(|r| *r == range).unwrap_or(1) +} + +/// 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..8c451cc --- /dev/null +++ b/crates/server/src/history.rs @@ -0,0 +1,371 @@ +//! The saved history in one SQLite file. Each row holds what changed since the row before it, +//! so that a range total is one indexed `SELECT SUM(...)`. Rows come at most one a minute and +//! only when sccache's counters changed; a stretch without rows is a gap. + +use std::collections::BTreeMap; +use std::path::Path; +use std::time::Duration; + +use rusqlite::{params, params_from_iter, Connection, OptionalExtension}; +use sccache_dash_api::Totals; +use serde::{de::DeserializeOwned, Deserialize, Serialize}; + +use crate::stats::{Counters, COMPILE}; + +/// Rows older than this are deleted. +pub const KEEP_DAYS: i64 = 30; +/// Never more than one saved row per minute. +pub const MIN_ROW_SECS: i64 = 60; + +const NANOS: f64 = 1e9; + +/// The counters of a reading, each visited once: every query goes through this list. +macro_rules! each { + ($m:ident!($($a:tt)*)) => { + $m!(requests, executed, hits, misses, not_cacheable, unsupported_compiler, not_compile, + timeouts, read_errors, write_errors, other_errors, compile_fails, forced_recaches, + cache_writes; $($a)*) + }; +} +macro_rules! names { + ($($c:ident),* ;) => { concat!($(",", stringify!($c)),*) }; +} +macro_rules! defs { + ($($c:ident),* ;) => { concat!($(",", stringify!($c), " INTEGER NOT NULL DEFAULT 0"),*) }; +} +macro_rules! sums { + ($($c:ident),* ;) => { concat!($(", SUM(", stringify!($c), ") AS ", stringify!($c)),*) }; +} +macro_rules! totals_of { + ($($c:ident),* ; $row:expr) => { Totals { $( $c: $row.get::<_, i64>(stringify!($c))?.max(0) as u64, )* } }; +} +macro_rules! push { + ($($c:ident),* ; $t:expr, $v:expr) => { $( $v.push(Box::new($t.$c as i64) as Box); )* }; +} + +const NAMES: &str = each!(names!()); +const DEFS: &str = each!(defs!()); +const SUMS: &str = each!(sums!()); +/// One point of the histogram of build times: the builds of one language that finished between +/// two polls ten seconds apart. +#[derive(Clone, Debug, PartialEq)] +pub struct BuildObs { + pub t: i64, + pub language: String, + pub compiles: u64, + pub seconds: f64, +} + +/// What is remembered between polls, so that differences survive a restart of sccache-dash. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct Tracker { + /// The running totals at the previous poll. + pub last_poll: Option, + /// The running totals when the last row was saved. + pub row_base: Option, + /// When the last row was saved. + pub row_at: i64, +} + +/// One saved row: when it was written, and what had changed since the row before. +#[derive(Clone, Debug, PartialEq)] +pub struct Row { + pub t: i64, + /// sccache's counters went back to zero before this row. + pub reset: bool, + pub delta: Counters, +} + +pub struct History { + conn: Connection, +} + +impl History { + /// Opens (or creates) the file in WAL mode. The connection belongs to the task that polls. + pub fn open(path: &Path) -> Result { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + Self::init(Connection::open(path).map_err(|e| format!("{}: {e}", path.display()))?) + .map_err(|e| e.to_string()) + } + + /// An empty history that is never written to disk, for tests. + pub fn memory() -> rusqlite::Result { + Self::init(Connection::open_in_memory()?) + } + + fn init(conn: Connection) -> rusqlite::Result { + let _: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?; + conn.busy_timeout(Duration::from_secs(5))?; + conn.execute_batch(&format!( + "CREATE TABLE IF NOT EXISTS readings (t INTEGER PRIMARY KEY, reset INTEGER NOT NULL DEFAULT 0{DEFS}, \ + compilations INTEGER NOT NULL DEFAULT 0, hit_read REAL NOT NULL DEFAULT 0, \ + cache_write REAL NOT NULL DEFAULT 0, compile REAL NOT NULL DEFAULT 0);\n{OTHER_TABLES}" + ))?; + Ok(History { conn }) + } + + /// Deletes the rows older than [`KEEP_DAYS`], and says how many went. + pub fn prune(&self, now: i64) -> rusqlite::Result { + let cutoff = now - KEEP_DAYS * 86_400; + let mut gone = 0; + for table in ["readings", "reading_languages", "not_cached", "build_obs"] { + gone += self + .conn + .execute(&format!("DELETE FROM {table} WHERE t < ?1"), [cutoff])?; + } + Ok(gone) + } + + fn state(&self, key: &str) -> Option { + let text: Option = self + .conn + .query_row("SELECT value FROM state WHERE key = ?1", [key], |row| { + row.get(0) + }) + .optional() + .ok()?; + text.and_then(|text| serde_json::from_str(&text).ok()) + } + + fn set_state(&self, key: &str, value: &T) -> rusqlite::Result<()> { + let value = serde_json::to_string(value) + .map_err(|e| rusqlite::Error::ToSqlConversionFailure(Box::new(e)))?; + self.conn.execute( + "INSERT INTO state (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", + params![key, value], + )?; + Ok(()) + } + + /// What the previous run of sccache-dash remembered, so that it carries on where it stopped. + pub fn tracker(&self) -> Tracker { + self.state("tracker").unwrap_or_default() + } + + /// Records what a poll saw at `now`: a build-time observation when one language's builds + /// finished since the previous poll, a row when one is due and something changed, and the + /// totals for next time. + pub fn record(&self, tracker: &mut Tracker, c: &Counters, now: i64) -> rusqlite::Result<()> { + if let Some(previous) = &tracker.last_poll { + let (since, _) = c.since(previous); + if let Some((language, _)) = since.one_missed_language() { + let seconds = since.ns[COMPILE] as f64 / NANOS; + self.conn.execute( + "INSERT OR REPLACE INTO build_obs (t, language, compiles, seconds) VALUES (?1, ?2, ?3, ?4)", + params![now, language, since.compilations as i64, seconds], + )?; + } + } + // The first reading ever is a baseline. After it: a row a minute at most, and only when something changed. + match &tracker.row_base { + None => { + tracker.row_base = Some(c.clone()); + tracker.row_at = now; + } + Some(base) => { + let (diff, reset) = c.since(base); + let changed = diff != Counters::default() || reset; + if changed && now - tracker.row_at >= MIN_ROW_SECS { + self.save(now, &diff, reset)?; + tracker.row_base = Some(c.clone()); + tracker.row_at = now; + } + } + } + tracker.last_poll = Some(c.clone()); + self.set_state("tracker", tracker) + } + + /// Writes what changed since the row before. + fn save(&self, t: i64, diff: &Counters, reset: bool) -> rusqlite::Result<()> { + let mut values: Vec> = vec![Box::new(t), Box::new(reset)]; + each!(push!(diff.totals, values)); + values.push(Box::new(diff.compilations as i64)); + for n in diff.ns { + values.push(Box::new(n as f64 / NANOS)); + } + let marks = vec!["?"; NAMES.matches(',').count()].join(", "); + let sql = format!( + "INSERT INTO readings (t, reset{NAMES}, compilations, hit_read, cache_write, compile) VALUES (?, ?, {marks}, ?, ?, ?, ?)" + ); + self.conn + .execute(&sql, params_from_iter(values.iter().map(|v| v.as_ref())))?; + let mut langs = self.conn.prepare( + "INSERT INTO reading_languages (t, language, hits, misses, errors) VALUES (?1, ?2, ?3, ?4, ?5)", + )?; + for (name, v) in &diff.langs { + langs.execute(params![t, name, v[0] as i64, v[1] as i64, v[2] as i64])?; + } + let mut reasons = self + .conn + .prepare("INSERT INTO not_cached (t, reason, count) VALUES (?1, ?2, ?3)")?; + for (reason, count) in &diff.not_cached { + reasons.execute(params![t, reason, *count as i64])?; + } + Ok(()) + } + + /// The totals of the rows from `from` (inclusive) to `to` (exclusive): one indexed query. + /// `None` when there is no row in that time. + pub fn sums(&self, from: i64, to: i64) -> rusqlite::Result> { + let sql = format!("SELECT COUNT(*){SUMS} FROM readings WHERE t >= ?1 AND t < ?2"); + self.conn.query_row(&sql, params![from, to], |row| { + let rows: i64 = row.get(0)?; + Ok(if rows > 0 { + Some(each!(totals_of!(row))) + } else { + None + }) + }) + } + + /// The rows from `from` (inclusive) to `to` (exclusive), oldest first. + pub fn rows(&self, from: i64, to: i64) -> rusqlite::Result> { + let sql = format!( + "SELECT t, reset{NAMES}, compilations, hit_read, cache_write, compile FROM readings WHERE t >= ?1 AND t < ?2 ORDER BY t" + ); + let mut stmt = self.conn.prepare(&sql)?; + let rows = stmt.query_map(params![from, to], |row| { + let nanos = |name: &str| -> rusqlite::Result { + Ok((row.get::<_, f64>(name)? * NANOS).round().max(0.0) as u64) + }; + Ok(Row { + t: row.get("t")?, + reset: row.get::<_, i64>("reset")? != 0, + delta: Counters { + totals: each!(totals_of!(row)), + compilations: row.get::<_, i64>("compilations")?.max(0) as u64, + ns: [nanos("hit_read")?, nanos("cache_write")?, nanos("compile")?], + ..Counters::default() + }, + }) + })?; + rows.collect() + } + + /// (language, hits, misses, errors) summed over the rows from `from` to `to`. + pub fn languages(&self, from: i64, to: i64) -> rusqlite::Result> { + let mut stmt = self.conn.prepare( + "SELECT language, SUM(hits), SUM(misses), SUM(errors) FROM reading_languages WHERE t >= ?1 AND t < ?2 GROUP BY language ORDER BY language", + )?; + let out = stmt.query_map(params![from, to], |row| { + Ok(( + row.get(0)?, + [ + row.get::<_, i64>(1)?.max(0) as u64, + row.get::<_, i64>(2)?.max(0) as u64, + row.get::<_, i64>(3)?.max(0) as u64, + ], + )) + })?; + out.collect() + } + + /// (t, language, hits, misses) of the rows from `from` to `to`, for the chart. + pub fn language_rows( + &self, + from: i64, + to: i64, + ) -> rusqlite::Result> { + let mut stmt = self.conn.prepare( + "SELECT t, language, hits, misses FROM reading_languages WHERE t >= ?1 AND t < ?2 ORDER BY t", + )?; + let out = stmt.query_map(params![from, to], |row| { + Ok(( + row.get(0)?, + row.get(1)?, + row.get::<_, i64>(2)?.max(0) as u64, + row.get::<_, i64>(3)?.max(0) as u64, + )) + })?; + out.collect() + } + + /// (reason, count) summed over the rows from `from` to `to`. + pub fn reasons(&self, from: i64, to: i64) -> rusqlite::Result> { + let mut stmt = self.conn.prepare( + "SELECT reason, SUM(count) FROM not_cached WHERE t >= ?1 AND t < ?2 GROUP BY reason ORDER BY reason", + )?; + let out = stmt.query_map(params![from, to], |row| { + Ok((row.get(0)?, row.get::<_, i64>(1)?.max(0) as u64)) + })?; + out.collect() + } + + /// `requests` summed over the rows from `from` on. + pub fn requests_since(&self, from: i64) -> rusqlite::Result { + let sum: i64 = self.conn.query_row( + "SELECT COALESCE(SUM(requests), 0) FROM readings WHERE t >= ?1", + [from], + |row| row.get(0), + )?; + Ok(sum.max(0) as u64) + } + + /// When the counters were last seen to be zeroed; `None` when they never were. + pub fn last_reset(&self) -> rusqlite::Result> { + self.conn + .query_row("SELECT MAX(t) FROM readings WHERE reset != 0", [], |row| { + row.get(0) + }) + } + + /// The oldest row there is. + pub fn first_row(&self) -> rusqlite::Result> { + self.conn + .query_row("SELECT MIN(t) FROM readings", [], |row| row.get(0)) + } + + /// How many rows there are, all told. + pub fn row_count(&self) -> rusqlite::Result { + self.conn + .query_row("SELECT COUNT(*) FROM readings", [], |row| row.get(0)) + } + + /// (seconds spent compiling, compiles) seen for each language, from the build observations. + pub fn build_time_totals(&self) -> rusqlite::Result> { + let mut stmt = self.conn.prepare( + "SELECT language, SUM(seconds), SUM(compiles) FROM build_obs GROUP BY language", + )?; + let out = stmt.query_map([], |row| { + Ok(( + row.get(0)?, + (row.get::<_, f64>(1)?, row.get::<_, i64>(2)?.max(0) as u64), + )) + })?; + out.collect() + } + + /// The build-time observations, per language and oldest first: the raw data of the histogram. + pub fn build_observations(&self) -> rusqlite::Result>> { + let mut stmt = self + .conn + .prepare("SELECT t, language, compiles, seconds FROM build_obs ORDER BY language, t")?; + let out = stmt.query_map([], |row| { + Ok(BuildObs { + t: row.get(0)?, + language: row.get(1)?, + compiles: row.get::<_, i64>(2)?.max(0) as u64, + seconds: row.get(3)?, + }) + })?; + let mut by_language: BTreeMap> = BTreeMap::new(); + for obs in out { + let obs = obs?; + by_language + .entry(obs.language.clone()) + .or_default() + .push(obs); + } + Ok(by_language) + } +} + +const OTHER_TABLES: &str = " +CREATE TABLE IF NOT EXISTS reading_languages (t INTEGER NOT NULL, language TEXT NOT NULL, hits INTEGER NOT NULL, misses INTEGER NOT NULL, errors INTEGER NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID; +CREATE TABLE IF NOT EXISTS not_cached (t INTEGER NOT NULL, reason TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (t, reason)) WITHOUT ROWID; +CREATE TABLE IF NOT EXISTS build_obs (t INTEGER NOT NULL, language TEXT NOT NULL, compiles INTEGER NOT NULL, seconds REAL NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID; +CREATE INDEX IF NOT EXISTS build_obs_language ON build_obs (language); +CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;"; 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..fa86dc4 --- /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::{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()?)); + 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..9ea79af --- /dev/null +++ b/crates/server/src/stats.rs @@ -0,0 +1,576 @@ +//! 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) + } + + /// The language of the misses when they were all of one language: (name, misses). + pub fn one_missed_language(&self) -> Option<(&str, u64)> { + let mut with_misses = self.langs.iter().filter(|(_, v)| v[1] > 0); + let (name, v) = with_misses.next()?; + with_misses.next().is_none().then(|| (name.as_str(), v[1])) + } + + /// 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 counters_survive_the_round_trip_through_saved_state() { + // The totals sccache-dash remembers between polls are saved as JSON. + let counters = parse(LIVE).unwrap().counters; + let text = serde_json::to_string(&counters).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), counters); + assert!(text.len() < 1024, "{} bytes: {text}", text.len()); + } + + #[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..db34f2a --- /dev/null +++ b/crates/server/src/view.rs @@ -0,0 +1,1342 @@ +//! Turning the saved history into the five `View`s the page draws, one per range. They are made +//! after every poll and kept; a request never waits for the database. + +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, RANGES}; +use crate::history::{History, Row}; +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; + /// While anything changes a row comes at least this often, so a bucket with no row between + /// two rows further apart than this is a gap. + pub const GAP_SECS: 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, + } +} + +/// A query that fails reads as "nothing saved": the reason goes to the log, and the poll goes on. +fn soft(result: rusqlite::Result) -> T { + match result { + Ok(value) => value, + Err(e) => { + eprintln!("sccache-dash: cannot read the history: {e}"); + T::default() + } + } +} + +/// What a compile of each language takes, from the build observations: the polls after which +/// every build that had finished was of that one language. +#[derive(Default)] +struct Learned(BTreeMap); + +impl Learned { + /// (average build time in seconds, compiles it was learned from). + fn build_time(&self, lang: &str) -> Option<(f64, u64)> { + let (seconds, n) = self.0.get(lang).filter(|(_, n)| *n > 0)?; + Some((*seconds / *n as f64, *n)) + } +} + +/// What every range needs the same way, gathered once per poll. +struct Known { + learned: Learned, + /// What the live reading adds since the last saved row, dated when it was read. + pending: Option, + server: Server, +} + +fn gather(h: &History, st: &State, now: i64) -> Known { + let live = st.live.as_ref(); + let pending = live.zip(st.tracker.row_base.as_ref()).map(|(live, base)| { + let (delta, reset) = live.snapshot.counters.since(base); + Row { + t: live.at, + reset, + delta, + } + }); + let since = now - levels::RUNNING_WINDOW.as_secs() as i64; + let changed_recently = pending + .as_ref() + .is_some_and(|p| p.delta.totals.requests > 0) + || soft(h.requests_since(since + 1)) > 0; + Known { + learned: Learned(soft(h.build_time_totals())), + pending, + 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(), + }, + } +} + +/// 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 polls after which every build that finished was 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, + interval_90: None, + }, + hit_read, + ) +} + +/// The chart: at most [`levels::BUCKETS`] buckets from `from` up to and including `to`, each +/// holding the rows dated in it. `live` says the service is running now, so `to` itself was seen. +fn buckets( + rows: &[&Row], + langs: &[(i64, String, u64, u64)], + from: i64, + to: i64, + learned: &Learned, + hit_read: f64, + live: bool, +) -> 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 the live 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(); + for row in rows { + if row.t < from || row.t > to { + continue; + } + let b = &mut out[bucket_of(row.t)]; + let t = &row.delta.totals; + b.reset |= row.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 (t, name, hits, misses) in langs { + if *t < from || *t > to { + continue; + } + let b = &mut out[bucket_of(*t)]; + match b.languages.iter_mut().find(|(k, _, _)| k == name) { + Some((_, h, m)) => { + *h += hits; + *m += misses; + } + None => b.languages.push((name.clone(), *hits, *misses)), + } + b.saved_seconds += *hits as f64 + * learned + .build_time(name) + .map_or(0.0, |(build, _)| (build - hit_read).max(0.0)); + } + + // A bucket is open when a row falls in it, or when it lies between rows less than two + // minutes apart: rows come every minute while anything changes. + let mut times: Vec = rows + .iter() + .map(|r| r.t) + .filter(|&t| t >= from && t <= to) + .collect(); + if live { + times.push(to); + } + for &t in × { + out[bucket_of(t)].gap = false; + } + for w in times.windows(2) { + if w[1] - w[0] <= levels::GAP_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. +fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> View { + let live = st.live.as_ref(); + // When the chart starts: at the last zeroing for `reset`, a range's length back otherwise. + let from = match range { + Range::SinceReset => soft(h.last_reset()) + .or_else(|| soft(h.first_row())) + .unwrap_or_else(|| live.map_or(now, |l| l.at)), + _ => now - length(range), + }; + let to = if range == Range::SinceReset { + i64::MAX + } else { + now + 1 + }; + // The saved rows are read once: they make the totals and the chart, so the two always agree. + let saved = soft(h.rows(from, to)); + let (counters, previous) = match range { + // The counters as they are. + Range::SinceReset => ( + live.map_or_else(Counters::default, |l| l.snapshot.counters.clone()), + None, + ), + _ => { + let mut counters = Counters::default(); + for row in &saved { + counters.add(&row.delta); + } + counters.langs = soft(h.languages(from, to)); + counters.not_cached = soft(h.reasons(from, to)); + if let Some(pending) = &known.pending { + counters.add(&pending.delta); + } + // The period of the same length just before: one indexed SUM. + (counters, soft(h.sums(now - 2 * length(range), from))) + } + }; + let mut chart: Vec<&Row> = saved.iter().collect(); + let mut langs = soft(h.language_rows(from, to)); + if let Some(pending) = &known.pending { + chart.push(pending); + langs.extend( + pending + .delta + .langs + .iter() + .map(|(name, v)| (pending.t, name.clone(), v[0], v[1])), + ); + } + + 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, &known.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 mut view = View { + range: Some(range), + generated_at: now, + problems: problems(&counters, &known.server), + server: known.server.clone(), + totals: counters.totals, + previous, + timing, + time_saved, + languages, + not_cached, + buckets: buckets( + &chart, + &langs, + from, + now, + &known.learned, + hit_read, + live.is_some(), + ), + extras: live.map_or_else(Vec::new, |l| stats::extras(&l.snapshot)), + raw: st.raw.clone().unwrap_or(Value::Null), + summary_markdown: String::new(), + build_times: Vec::new(), + }; + view.summary_markdown = summary(&view); + view +} + +/// The five views, one per range of [`RANGES`], made after every poll. +pub fn all(h: &History, st: &State, now: i64) -> Vec { + let known = gather(h, st, now); + RANGES + .iter() + .map(|&range| compute(h, &known, st, range, now)) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::app::Live; + use crate::history::{History, Tracker}; + use sccache_dash_api::Totals; + + /// sccache's counters at one moment, as the tests spell out a history. + #[derive(Clone)] + struct Reading { + t: i64, + c: Counters, + } + + 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() + }, + } + } + + /// A saved history with a state, as the service has them. + struct Scene { + history: History, + state: State, + } + + impl Scene { + fn view(&self, range: Range, now: i64) -> View { + all(&self.history, &self.state, now)[RANGES.iter().position(|r| *r == range).unwrap()] + .clone() + } + } + + fn state(readings: Vec, live: Option<(i64, &str)>) -> Scene { + let history = History::memory().unwrap(); + let mut tracker = Tracker::default(); + for r in readings { + history.record(&mut tracker, &r.c, r.t).unwrap(); + } + let mut state = State { + tracker: history.tracker(), + ..State::default() + }; + if let Some((at, text)) = live { + state.raw = serde_json::from_str(text).ok(); + state.live = Some(Live { + at, + snapshot: stats::parse(text).unwrap(), + raw_text: text.to_owned(), + }); + } + Scene { history, state } + } + + /// The readings, with a live reading at `at` that saw nothing change since the last of them. + fn quiet_since(readings: Vec, at: i64) -> Scene { + let counters = readings + .last() + .map_or_else(Counters::default, |r| r.c.clone()); + let snapshot = stats::Snapshot { + counters, + ..Default::default() + }; + let mut scene = state(readings, None); + scene.state.live = Some(Live { + at, + snapshot, + raw_text: String::new(), + }); + scene + } + + /// 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 mut scene = state(vec![], None); + scene.state.live = Some(Live { + at: 100, + raw_text: LIVE.to_owned(), + snapshot, + }); + scene.state.client_version = Some(client.to_owned()); + scene.view(Range::SinceReset, 100) + } + + /// No reading at all, only the reason. + fn broken(error: &str) -> Scene { + let mut scene = state(vec![], None); + scene.state.error = Some(error.to_owned()); + scene + } + + 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 = st.view(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 = st.view(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 = st.view(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 = st.view(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 = fresh.view(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 = st.view(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 = st.view(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_eq!( + v.buckets.iter().filter(|b| b.gap).count(), + 118, + "a row at the reset, the live reading at the end, nothing in between" + ); + 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(4120, 3, 1, 2), + ], + None, + ); + let v = st.view(Range::Hour, 4200); + assert_eq!(v.totals.requests, 2, "the row 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![3990, 4020, 4050, 4080, 4110], + "the buckets with a row, and those between rows two minutes apart" + ); + assert_eq!( + ( + v.buckets[113].misses, + v.buckets[117].misses, + v.buckets[114].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 rows = (0..=10) + .map(|i| reading(i * 60, i as u64, i as u64, 0)) + .collect(); + let st = state([vec![reading(-600, 0, 0, 0)], rows].concat(), None); + let v = st.view(Range::Hour, 610); + assert_eq!( + v.buckets.iter().filter(|b| b.gap).count(), + 101, + "rows every minute keep the stretch from the first row open" + ); + } + + /// Four polls, after each of which (from the second on) one Rust miss of 60 s had finished: + /// ten seconds apart, then two minutes, so that two rows are saved and three build + /// observations. Then a live reading with hits in three languages and half a second per hit read. + fn taught() -> Scene { + let taught = |misses: u64| 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 history = History::memory().unwrap(); + let mut tracker = Tracker::default(); + for (t, misses) in [(0, 0), (10, 1), (70, 2), (130, 3)] { + history.record(&mut tracker, &taught(misses), t).unwrap(); + } + 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 state = State { + tracker: history.tracker(), + ..State::default() + }; + let mut scene = Scene { history, state }; + scene.state.live = Some(Live { + at: 240, + snapshot, + raw_text: String::new(), + }); + scene + } + + #[test] + fn time_saved_counts_only_languages_whose_build_time_is_known() { + let v = taught().view(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.state.live = Some(Live { + at: 120, + snapshot, + raw_text: String::new(), + }); + let ts = st.view(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 = state(vec![reading(0, 0, 0, 5)], None) + .view(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 = taught().view(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!(taught() + .view(Range::Hour, 240) + .summary_markdown + .starts_with("**sccache, last hour**\n")); + assert!(taught() + .view(Range::Week, 240) + .summary_markdown + .starts_with("**sccache, last 7 days**\n")); + assert!(taught() + .view(Range::Month, 240) + .summary_markdown + .starts_with("**sccache, last 30 days**\n")); + + let mut plain = state(vec![], Some((100, LIVE))); + plain.state.client_version = Some("0.18.0".to_owned()); + assert_eq!( + plain.view(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 = broken("").view(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 = broken("`sccache --show-stats --stats-format json`: command not found"); + let v = off.view(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!( + quiet_since(readings.clone(), 1200) + .view(Range::Hour, 1200) + .server + .status, + Status::Running, + "a compile 200 s ago" + ); + assert_eq!( + quiet_since(readings, 1300) + .view(Range::Hour, 1300) + .server + .status, + Status::Idle, + "the last compile was 300 s ago" + ); + assert_eq!( + state(vec![reading(0, 0, 0, 5)], None) + .view(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!( + quiet.view(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!( + busy.view(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..7012abc --- /dev/null +++ b/crates/server/tests/http.rs @@ -0,0 +1,408 @@ +//! 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::history::History; +use sccache_dash::stats; +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 { + log: dir.path().join("sccache.log"), + history: dir.path().join("data").join("history.db"), + dir, + script, + } + } + + /// What `--show-stats` prints from now on. + fn answers(&self, text: &str) { + std::fs::write(self.dir.path().join("sccache.out"), text).unwrap(); + } + + /// 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() + } + + fn config(&self) -> Config { + Config { + sccache: self.script.clone().into(), + history: self.history.clone(), + } + } +} + +/// A server on a free port next to an empty history, polled once, answering in the background. +/// The test stands in for the polling task: it holds the history and polls by hand. +fn start(fake: &Fake) -> (Arc, History, SocketAddr) { + let app = Arc::new(App::new(fake.config())); + let history = History::memory().unwrap(); + app.poll_at(&history, 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, history, 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, history, 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!( + history.row_count().unwrap(), + 0, + "and nothing was written to the history" + ); + assert_eq!( + app.lock().tracker.row_base.as_ref().unwrap().totals, + stats::parse(LIVE).unwrap().counters.totals + ); +} + +#[test] +fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() { + let fake = Fake::new(); + let (app, history, addr) = start(&fake); + + 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" + ); + + // What the polling task then does, woken by the request: it reads the counters again. + app.poll_at(&history, unix_now()); + 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"); + + assert_eq!( + history.row_count().unwrap(), + 1, + "the history stays, and the zeroing is one more row" + ); + let row = &history.rows(0, i64::MAX).unwrap()[0]; + assert!(row.reset, "the zeroing shows in the history as a reset"); + assert_eq!( + row.delta, + stats::Counters::default(), + "nothing has been compiled since" + ); + assert_eq!(history.last_reset().unwrap(), Some(row.t)); + + let v = app.view(Range::SinceReset); + assert_eq!( + v.totals, + Totals::default(), + "sccache's counters read zero now" + ); + assert!( + v.buckets[0].reset, + "and its chart starts at the reset: {:?}", + v.buckets + ); +} + +#[test] +fn view_export_and_the_page_answer() { + let fake = Fake::new(); + let (_app, _history, 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")); + for range in ["1h", "24h", "7d", "30d"] { + let response = send(addr, &format!("GET /api/view?range={range}{GET}")); + let v: View = serde_json::from_str(response.split("\r\n\r\n").nth(1).unwrap()).unwrap(); + assert_eq!(v.buckets.len(), 120, "{range}"); + } + + 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 rows_are_saved_when_counters_change_and_at_most_once_a_minute() { + let fake = Fake::new(); + let app = App::new(fake.config()); + let history = History::memory().unwrap(); + let rows = || history.row_count().unwrap(); + + app.poll_at(&history, NOW); + assert_eq!(rows(), 0, "the first reading is a baseline, not a row"); + app.poll_at(&history, NOW + 10); + assert_eq!(rows(), 0, "nothing changed"); + + fake.answers(&LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352")); + app.poll_at(&history, NOW + 30); + assert_eq!( + rows(), + 0, + "changed, but less than a minute after the baseline" + ); + app.poll_at(&history, NOW + 60); + assert_eq!(rows(), 1, "a minute on, the change is saved"); + let row = &history.rows(0, i64::MAX).unwrap()[0]; + assert_eq!( + (row.t, row.delta.totals.requests, row.reset), + (NOW + 60, 1, false) + ); + + app.poll_at(&history, NOW + 700); + assert_eq!( + rows(), + 1, + "unchanged: nothing more is saved, however long the quiet lasts" + ); + assert!( + history.build_observations().unwrap().is_empty(), + "and with no misses there is no build observation" + ); + assert_eq!(app.lock().views.len(), 5, "every poll makes the five views"); +} + +#[test] +fn the_history_survives_a_restart_in_its_file() { + let fake = Fake::new(); + let app = App::new(fake.config()); + let path = fake.history.clone(); + + // The first run sees the baseline and a change, then stops. + let history = History::open(&path).unwrap(); + history.prune(NOW).unwrap(); + let mut tracker = history.tracker(); + assert_eq!(tracker, Default::default(), "a new file remembers nothing"); + let (a, b) = ( + stats::parse(LIVE).unwrap().counters, + stats::parse(LIVE).unwrap().counters, + ); + history.record(&mut tracker, &a, NOW).unwrap(); + history.record(&mut tracker, &b, NOW + 10).unwrap(); + drop(history); + + // The next run picks up where it stopped: the difference is not lost or counted twice. + let history = History::open(&path).unwrap(); + let mut tracker = history.tracker(); + assert_eq!( + tracker.row_base, + Some(a.clone()), + "the totals at the baseline" + ); + let mut c = b.clone(); + c.totals.requests += 5; + history.record(&mut tracker, &c, NOW + 70).unwrap(); + let rows = history.rows(0, i64::MAX).unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!((rows[0].t, rows[0].delta.totals.requests), (NOW + 70, 5)); + assert_eq!( + app.view(Range::Day).range, + Some(Range::Day), + "and a server that has not polled yet answers with an empty view" + ); +} + +#[test] +fn old_rows_are_deleted_at_startup() { + let fake = Fake::new(); + // A real file, as the service has, in WAL mode. + let history = History::open(&fake.history).unwrap(); + let mut tracker = Default::default(); + let day = 86_400; + let mut c = stats::Counters::default(); + for (t, requests) in [ + (NOW - 33 * day, 1), + (NOW - 31 * day, 2), + (NOW - 30 * day + 3600, 3), + (NOW - 3600, 4), + (NOW, 5), + ] { + c.totals.requests = requests; + history.record(&mut tracker, &c, t).unwrap(); + } + assert_eq!( + history.row_count().unwrap(), + 4, + "rows carry differences; the first reading is the baseline" + ); + assert_eq!( + history.prune(NOW).unwrap(), + 1, + "the one row older than 30 days" + ); + let left: Vec = history + .rows(0, i64::MAX) + .unwrap() + .iter() + .map(|r| r.t) + .collect(); + assert_eq!(left, vec![NOW - 30 * day + 3600, NOW - 3600, NOW]); + assert_eq!(history.prune(NOW).unwrap(), 0, "nothing more to delete"); + assert!( + fake.history.with_extension("db-wal").exists() + || fake.history.with_extension("db-shm").exists(), + "WAL mode is on" + ); +} 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