Server half of sccache-dash

Polls sccache's counters every 10 s, keeps a JSON-lines history, and serves
the page and its API on 127.0.0.1: one difference-with-reset mechanism behind
every range, per-language time saved, problems, a copyable summary, and
extra tables for multi-level and distributed caches.

The page is embedded from crates/ui/dist when it exists, with a placeholder
until then. POST /api/zero refuses foreign Host and Origin headers.
Tests run against a stand-in sccache script; sample fixtures for the
multi-level and distributed shapes are made up.
This commit is contained in:
swaits committed 2026-11-28 11:23:39 -07:00
1 parent a8e7bd66cf
commit 3cbc02e631
18 files changed
+3654

No files matched your search

+579
View File
@@ -0,0 +1,579 @@
//! sccache's counters: reading them out of its JSON and telling two readings apart.
use std::collections::BTreeMap;
use sccache_dash_api::{Extra, Totals};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::pretty;
/// Positions in [`Counters::ns`].
pub const HIT_READ: usize = 0;
pub const CACHE_WRITE: usize = 1;
pub const COMPILE: usize = 2;
/// sccache's counters at one moment. Each only grows, until sccache resets them.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Counters {
#[serde(default)]
pub totals: Totals,
/// Compiler runs: misses, plus compiles that could not be cached or failed.
#[serde(default)]
pub compilations: u64,
/// Nanoseconds spent reading hits, writing cache entries and running compilers.
#[serde(default)]
pub ns: [u64; 3],
/// (language, [hits, misses, errors]) by name, for languages that have counted something.
#[serde(default)]
pub langs: Vec<(String, [u64; 3])>,
/// (reason, count) by name, for reasons that have counted something.
#[serde(default)]
pub not_cached: Vec<(String, u64)>,
}
impl Counters {
/// What happened between `older` and `self`, and whether sccache reset its counters in between.
///
/// A counter that went down can only mean sccache zeroed its counters (a new server, or
/// `--zero-stats`), and it zeroes all of them at once: every difference is then the new value.
pub fn since(&self, older: &Counters) -> (Counters, bool) {
let mut reset = false;
let mut sub = |a: u64, b: u64| {
if b < a {
reset = true;
}
b.saturating_sub(a)
};
let (a, b) = (&older.totals, &self.totals);
let totals = Totals {
requests: sub(a.requests, b.requests),
executed: sub(a.executed, b.executed),
hits: sub(a.hits, b.hits),
misses: sub(a.misses, b.misses),
not_cacheable: sub(a.not_cacheable, b.not_cacheable),
unsupported_compiler: sub(a.unsupported_compiler, b.unsupported_compiler),
not_compile: sub(a.not_compile, b.not_compile),
timeouts: sub(a.timeouts, b.timeouts),
read_errors: sub(a.read_errors, b.read_errors),
write_errors: sub(a.write_errors, b.write_errors),
other_errors: sub(a.other_errors, b.other_errors),
compile_fails: sub(a.compile_fails, b.compile_fails),
forced_recaches: sub(a.forced_recaches, b.forced_recaches),
cache_writes: sub(a.cache_writes, b.cache_writes),
};
let compilations = sub(older.compilations, self.compilations);
let mut ns = [0; 3];
for (d, (a, b)) in ns.iter_mut().zip(older.ns.iter().zip(self.ns.iter())) {
*d = sub(*a, *b);
}
let langs = self
.langs
.iter()
.filter_map(|(name, v)| {
let o = older
.langs
.iter()
.find(|(k, _)| k == name)
.map_or([0; 3], |(_, o)| *o);
let mut d = [0; 3];
for (d, (a, b)) in d.iter_mut().zip(o.iter().zip(v.iter())) {
*d = sub(*a, *b);
}
(d != [0; 3]).then(|| (name.clone(), d))
})
.collect();
let not_cached = self
.not_cached
.iter()
.filter_map(|(name, v)| {
let o = older
.not_cached
.iter()
.find(|(k, _)| k == name)
.map_or(0, |(_, o)| *o);
let d = sub(o, *v);
(d > 0).then(|| (name.clone(), d))
})
.collect();
let diff = Counters {
totals,
compilations,
ns,
langs,
not_cached,
};
(if reset { self.clone() } else { diff }, reset)
}
/// Adds another set of counters into this one.
pub fn add(&mut self, other: &Counters) {
macro_rules! sum {
($($f:ident),* $(,)?) => { $( self.totals.$f += other.totals.$f; )* };
}
sum!(
requests,
executed,
hits,
misses,
not_cacheable,
unsupported_compiler,
not_compile,
timeouts,
read_errors,
write_errors,
other_errors,
compile_fails,
forced_recaches,
cache_writes,
);
self.compilations += other.compilations;
for (n, x) in self.ns.iter_mut().zip(other.ns.iter()) {
*n += x;
}
for (name, v) in &other.langs {
match self.langs.iter_mut().find(|(k, _)| k == name) {
Some((_, have)) => {
for (h, x) in have.iter_mut().zip(v.iter()) {
*h += x;
}
}
None => self.langs.push((name.clone(), *v)),
}
}
for (name, v) in &other.not_cached {
match self.not_cached.iter_mut().find(|(k, _)| k == name) {
Some((_, have)) => *have += v,
None => self.not_cached.push((name.clone(), *v)),
}
}
}
}
/// One level of a multi-level cache, as sccache 0.18 reports it in `stats.multi_level`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Level {
pub name: String,
pub location: String,
pub hits: u64,
pub misses: u64,
pub writes: u64,
pub write_failures: u64,
pub backfills_from: u64,
pub backfills_to: u64,
pub hit_ns: u64,
pub write_ns: u64,
}
/// What one run of `sccache --show-stats --stats-format json` said.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Snapshot {
pub counters: Counters,
pub version: Option<String>,
pub cache_location: Option<String>,
pub cache_size: Option<u64>,
pub max_cache_size: Option<u64>,
pub multi_level: Vec<Level>,
/// (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<Snapshot, String> {
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<String, u64> {
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<String, u64> {
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<Extra> {
let mut out = Vec::new();
if !s.multi_level.is_empty() {
let rows = s
.multi_level
.iter()
.map(|l| {
let per = |total: u64, n: u64| (n > 0).then(|| total as f64 / n as f64 / 1e9);
(
format!("{} \u{2014} {}", l.name, l.location),
format!(
"{} hits \u{b7} {} misses \u{b7} {} writes, {} failed \u{b7} backfilled {} in, {} out \u{b7} avg hit read {} \u{b7} avg write {}",
pretty::thousands(l.hits),
pretty::thousands(l.misses),
pretty::thousands(l.writes),
pretty::thousands(l.write_failures),
pretty::thousands(l.backfills_from),
pretty::thousands(l.backfills_to),
per(l.hit_ns, l.hits).map_or_else(|| "\u{2014}".to_owned(), pretty::short),
per(l.write_ns, l.writes).map_or_else(|| "\u{2014}".to_owned(), pretty::short),
),
)
})
.collect();
out.push(Extra {
title: "Multi-level cache".to_owned(),
rows,
});
}
if !s.dist_compiles.is_empty() || s.dist_errors > 0 {
let mut rows: Vec<_> = s
.dist_compiles
.iter()
.map(|(server, n)| (server.clone(), pretty::thousands(*n)))
.collect();
rows.push((
"Errors (re-run locally)".to_owned(),
pretty::thousands(s.dist_errors),
));
out.push(Extra {
title: "Distributed compiles".to_owned(),
rows,
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
const MULTILEVEL: &str = include_str!("../../../fixtures/sample-multilevel.json");
const DIST: &str = include_str!("../../../fixtures/sample-dist.json");
fn counters(requests: u64, hits: u64, misses: u64) -> Counters {
Counters {
totals: Totals {
requests,
hits,
misses,
..Totals::default()
},
compilations: misses,
langs: vec![("Rust".to_owned(), [hits, misses, 0])],
..Counters::default()
}
}
#[test]
fn live_output_is_read_as_it_is() {
let s = parse(LIVE).unwrap();
assert_eq!(
s.counters.totals,
Totals {
requests: 7351,
executed: 6495,
hits: 3197,
misses: 3256,
not_cacheable: 829,
not_compile: 27,
other_errors: 0,
compile_fails: 39,
cache_writes: 3256,
..Totals::default()
}
);
assert_eq!(s.counters.compilations, 3256);
assert_eq!(
s.counters.ns,
[2_190_691_578, 8_758_680_079, 25_343_119_040_435]
);
assert_eq!(
s.counters.langs,
vec![
("Assembler".to_owned(), [886, 0, 0]),
("C/C++".to_owned(), [2082, 0, 0]),
("Rust".to_owned(), [229, 3256, 0]),
]
);
assert_eq!(s.counters.not_cached.len(), 7);
assert_eq!(s.counters.not_cached[0], ("-".to_owned(), 35));
assert_eq!(s.version.as_deref(), Some("0.18.0"));
assert_eq!(
s.cache_location.as_deref(),
Some("Local disk: \"/home/swaits/.cache/sccache\"")
);
assert_eq!(
(s.cache_size, s.max_cache_size),
(Some(10_726_353_131), Some(10_737_418_240))
);
assert!(s.multi_level.is_empty() && s.dist_compiles.is_empty() && s.dist_errors == 0);
assert!(
extras(&s).is_empty(),
"nothing extra is reported, so there are no extra tables"
);
}
#[test]
fn a_saved_line_is_small() {
let reading = crate::history::Reading {
t: 1_764_000_000,
c: parse(LIVE).unwrap().counters,
};
let line = serde_json::to_string(&reading).unwrap();
assert!(line.len() < 1024, "{} bytes: {line}", line.len());
assert!(
line.starts_with("{\"t\":1764000000,\"c\":{\"totals\":{\"requests\":7351"),
"{line}"
);
assert!(line.ends_with("[\"multiple input files\",3]]}}"), "{line}");
assert_eq!(
serde_json::from_str::<crate::history::Reading>(&line).unwrap(),
reading
);
}
#[test]
fn unknown_and_missing_fields_do_not_break_it() {
let s = parse(
"{\"stats\":{\"compile_requests\":\"many\",\"cache_hits\":{\"counts\":{\"Rust\":-1}},\"new_field\":1},\"extra\":2}",
)
.unwrap();
assert_eq!(s.counters, Counters::default());
assert_eq!(parse("{\"stats\":{}}").unwrap(), Snapshot::default());
assert_eq!(
parse("{\"stats\":null,\"version\":\"1.0\"}")
.unwrap()
.version
.as_deref(),
Some("1.0")
);
assert!(parse("not json").is_err());
assert!(parse("{\"error\":\"no server\"}").is_err());
}
#[test]
fn differences_are_what_grew() {
let (older, newer) = (counters(100, 60, 40), counters(130, 80, 50));
let (diff, reset) = newer.since(&older);
assert_eq!(diff.totals.requests, 30);
assert_eq!(diff.totals.hits, 20);
assert_eq!(diff.totals.misses, 10);
assert_eq!(diff.langs, vec![("Rust".to_owned(), [20, 10, 0])]);
assert!(!reset);
let (same, _) = newer.since(&newer);
assert!(same.totals == Totals::default() && same.langs.is_empty());
}
#[test]
fn a_counter_going_down_zeroes_the_whole_reading() {
let mut older = counters(100, 60, 40);
older.not_cached.push(("crate-type".to_owned(), 9));
older.ns[COMPILE] = 400;
let mut newer = counters(130, 5, 0);
newer.not_cached.push(("crate-type".to_owned(), 2));
newer.not_cached.push(("-o".to_owned(), 1));
newer.ns[COMPILE] = 7;
let (diff, reset) = newer.since(&older);
assert!(
reset,
"hits went down, so the counters were zeroed in between"
);
assert_eq!(
diff, newer,
"every difference is the new value, even where the counter grew"
);
}
#[test]
fn sums_merge_languages_and_reasons() {
let mut a = counters(10, 4, 6);
a.not_cached.push(("crate-type".to_owned(), 1));
let mut b = counters(1, 1, 0);
b.compilations = 0;
b.langs = vec![
("C/C++".to_owned(), [1, 0, 0]),
("Rust".to_owned(), [0, 0, 2]),
];
b.not_cached.push(("crate-type".to_owned(), 2));
b.not_cached.push(("incremental".to_owned(), 1));
a.add(&b);
assert_eq!(a.totals.requests, 11);
assert_eq!(a.totals.hits, 5);
assert_eq!(a.compilations, 6);
assert_eq!(
a.langs,
vec![
("Rust".to_owned(), [4, 6, 2]),
("C/C++".to_owned(), [1, 0, 0])
]
);
assert_eq!(
a.not_cached,
vec![("crate-type".to_owned(), 3), ("incremental".to_owned(), 1)]
);
}
#[test]
fn multilevel_sample_becomes_a_table() {
let s = parse(MULTILEVEL).unwrap();
assert_eq!(s.multi_level.len(), 2);
assert_eq!(s.multi_level[1].name, "L1 (s3)");
assert_eq!(s.multi_level[0].hit_ns, 1_500_000_000);
assert_eq!(s.multi_level[1].write_ns, 36_500_000_000);
let extras = extras(&s);
assert_eq!(extras.len(), 1);
assert_eq!(extras[0].title, "Multi-level cache");
assert_eq!(extras[0].rows.len(), 2);
assert_eq!(
extras[0].rows[0].0,
"L0 (disk) \u{2014} Local disk: \"/home/me/.cache/sccache\""
);
assert_eq!(
extras[0].rows[0].1,
"1,500 hits \u{b7} 1,000 misses \u{b7} 1,400 writes, 2 failed \u{b7} backfilled 300 in, 0 out \u{b7} avg hit read 1 ms \u{b7} avg write 2 ms"
);
}
#[test]
fn dist_sample_becomes_a_table() {
let s = parse(DIST).unwrap();
assert_eq!(
s.dist_compiles,
vec![
("10.0.0.11:4226".to_owned(), 402),
("10.0.0.12:4226".to_owned(), 379),
("buildbox.local:4228".to_owned(), 9),
]
);
assert_eq!(s.dist_errors, 7);
let extras = extras(&s);
assert_eq!(extras.len(), 1);
assert_eq!(extras[0].title, "Distributed compiles");
assert_eq!(
extras[0].rows[2],
("buildbox.local:4228".to_owned(), "9".to_owned())
);
assert_eq!(
extras[0].rows[3],
("Errors (re-run locally)".to_owned(), "7".to_owned())
);
}
#[test]
fn only_dist_errors_still_makes_a_table() {
let mut s = parse(DIST).unwrap();
s.dist_compiles.clear();
assert_eq!(
extras(&s)[0].rows,
vec![("Errors (re-run locally)".to_owned(), "7".to_owned())]
);
}
}