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:
1 parent
a83ae5e0d9
commit
7f58931b7b
8 files changed
+970
-642
No files matched your search
@@ -39,11 +39,15 @@ that origin is this server, so a web page elsewhere cannot zero the stats.
|
||||
|
||||
## Where history lives
|
||||
|
||||
`$XDG_DATA_HOME/sccache-dash/history.jsonl` (`~/.local/share/...` by default): one compact JSON
|
||||
line per reading, oldest first, at most one a minute and only when sccache's counters changed,
|
||||
plus one every ten minutes so that time with the service running can be told from time it was
|
||||
not. A reading is a few hundred bytes. Lines older than 30 days are deleted at startup and once
|
||||
a day. Deleting the file loses the history and nothing else.
|
||||
`$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
|
||||
|
||||
@@ -10,6 +10,7 @@ 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"
|
||||
|
||||
+115
-127
@@ -4,6 +4,7 @@ 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};
|
||||
@@ -12,38 +13,41 @@ use sccache_dash_api::{Range, View};
|
||||
use serde_json::Value;
|
||||
use wait_timeout::ChildExt;
|
||||
|
||||
use crate::history::{self, Reading};
|
||||
use crate::stats::{self, Counters, Snapshot};
|
||||
use crate::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 line is saved when the counters change, and at least this often besides, so that time
|
||||
/// with the service running can be told from time it was not.
|
||||
pub const HEARTBEAT_SECS: i64 = 600;
|
||||
/// Never more than one saved line per minute.
|
||||
pub const MIN_LINE_SECS: i64 = 60;
|
||||
/// A sccache command that takes longer than this counts as failed.
|
||||
const COMMAND_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
const PRUNE_EVERY: Duration = Duration::from_secs(86_400);
|
||||
/// 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,
|
||||
/// Where the history is saved.
|
||||
/// 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`.
|
||||
/// lives in `$XDG_DATA_HOME/sccache-dash/history.db`.
|
||||
pub fn from_env() -> Result<Config, String> {
|
||||
let sccache = std::env::var_os("SCCACHE_DASH_SCCACHE").unwrap_or_else(|| "sccache".into());
|
||||
let dir = dirs::data_dir()
|
||||
.ok_or("cannot find the data directory ($XDG_DATA_HOME, or ~/.local/share)")?;
|
||||
Ok(Config {
|
||||
sccache,
|
||||
history: dir.join("sccache-dash").join("history.jsonl"),
|
||||
history: dir.join("sccache-dash").join("history.db"),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -54,14 +58,6 @@ pub fn unix_now() -> i64 {
|
||||
.map_or(0, |d| d.as_secs() as i64)
|
||||
}
|
||||
|
||||
/// What happened between two consecutive saved readings, dated when the later one was taken.
|
||||
pub struct Interval {
|
||||
pub end: i64,
|
||||
/// sccache's counters went back to zero in this interval.
|
||||
pub reset: bool,
|
||||
pub delta: Counters,
|
||||
}
|
||||
|
||||
/// The last reading sccache answered.
|
||||
pub struct Live {
|
||||
pub at: i64,
|
||||
@@ -72,89 +68,74 @@ pub struct Live {
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct State {
|
||||
/// The saved readings, oldest first.
|
||||
pub readings: Vec<Reading>,
|
||||
/// One per reading after the first.
|
||||
pub intervals: Vec<Interval>,
|
||||
pub live: Option<Live>,
|
||||
/// sccache's output of the last good reading, as JSON.
|
||||
pub raw: Option<Value>,
|
||||
pub client_version: Option<String>,
|
||||
/// Why there is no live reading.
|
||||
pub error: Option<String>,
|
||||
/// Whether a failure to save has already been reported.
|
||||
pub warned: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
/// Adds a reading to the end of the history, with what changed since the one before it.
|
||||
pub fn push(&mut self, reading: Reading) {
|
||||
if let Some(last) = self.readings.last() {
|
||||
let (delta, reset) = reading.c.since(&last.c);
|
||||
self.intervals.push(Interval {
|
||||
end: reading.t,
|
||||
reset,
|
||||
delta,
|
||||
});
|
||||
}
|
||||
self.readings.push(reading);
|
||||
}
|
||||
|
||||
/// Works out again what changed between the saved readings, after they were pruned.
|
||||
pub fn relink(&mut self) {
|
||||
self.intervals = self
|
||||
.readings
|
||||
.windows(2)
|
||||
.map(|w| {
|
||||
let (delta, reset) = w[1].c.since(&w[0].c);
|
||||
Interval {
|
||||
end: w[1].t,
|
||||
reset,
|
||||
delta,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
/// 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<View>,
|
||||
/// 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<State>,
|
||||
pruned: Mutex<Instant>,
|
||||
/// Wakes the polling task, as `/api/zero` needs: only that task holds the database.
|
||||
wake: (Sender<()>, Mutex<Option<Receiver<()>>>),
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Loads the saved history, deleting what is older than 30 days.
|
||||
pub fn new(cfg: Config, now: i64) -> Result<App, String> {
|
||||
let mut state = State {
|
||||
readings: history::load(&cfg.history),
|
||||
..State::default()
|
||||
};
|
||||
history::prune(&mut state.readings, &cfg.history, now)
|
||||
.map_err(|e| format!("cannot prune {}: {e}", cfg.history.display()))?;
|
||||
state.relink();
|
||||
let pruned = Mutex::new(Instant::now());
|
||||
Ok(App {
|
||||
pub fn new(cfg: Config) -> App {
|
||||
let (send, receive) = channel();
|
||||
App {
|
||||
cfg,
|
||||
state: Mutex::new(state),
|
||||
pruned,
|
||||
})
|
||||
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 {
|
||||
view::build(&self.lock(), range, unix_now())
|
||||
let state = self.lock();
|
||||
match state.views.get(index(range)) {
|
||||
Some(view) => view.clone(),
|
||||
None => View {
|
||||
range: Some(range),
|
||||
..View::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn poll(&self) {
|
||||
self.poll_at(unix_now());
|
||||
/// 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<History, String> {
|
||||
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)
|
||||
}
|
||||
|
||||
/// Asks sccache for its counters and version, and saves a line when one is due.
|
||||
pub fn poll_at(&self, now: i64) {
|
||||
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| {
|
||||
@@ -171,27 +152,13 @@ impl App {
|
||||
state.client_version = version;
|
||||
match read {
|
||||
Ok((text, snapshot)) => {
|
||||
let live = Live {
|
||||
state.error = None;
|
||||
state.raw = serde_json::from_str(&text).ok();
|
||||
state.live = Some(Live {
|
||||
at: now,
|
||||
snapshot,
|
||||
raw_text: text,
|
||||
};
|
||||
state.raw = serde_json::from_str(&live.raw_text).ok();
|
||||
let due = match state.readings.last() {
|
||||
None => true,
|
||||
Some(last) => {
|
||||
last.c != live.snapshot.counters || now - last.t >= HEARTBEAT_SECS
|
||||
}
|
||||
};
|
||||
let too_soon = state
|
||||
.readings
|
||||
.last()
|
||||
.is_some_and(|last| now - last.t < MIN_LINE_SECS);
|
||||
state.error = None;
|
||||
state.live = Some(live);
|
||||
if due && !too_soon {
|
||||
self.save(&mut state, now);
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
state.error = Some(e);
|
||||
@@ -199,63 +166,84 @@ impl App {
|
||||
state.raw = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn save(&self, state: &mut State, now: i64) {
|
||||
let reading = Reading {
|
||||
t: now,
|
||||
c: state
|
||||
.live
|
||||
.as_ref()
|
||||
.map_or_else(Counters::default, |l| l.snapshot.counters.clone()),
|
||||
};
|
||||
match history::append(&self.cfg.history, &reading) {
|
||||
Ok(()) => state.push(reading),
|
||||
Err(e) => {
|
||||
if !state.warned {
|
||||
state.warned = true;
|
||||
eprintln!(
|
||||
"sccache-dash: cannot save history to {}: {e}",
|
||||
self.cfg.history.display()
|
||||
);
|
||||
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"])?;
|
||||
self.poll();
|
||||
// The counters are read again right away by the polling task, which owns the database.
|
||||
let _ = self.wake.0.send(());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Asks sccache for its counters every [`POLL`] and prunes the history once a day, until
|
||||
/// the process ends.
|
||||
/// 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<Self>) {
|
||||
thread::spawn(move || loop {
|
||||
self.poll();
|
||||
let mut pruned = self.pruned.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if pruned.elapsed() >= PRUNE_EVERY {
|
||||
*pruned = Instant::now();
|
||||
let mut state = self.lock();
|
||||
match history::prune(&mut state.readings, &self.cfg.history, unix_now()) {
|
||||
Ok(_) => state.relink(),
|
||||
Err(e) if !state.warned => {
|
||||
state.warned = true;
|
||||
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()
|
||||
);
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
match &wake {
|
||||
Some(receiver) => {
|
||||
let _ = receiver.recv_timeout(POLL);
|
||||
}
|
||||
None => thread::sleep(POLL),
|
||||
}
|
||||
}
|
||||
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<String, String> {
|
||||
let mut child = Command::new(sccache)
|
||||
|
||||
+347
-160
@@ -1,184 +1,371 @@
|
||||
//! The saved history: one compact JSON line per reading, oldest first.
|
||||
//! 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::fs::OpenOptions;
|
||||
use std::io::{self, Write};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use rusqlite::{params, params_from_iter, Connection, OptionalExtension};
|
||||
use sccache_dash_api::Totals;
|
||||
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
||||
|
||||
use crate::stats::Counters;
|
||||
use crate::stats::{Counters, COMPILE};
|
||||
|
||||
/// Readings older than this are deleted.
|
||||
/// 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;
|
||||
|
||||
/// sccache's counters at one moment.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Reading {
|
||||
/// Unix seconds.
|
||||
pub t: i64,
|
||||
#[serde(default)]
|
||||
pub c: Counters,
|
||||
}
|
||||
const NANOS: f64 = 1e9;
|
||||
|
||||
/// The saved readings; a line that cannot be read is skipped, not fatal.
|
||||
pub fn load(path: &Path) -> Vec<Reading> {
|
||||
std::fs::read_to_string(path)
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter_map(read_line)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One saved line. A counter the line does not have (it was written by another version of this
|
||||
/// program) reads as zero rather than making the whole line unreadable.
|
||||
fn read_line(line: &str) -> Option<Reading> {
|
||||
let mut value: Value = serde_json::from_str(line).ok()?;
|
||||
let defaults = serde_json::to_value(Counters::default()).ok()?;
|
||||
if let Some(counters) = value.get_mut("c") {
|
||||
fill_in(counters, &defaults);
|
||||
}
|
||||
serde_json::from_value(value).ok()
|
||||
}
|
||||
|
||||
/// Adds the keys of `defaults` that `value` lacks, recursively.
|
||||
fn fill_in(value: &mut Value, defaults: &Value) {
|
||||
let (Some(value), Some(defaults)) = (value.as_object_mut(), defaults.as_object()) else {
|
||||
return;
|
||||
/// 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)*)
|
||||
};
|
||||
for (key, default) in defaults {
|
||||
match value.get_mut(key) {
|
||||
None => {
|
||||
value.insert(key.clone(), default.clone());
|
||||
}
|
||||
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<dyn rusqlite::ToSql>); )* };
|
||||
}
|
||||
|
||||
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<Counters>,
|
||||
/// The running totals when the last row was saved.
|
||||
pub row_base: Option<Counters>,
|
||||
/// 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<History, String> {
|
||||
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<History> {
|
||||
Self::init(Connection::open_in_memory()?)
|
||||
}
|
||||
|
||||
fn init(conn: Connection) -> rusqlite::Result<History> {
|
||||
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<usize> {
|
||||
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<T: DeserializeOwned>(&self, key: &str) -> Option<T> {
|
||||
let text: Option<String> = 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<T: Serialize>(&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],
|
||||
)?;
|
||||
}
|
||||
Some(found) => fill_in(found, default),
|
||||
}
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds one line to the end.
|
||||
pub fn append(path: &Path, reading: &Reading) -> io::Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
/// Writes what changed since the row before.
|
||||
fn save(&self, t: i64, diff: &Counters, reset: bool) -> rusqlite::Result<()> {
|
||||
let mut values: Vec<Box<dyn rusqlite::ToSql>> = 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(())
|
||||
}
|
||||
let mut line = serde_json::to_string(reading)?;
|
||||
line.push('\n');
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(path)?
|
||||
.write_all(line.as_bytes())
|
||||
}
|
||||
|
||||
/// Deletes the readings older than [`KEEP_DAYS`], rewriting the file, and says how many went.
|
||||
pub fn prune(readings: &mut Vec<Reading>, path: &Path, now: i64) -> io::Result<usize> {
|
||||
let cutoff = now - KEEP_DAYS * 86_400;
|
||||
let keep = readings.iter().filter(|r| r.t >= cutoff).count();
|
||||
let removed = readings.len() - keep;
|
||||
if removed == 0 {
|
||||
return Ok(0);
|
||||
/// 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<Option<Totals>> {
|
||||
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
|
||||
})
|
||||
})
|
||||
}
|
||||
readings.drain(..removed);
|
||||
let mut text = String::new();
|
||||
for r in readings.iter() {
|
||||
text.push_str(&serde_json::to_string(r)?);
|
||||
text.push('\n');
|
||||
}
|
||||
let tmp = path.with_extension("jsonl.tmp");
|
||||
std::fs::write(&tmp, text)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn reading(t: i64, requests: u64) -> Reading {
|
||||
Reading {
|
||||
t,
|
||||
c: Counters {
|
||||
totals: sccache_dash_api::Totals {
|
||||
requests,
|
||||
..Default::default()
|
||||
/// The rows from `from` (inclusive) to `to` (exclusive), oldest first.
|
||||
pub fn rows(&self, from: i64, to: i64) -> rusqlite::Result<Vec<Row>> {
|
||||
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<u64> {
|
||||
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()
|
||||
},
|
||||
..Counters::default()
|
||||
},
|
||||
}
|
||||
})
|
||||
})?;
|
||||
rows.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_lines_are_deleted_at_startup() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("history.jsonl");
|
||||
let (day, now) = (86_400, 1_764_000_000);
|
||||
for (t, n) in [
|
||||
(now - 31 * day, 1),
|
||||
(now - 30 * day + 3600, 2),
|
||||
(now - 3600, 3),
|
||||
(now, 4),
|
||||
] {
|
||||
append(&path, &reading(t, n)).unwrap();
|
||||
}
|
||||
|
||||
let mut readings = load(&path);
|
||||
assert_eq!(readings.len(), 4);
|
||||
assert_eq!(prune(&mut readings, &path, now).unwrap(), 1);
|
||||
assert_eq!(
|
||||
readings,
|
||||
vec![
|
||||
reading(now - 30 * day + 3600, 2),
|
||||
reading(now - 3600, 3),
|
||||
reading(now, 4)
|
||||
]
|
||||
);
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let lines: Vec<_> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 3, "the file itself was rewritten");
|
||||
assert!(lines[0].contains("\"requests\":2"));
|
||||
assert!(
|
||||
!path.with_extension("jsonl.tmp").exists(),
|
||||
"the temporary file is gone"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
prune(&mut readings, &path, now).unwrap(),
|
||||
0,
|
||||
"nothing more to delete"
|
||||
);
|
||||
/// (language, hits, misses, errors) summed over the rows from `from` to `to`.
|
||||
pub fn languages(&self, from: i64, to: i64) -> rusqlite::Result<Vec<(String, [u64; 3])>> {
|
||||
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()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_damaged_file_is_not_fatal() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("nested").join("history.jsonl");
|
||||
assert!(load(&path).is_empty(), "no file yet");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(
|
||||
&path,
|
||||
"{\"t\":1,\"c\":{\"totals\":{\"requests\":7}}}\nnot json\n{\"t\":2}\n",
|
||||
)
|
||||
.unwrap();
|
||||
let readings = load(&path);
|
||||
assert_eq!(readings.len(), 2, "the unreadable line is skipped");
|
||||
assert_eq!(readings[0].c.totals.requests, 7);
|
||||
assert_eq!(
|
||||
readings[1],
|
||||
Reading {
|
||||
t: 2,
|
||||
c: Counters::default()
|
||||
},
|
||||
"missing counters read as zero"
|
||||
);
|
||||
assert_eq!(
|
||||
prune(&mut readings.clone(), &path, 1_764_000_000).unwrap(),
|
||||
2,
|
||||
"both are older than 30 days"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&path).unwrap(),
|
||||
"",
|
||||
"and the file is emptied"
|
||||
);
|
||||
/// (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<Vec<(i64, String, u64, u64)>> {
|
||||
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<Vec<(String, u64)>> {
|
||||
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<u64> {
|
||||
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<Option<i64>> {
|
||||
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<Option<i64>> {
|
||||
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<usize> {
|
||||
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<BTreeMap<String, (f64, u64)>> {
|
||||
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<BTreeMap<String, Vec<BuildObs>>> {
|
||||
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<String, Vec<BuildObs>> = 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;";
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::process::{Command as Process, Stdio};
|
||||
use std::sync::Arc;
|
||||
|
||||
use sccache_dash::app::{unix_now, App, Config};
|
||||
use sccache_dash::app::{App, Config};
|
||||
use sccache_dash::{http, systemd};
|
||||
|
||||
const USAGE: &str = "\
|
||||
@@ -79,7 +79,7 @@ fn parse(args: &[String]) -> Result<Command, String> {
|
||||
}
|
||||
|
||||
fn serve(port: u16, open: bool) -> Result<(), String> {
|
||||
let app = Arc::new(App::new(Config::from_env()?, unix_now())?);
|
||||
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}");
|
||||
|
||||
+13
-16
@@ -106,6 +106,13 @@ impl Counters {
|
||||
(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 {
|
||||
@@ -422,22 +429,12 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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
|
||||
);
|
||||
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::<Counters>(&text).unwrap(), counters);
|
||||
assert!(text.len() < 1024, "{} bytes: {text}", text.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+310
-257
@@ -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 × {
|
||||
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"
|
||||
);
|
||||
|
||||
+173
-75
@@ -8,8 +8,8 @@ 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::view;
|
||||
use sccache_dash_api::{Range, Status, Totals, View};
|
||||
|
||||
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
|
||||
@@ -19,7 +19,7 @@ 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,
|
||||
dir: tempfile::TempDir,
|
||||
script: PathBuf,
|
||||
log: PathBuf,
|
||||
history: PathBuf,
|
||||
@@ -45,13 +45,18 @@ esac
|
||||
std::fs::write(dir.path().join("sccache.out"), LIVE).unwrap();
|
||||
std::fs::write(dir.path().join("sccache.zeroed"), ZEROED).unwrap();
|
||||
Fake {
|
||||
script,
|
||||
log: dir.path().join("sccache.log"),
|
||||
history: dir.path().join("data").join("history.jsonl"),
|
||||
_dir: dir,
|
||||
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<String> {
|
||||
std::fs::read_to_string(&self.log)
|
||||
@@ -60,21 +65,26 @@ esac
|
||||
.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, polled once, answering in the background.
|
||||
fn start(fake: &Fake) -> (Arc<App>, SocketAddr) {
|
||||
let cfg = Config {
|
||||
sccache: fake.script.clone().into(),
|
||||
history: fake.history.clone(),
|
||||
};
|
||||
let app = Arc::new(App::new(cfg, NOW).unwrap());
|
||||
app.poll_at(NOW);
|
||||
/// 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<App>, 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, addr)
|
||||
(app, history, addr)
|
||||
}
|
||||
|
||||
/// Sends one raw request (`{port}` stands for the server's port) and returns the whole response.
|
||||
@@ -109,7 +119,7 @@ fn zero(addr: SocketAddr, host: Option<&str>, origin: Option<&str>) -> (u16, Str
|
||||
#[test]
|
||||
fn zero_is_refused_for_a_foreign_origin_or_host() {
|
||||
let fake = Fake::new();
|
||||
let (app, addr) = start(&fake);
|
||||
let (app, history, addr) = start(&fake);
|
||||
|
||||
// A page anywhere else, in any shape: a bare host, another port, or "null".
|
||||
for origin in [
|
||||
@@ -143,18 +153,21 @@ fn zero_is_refused_for_a_foreign_origin_or_host() {
|
||||
"sccache was never asked to zero: {:?}",
|
||||
fake.calls()
|
||||
);
|
||||
assert_eq!(app.lock().readings.len(), 1, "and the history is as it was");
|
||||
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, addr) = start(&fake);
|
||||
assert_eq!(
|
||||
app.lock().readings.len(),
|
||||
1,
|
||||
"the first reading is saved as the baseline"
|
||||
);
|
||||
let (app, history, addr) = start(&fake);
|
||||
|
||||
let (code, response) = zero(
|
||||
addr,
|
||||
@@ -172,38 +185,43 @@ fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
|
||||
"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",
|
||||
"the counters are read again right after zeroing"
|
||||
);
|
||||
assert_eq!(calls.last().unwrap(), "--show-stats --stats-format json");
|
||||
|
||||
let state = app.lock();
|
||||
assert_eq!(
|
||||
state.readings.len(),
|
||||
2,
|
||||
"the baseline is kept and a line was added for the reset"
|
||||
history.row_count().unwrap(),
|
||||
1,
|
||||
"the history stays, and the zeroing is one more row"
|
||||
);
|
||||
assert_eq!(state.intervals.len(), 1);
|
||||
assert!(
|
||||
state.intervals[0].reset,
|
||||
"the zeroing shows in the history as a reset"
|
||||
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"
|
||||
);
|
||||
let v = view::build(&state, Range::SinceReset, unix_now());
|
||||
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);
|
||||
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, addr) = start(&fake);
|
||||
let (_app, _history, addr) = start(&fake);
|
||||
|
||||
let response = send(addr, &format!("GET /api/view?range=reset{GET}"));
|
||||
assert!(
|
||||
@@ -228,6 +246,11 @@ fn view_export_and_the_page_answer() {
|
||||
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!(
|
||||
@@ -262,49 +285,124 @@ fn view_export_and_the_page_answer() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lines_are_saved_when_counters_change_and_at_most_once_a_minute() {
|
||||
fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() {
|
||||
let fake = Fake::new();
|
||||
let cfg = Config {
|
||||
sccache: fake.script.clone().into(),
|
||||
history: fake.history.clone(),
|
||||
};
|
||||
let app = App::new(cfg, NOW).unwrap();
|
||||
let lines = |app: &App| app.lock().readings.len();
|
||||
let app = App::new(fake.config());
|
||||
let history = History::memory().unwrap();
|
||||
let rows = || history.row_count().unwrap();
|
||||
|
||||
app.poll_at(NOW);
|
||||
assert_eq!(lines(&app), 1, "the first reading is the baseline");
|
||||
app.poll_at(NOW + 10);
|
||||
assert_eq!(lines(&app), 1, "nothing changed");
|
||||
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");
|
||||
|
||||
std::fs::write(
|
||||
fake._dir.path().join("sccache.out"),
|
||||
LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"),
|
||||
)
|
||||
.unwrap();
|
||||
app.poll_at(NOW + 30);
|
||||
fake.answers(&LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"));
|
||||
app.poll_at(&history, NOW + 30);
|
||||
assert_eq!(
|
||||
lines(&app),
|
||||
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,
|
||||
"changed, but less than a minute after the last line"
|
||||
);
|
||||
app.poll_at(NOW + 60);
|
||||
assert_eq!(
|
||||
lines(&app),
|
||||
2,
|
||||
"a minute after the last line, the change is saved"
|
||||
);
|
||||
assert_eq!(app.lock().intervals[0].delta.totals.requests, 1);
|
||||
|
||||
app.poll_at(NOW + 60 + sccache_dash::app::HEARTBEAT_SECS - 1);
|
||||
assert_eq!(lines(&app), 2, "unchanged, and not yet ten minutes");
|
||||
app.poll_at(NOW + 60 + sccache_dash::app::HEARTBEAT_SECS);
|
||||
assert_eq!(
|
||||
lines(&app),
|
||||
3,
|
||||
"every ten minutes a line marks that the service is running"
|
||||
"unchanged: nothing more is saved, however long the quiet lasts"
|
||||
);
|
||||
assert!(
|
||||
app.lock().intervals[1].delta.totals == Totals::default(),
|
||||
"the heartbeat line records no change"
|
||||
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<i64> = 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"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user