Keep the history in SQLite, one view per range made after each poll

Each row of the readings table is the difference since the row before it,
at most one a minute and only when something changed, so a range total is
one indexed query. Per-language counts, not-cacheable reasons and build
observations have their own tables; what the last poll and the last row
saw is remembered in the state table, so differences survive a restart.

The five views are computed once per poll and kept; /api/view answers
from them and never touches the database, which only the polling task
holds. /api/zero wakes that task instead of reading the counters itself.

Build observations: after a poll in which every build that finished was
of one language, one row with the difference in compilations and compile
time, for the build-time histogram. Time saved uses their per-language
average. Views fill the api's build_times and interval_90 as empty/None.
This commit is contained in:
swaits committed 2026-11-28 11:44:50 -07:00
1 parent a83ae5e0d9
commit 7f58931b7b
8 files changed
+970 -642

No files matched your search

+310 -257
View File
@@ -1,4 +1,5 @@
//! Turning the saved readings into the one `View` the page draws.
//! 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;
@@ -7,7 +8,8 @@ use sccache_dash_api::{
};
use serde_json::Value;
use crate::app::{State, HEARTBEAT_SECS};
use crate::app::{State, RANGES};
use crate::history::{History, Row};
use crate::pretty;
use crate::stats::{self, Counters, CACHE_WRITE, COMPILE, HIT_READ};
@@ -27,6 +29,9 @@ pub mod levels {
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.
@@ -39,74 +44,69 @@ fn length(range: Range) -> i64 {
}
}
/// What happened between two consecutive readings, dated when the later one was taken.
struct Span<'a> {
end: i64,
reset: bool,
delta: &'a Counters,
}
/// Visits every interval that is known: the saved ones, then the one up to the live reading.
fn each_span(st: &State, mut f: impl FnMut(Span<'_>)) {
for i in &st.intervals {
f(Span {
end: i.end,
reset: i.reset,
delta: &i.delta,
});
}
if let (Some(live), Some(last)) = (&st.live, st.readings.last()) {
let (delta, reset) = live.snapshot.counters.since(&last.c);
f(Span {
end: live.at,
reset,
delta: &delta,
});
}
}
/// The sum of the intervals recorded from `from` (inclusive) to `to` (exclusive); `None` when
/// nothing was recorded in that time.
fn sum_between(st: &State, from: i64, to: i64) -> Option<Counters> {
let mut sum: Option<Counters> = None;
each_span(st, |s| {
if s.end >= from && s.end < to {
sum.get_or_insert_with(Counters::default).add(s.delta);
/// A query that fails reads as "nothing saved": the reason goes to the log, and the poll goes on.
fn soft<T: Default>(result: rusqlite::Result<T>) -> T {
match result {
Ok(value) => value,
Err(e) => {
eprintln!("sccache-dash: cannot read the history: {e}");
T::default()
}
});
sum
}
}
/// What a compile of each language takes, learned from every saved interval in which all the
/// misses were of that one language.
/// 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<String, (u64, u64)>);
struct Learned(BTreeMap<String, (f64, u64)>);
impl Learned {
fn from_history(st: &State) -> Learned {
let mut learned = Learned::default();
each_span(st, |s| {
if s.delta.totals.misses == 0 {
return;
}
let mut with_misses = s.delta.langs.iter().filter(|(_, v)| v[1] > 0);
let Some((name, _)) = with_misses.next() else {
return;
};
if with_misses.next().is_some() {
return;
}
let seen = learned.0.entry(name.clone()).or_default();
seen.0 += s.delta.ns[COMPILE];
seen.1 += s.delta.compilations;
});
learned
}
/// (average build time in seconds, compiles it was learned from).
fn build_time(&self, lang: &str) -> Option<(f64, u64)> {
let (ns, n) = self.0.get(lang).filter(|(_, n)| *n > 0)?;
Some((*ns as f64 / *n as f64 / 1e9, *n))
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<Row>,
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(),
},
}
}
@@ -144,7 +144,7 @@ fn time_saved(c: &Counters, learned: &Learned) -> (TimeSaved, f64) {
"There were no hits in this range, so nothing was saved.".to_owned()
} else if used.is_empty() {
format!(
"Nothing is counted: no build time has been learned yet, which takes saved minutes in which every miss was a compile of one language. {} hits left out.",
"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 {
@@ -172,18 +172,27 @@ fn time_saved(c: &Counters, learned: &Learned) -> (TimeSaved, f64) {
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 what was recorded up to the moment it was noticed.
fn buckets(st: &State, from: i64, to: i64, learned: &Learned, hit_read: f64) -> Vec<Bucket> {
/// 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<Bucket> {
let span = (to - from).max(1);
let len = (span + levels::BUCKETS - 1) / levels::BUCKETS;
let count = ((span + len - 1) / len) as usize;
// The last bucket takes the moment `to` itself, which is always a reading.
// 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<Bucket> = (0..count as i64)
.map(|i| Bucket {
@@ -192,51 +201,51 @@ fn buckets(st: &State, from: i64, to: i64, learned: &Learned, hit_read: f64) ->
..Bucket::default()
})
.collect();
each_span(st, |s| {
if s.end < from || s.end > to {
return;
for row in rows {
if row.t < from || row.t > to {
continue;
}
let b = &mut out[bucket_of(s.end)];
let t = &s.delta.totals;
b.reset |= s.reset;
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 (name, v) in &s.delta.langs {
match b.languages.iter_mut().find(|(k, _, _)| k == name) {
Some((_, hits, misses)) => {
*hits += v[0];
*misses += v[1];
}
None => b.languages.push((name.clone(), v[0], v[1])),
}
b.saved_seconds += v[0] as f64
* learned
.build_time(name)
.map_or(0.0, |(build, _)| (build - hit_read).max(0.0));
}
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 reading falls in it, or when it lies between two readings less
// than ten minutes apart: the service was running then, just nothing changed.
let mut times: Vec<i64> = st
.readings
// 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<i64> = rows
.iter()
.map(|r| r.t)
.filter(|&t| t >= from && t <= to)
.collect();
times.extend(
st.live
.iter()
.map(|l| l.at)
.filter(|&t| t >= from && t <= to),
);
if live {
times.push(to);
}
for &t in &times {
out[bucket_of(t)].gap = false;
}
for w in times.windows(2) {
if w[1] - w[0] <= HEARTBEAT_SECS {
if w[1] - w[0] <= levels::GAP_SECS {
for b in &mut out[bucket_of(w[0])..bucket_of(w[1])] {
b.gap = false;
}
@@ -416,38 +425,56 @@ pub fn summary(view: &View) -> String {
s
}
/// Makes the view for one range from what is known now.
pub fn build(st: &State, range: Range, now: i64) -> View {
/// 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();
let learned = Learned::from_history(st);
// What the range counts, and when its chart starts.
let (counters, previous, from) = match range {
Range::SinceReset => {
// The counters as they are, charted since they were last zeroed.
let mut from = live
.map_or(now, |l| l.at)
.min(st.readings.first().map_or(now, |r| r.t));
each_span(st, |s| {
if s.reset {
from = s.end;
}
});
(
live.map_or_else(Counters::default, |l| l.snapshot.counters.clone()),
None,
from,
)
}
// 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 length = length(range);
(
sum_between(st, now - length, now + 1).unwrap_or_default(),
sum_between(st, now - 2 * length, now - length),
now - length,
)
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 {
@@ -455,7 +482,7 @@ pub fn build(st: &State, range: Range, now: i64) -> View {
avg_cache_write_ms: per(counters.ns[CACHE_WRITE], t.cache_writes),
avg_compile_ms: per(counters.ns[COMPILE], counters.compilations),
};
let (time_saved, hit_read) = time_saved(&counters, &learned);
let (time_saved, hit_read) = time_saved(&counters, &known.learned);
let mut languages: Vec<Language> = counters
.langs
.iter()
@@ -474,51 +501,58 @@ pub fn build(st: &State, range: Range, now: i64) -> View {
let mut not_cached = counters.not_cached.clone();
not_cached.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
let window = levels::RUNNING_WINDOW.as_secs() as i64;
let mut changed_recently = false;
each_span(st, |s| {
changed_recently |= s.end > now - window && s.end <= now && s.delta.totals.requests > 0;
});
let server = Server {
status: match live {
None => Status::NotRunning,
Some(_) if changed_recently => Status::Running,
Some(_) => Status::Idle,
},
version: live.and_then(|l| l.snapshot.version.clone()),
client_version: st.client_version.clone(),
cache_location: live.and_then(|l| l.snapshot.cache_location.clone()),
cache_size: live.and_then(|l| l.snapshot.cache_size),
max_cache_size: live.and_then(|l| l.snapshot.max_cache_size),
error: st.error.clone(),
};
let mut view = View {
range: Some(range),
generated_at: now,
problems: problems(&counters, &server),
server,
problems: problems(&counters, &known.server),
server: known.server.clone(),
totals: counters.totals,
previous: previous.map(|p| p.totals),
previous,
timing,
time_saved,
languages,
not_cached,
buckets: buckets(st, from, now, &learned, hit_read),
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<View> {
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::Reading;
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
@@ -546,38 +580,56 @@ mod tests {
}
}
fn state(readings: Vec<Reading>, live: Option<(i64, &str)>) -> State {
let mut st = State::default();
for r in readings {
st.push(r);
/// 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<Reading>, 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 {
let snapshot = stats::parse(text).unwrap();
st.raw = serde_json::from_str(text).ok();
st.live = Some(Live {
state.raw = serde_json::from_str(text).ok();
state.live = Some(Live {
at,
snapshot,
snapshot: stats::parse(text).unwrap(),
raw_text: text.to_owned(),
});
}
st
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<Reading>, at: i64) -> State {
fn quiet_since(readings: Vec<Reading>, at: i64) -> Scene {
let counters = readings
.last()
.map_or_else(Counters::default, |r| r.c.clone());
let snapshot = stats::Snapshot {
counters: readings
.last()
.map_or_else(Counters::default, |r| r.c.clone()),
..stats::Snapshot::default()
counters,
..Default::default()
};
let mut st = state(readings, None);
st.live = Some(Live {
let mut scene = state(readings, None);
scene.state.live = Some(Live {
at,
snapshot,
raw_text: String::new(),
});
st
scene
}
/// A view of the live output with `edit` applied and sccache's command at `client`. It starts
@@ -588,16 +640,21 @@ mod tests {
snapshot.cache_size = Some(1024 * 1024 * 1024);
snapshot.counters.langs = vec![("C/C++".to_owned(), [2082, 0, 0])];
edit(&mut snapshot);
let st = State {
live: Some(Live {
at: 100,
raw_text: LIVE.to_owned(),
snapshot,
}),
client_version: Some(client.to_owned()),
..State::default()
};
build(&st, Range::SinceReset, 100)
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> {
@@ -615,7 +672,7 @@ mod tests {
],
200,
);
let v = build(&st, Range::Hour, 200);
let v = st.view(Range::Hour, 200);
assert_eq!(
v.totals,
Totals {
@@ -673,7 +730,7 @@ mod tests {
],
None,
);
let v = build(&st, Range::Hour, 8000);
let v = st.view(Range::Hour, 8000);
assert_eq!(
v.totals.requests, 6,
"the three intervals ending in the last hour"
@@ -683,7 +740,7 @@ mod tests {
Some(15),
"the three in the hour before"
);
let v = build(&st, Range::Day, 8000);
let v = st.view(Range::Day, 8000);
assert_eq!(v.totals.requests, 21);
assert_eq!(v.previous, None, "nothing was saved before that day");
}
@@ -694,7 +751,7 @@ mod tests {
vec![reading(0, 100, 60, 40), reading(60, 130, 80, 50)],
None,
);
let v = build(&st, Range::Week, 100);
let v = st.view(Range::Week, 100);
assert_eq!(
v.totals.requests, 30,
"only what came after the first reading"
@@ -702,7 +759,7 @@ mod tests {
assert_eq!((v.totals.hits, v.totals.misses), (20, 10));
let fresh = state(vec![], Some((100, LIVE)));
let v = build(&fresh, Range::Week, 100);
let v = fresh.view(Range::Week, 100);
assert_eq!(
v.totals,
Totals::default(),
@@ -724,7 +781,7 @@ mod tests {
],
None,
);
let v = build(&st, Range::Hour, 1900);
let v = st.view(Range::Hour, 1900);
assert_eq!(
v.totals.requests, 55,
"30 before the reset, then 10 + 15 from zero"
@@ -768,7 +825,7 @@ mod tests {
],
Some((1800, LIVE)),
);
let v = build(&st, Range::SinceReset, 1800);
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);
@@ -788,9 +845,10 @@ mod tests {
live.totals.hits,
"3 at the reset, then the rest at the live reading"
);
assert!(
v.buckets.iter().all(|b| !b.gap),
"a reading at each end, ten minutes apart at most"
assert_eq!(
v.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],
@@ -817,15 +875,12 @@ mod tests {
reading(0, 0, 0, 0),
reading(60, 1, 1, 0),
reading(4000, 2, 1, 1),
reading(4020, 3, 1, 2),
reading(4120, 3, 1, 2),
],
None,
);
let v = build(&st, Range::Hour, 4100);
assert_eq!(
v.totals.requests, 2,
"the interval ending at 60 is before the range"
);
let v = st.view(Range::Hour, 4200);
assert_eq!(v.totals.requests, 2, "the row at 60 is before the range");
let open: Vec<i64> = v
.buckets
.iter()
@@ -834,54 +889,53 @@ mod tests {
.collect();
assert_eq!(
open,
vec![3980, 4010],
"only the two buckets with a reading in them"
vec![3990, 4020, 4050, 4080, 4110],
"the buckets with a row, and those between rows two minutes apart"
);
assert_eq!(
(
v.buckets[116].misses,
v.buckets[113].misses,
v.buckets[117].misses,
v.buckets[118].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 st = state(
vec![
reading(0, 0, 0, 0),
reading(300, 1, 1, 0),
reading(600, 2, 2, 0),
],
None,
);
let v = build(&st, Range::Hour, 610);
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(),
99,
"one open stretch from the reading at 0 to the one at 600"
101,
"rows every minute keep the stretch from the first row open"
);
}
/// Three saved minutes that each saw one Rust miss of 60 s, then a live reading with hits
/// in three languages and half a second per hit read.
fn taught() -> State {
let taught = |t: i64, misses: u64| Reading {
t,
c: Counters {
totals: Totals {
requests: misses,
misses,
cache_writes: misses,
..Totals::default()
},
compilations: misses,
ns: [0, 0, misses * 60_000_000_000],
langs: vec![("Rust".to_owned(), [0, misses, 0])],
..Counters::default()
/// 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]),
@@ -901,21 +955,22 @@ mod tests {
counters: c,
..stats::parse(LIVE).unwrap()
};
let mut st = state(
vec![taught(0, 0), taught(60, 1), taught(120, 2), taught(180, 3)],
None,
);
st.live = Some(Live {
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(),
});
st
scene
}
#[test]
fn time_saved_counts_only_languages_whose_build_time_is_known() {
let v = build(&taught(), Range::Week, 240);
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);
@@ -964,12 +1019,12 @@ mod tests {
],
None,
);
st.live = Some(Live {
st.state.live = Some(Live {
at: 120,
snapshot,
raw_text: String::new(),
});
let ts = build(&st, Range::Day, 120).time_saved;
let ts = st.view(Range::Day, 120).time_saved;
assert_eq!(
(ts.seconds, ts.hits_left_out),
(0.0, 10 + 3177),
@@ -983,7 +1038,9 @@ mod tests {
);
assert!(ts.note.ends_with("3,187 hits left out."), "{}", ts.note);
let only_misses = build(&state(vec![reading(0, 0, 0, 5)], None), Range::Day, 60).time_saved;
let only_misses = state(vec![reading(0, 0, 0, 5)], None)
.view(Range::Day, 60)
.time_saved;
assert_eq!(
(
only_misses.seconds,
@@ -1000,7 +1057,7 @@ mod tests {
#[test]
fn both_hit_rates_and_the_summary_text() {
let v = build(&taught(), Range::Day, 240);
let v = taught().view(Range::Day, 240);
assert_eq!(
v.totals.hit_rate(),
Some(3044.0 / 3047.0),
@@ -1033,27 +1090,23 @@ mod tests {
- Time saved: ~3h 47m (rough)\n\
- Cache: local disk, 10.0 of 10.0 GB \u{b7} sccache 0.18.0\n"
);
assert!(build(&taught(), Range::Hour, 240)
assert!(taught()
.view(Range::Hour, 240)
.summary_markdown
.starts_with("**sccache, last hour**\n"));
assert!(build(&taught(), Range::Week, 240)
assert!(taught()
.view(Range::Week, 240)
.summary_markdown
.starts_with("**sccache, last 7 days**\n"));
assert!(build(&taught(), Range::Month, 240)
assert!(taught()
.view(Range::Month, 240)
.summary_markdown
.starts_with("**sccache, last 30 days**\n"));
let st = State {
live: Some(Live {
at: 100,
raw_text: LIVE.to_owned(),
snapshot: stats::parse(LIVE).unwrap(),
}),
client_version: Some("0.18.0".to_owned()),
..State::default()
};
let mut plain = state(vec![], Some((100, LIVE)));
plain.state.client_version = Some("0.18.0".to_owned());
assert_eq!(
build(&st, Range::SinceReset, 100).summary_markdown,
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\
@@ -1066,7 +1119,7 @@ mod tests {
Vec::<&str>::new(),
"and the untouched starting point has no problems"
);
let empty = build(&State::default(), Range::Hour, 0);
let empty = broken("").view(Range::Hour, 0);
assert_eq!(
empty.summary_markdown,
"**sccache, last hour**\n\
@@ -1191,11 +1244,8 @@ mod tests {
.detail
.contains("The running sccache server is 0.18.0 but the `sccache` command is 0.19.0"));
let off = State {
error: Some("`sccache --show-stats --stats-format json`: command not found".to_owned()),
..State::default()
};
let v = build(&off, Range::Hour, 100);
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(),
@@ -1249,21 +1299,24 @@ mod tests {
fn running_means_compiles_in_the_last_five_minutes() {
let readings = vec![reading(0, 0, 0, 0), reading(1000, 5, 0, 5)];
assert_eq!(
build(&quiet_since(readings.clone(), 1200), Range::Hour, 1200)
quiet_since(readings.clone(), 1200)
.view(Range::Hour, 1200)
.server
.status,
Status::Running,
"a compile 200 s ago"
);
assert_eq!(
build(&quiet_since(readings, 1300), Range::Hour, 1300)
quiet_since(readings, 1300)
.view(Range::Hour, 1300)
.server
.status,
Status::Idle,
"the last compile was 300 s ago"
);
assert_eq!(
build(&state(vec![reading(0, 0, 0, 5)], None), Range::Hour, 100)
state(vec![reading(0, 0, 0, 5)], None)
.view(Range::Hour, 100)
.server
.status,
Status::NotRunning,
@@ -1275,13 +1328,13 @@ mod tests {
changed.totals.requests -= 3;
let quiet = state(vec![Reading { t: 0, c }], Some((1100, LIVE)));
assert_eq!(
build(&quiet, Range::Hour, 1100).server.status,
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!(
build(&busy, Range::Hour, 1100).server.status,
busy.view(Range::Hour, 1100).server.status,
Status::Running,
"the live reading saw three compiles"
);