Files
sccache-dash/crates/server/tests/http.rs
T
swaits 693dca6cdf Prove the steady cost by count, redraw the bootstrap once a minute, tidy
A test fills a history with a row a minute for thirty days (43,199 rows,
4,319 build observations) in one transaction, runs two polls and asserts
the second hands out fewer than 3,000 rows; it measures 1,567 (the first
reads every observation once). History::fill saves a run of readings as
the polls would have.

While a build keeps adding observations, they are stored at once but the
bootstrap and the histogram are redrawn at most once a minute.

A saving is never negative or a negative zero.

History::rows and History::build_observations are gone, with the tests
that only used them. History::first_row stays: without it the chart of
the reset range, on a database that never saw a zeroing, would start at
the live reading instead of at the first row.

The timing line is logged for the first two polls.
2026-11-28 12:07:56 -07:00

665 lines
22 KiB
Rust

//! The server as seen from a socket, with a stand-in for sccache so that the real one is never touched.
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use std::sync::Arc;
use std::thread;
use sccache_dash::app::{unix_now, App, Config, Probe, Prober, Task};
use sccache_dash::history::History;
use sccache_dash::stats;
use sccache_dash_api::{Range, Severity, Status, Totals, View};
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
const ZEROED: &str = "{\"stats\":{\"compile_requests\":0,\"cache_hits\":{\"counts\":{},\"adv_counts\":{}},\"cache_misses\":{\"counts\":{},\"adv_counts\":{}},\"cache_errors\":{\"counts\":{},\"adv_counts\":{}}},\"version\":\"0.18.0\"}";
const NOW: i64 = 1_764_000_000;
/// A script that answers like sccache: it prints a fixture for `--show-stats` and swaps in
/// `ZEROED` when asked to zero the stats. Every call is logged.
struct Fake {
dir: tempfile::TempDir,
script: PathBuf,
log: PathBuf,
history: PathBuf,
}
impl Fake {
fn new() -> Fake {
let dir = tempfile::tempdir().unwrap();
let script = dir.path().join("sccache");
std::fs::write(
&script,
r#"#!/bin/sh
printf '%s\n' "$*" >> "$0.log"
case "$1" in
--version) echo 'sccache 0.18.0' ;;
--zero-stats) cp "$0.zeroed" "$0.out" ;;
--start-server) if [ -e "$0.no-start" ]; then echo "Server startup failed: Address in use" >&2; exit 1; fi; cp "$0.live" "$0.out"; touch "$0.running"; echo started ;;
*) cat "$0.out" ;;
esac
"#,
)
.unwrap();
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::write(dir.path().join("sccache.out"), LIVE).unwrap();
std::fs::write(dir.path().join("sccache.live"), LIVE).unwrap();
std::fs::write(dir.path().join("sccache.running"), "").unwrap();
std::fs::write(dir.path().join("sccache.zeroed"), ZEROED).unwrap();
Fake {
log: dir.path().join("sccache.log"),
history: dir.path().join("data").join("history.db"),
dir,
script,
}
}
/// What `--show-stats` prints from now on.
fn answers(&self, text: &str) {
std::fs::write(self.dir.path().join("sccache.out"), text).unwrap();
}
/// The arguments of every call so far, one entry per call.
fn calls(&self) -> Vec<String> {
std::fs::read_to_string(&self.log)
.unwrap_or_default()
.lines()
.map(str::to_owned)
.collect()
}
/// No server running: `--show-stats` then answers with empty counters, as the real one does.
fn down(&self) {
std::fs::remove_file(self.dir.path().join("sccache.running")).unwrap();
self.answers(ZEROED);
}
/// The stand-in for the check on whether sccache's server is listening.
fn probe(&self) -> Prober {
let marker = self.dir.path().join("sccache.running");
Arc::new(move || {
if marker.exists() {
Probe::Running
} else {
Probe::NotRunning
}
})
}
fn config(&self) -> Config {
Config {
sccache: self.script.clone().into(),
history: self.history.clone(),
}
}
}
/// A server on a free port next to an empty history, polled once, answering in the background.
/// The test stands in for the polling task: it holds the history and polls by hand.
fn start(fake: &Fake) -> (Arc<App>, Task, SocketAddr) {
let app = Arc::new(App::with_probe(fake.config(), fake.probe()));
let mut task = Task::memory();
task.poll(&app, 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, task, addr)
}
/// Sends one raw request (`{port}` stands for the server's port) and returns the whole response.
fn send(addr: SocketAddr, request: &str) -> String {
let request = request.replace("{port}", &addr.port().to_string());
let mut stream = TcpStream::connect(addr).unwrap();
stream.write_all(request.as_bytes()).unwrap();
let mut response = String::new();
stream.read_to_string(&mut response).unwrap();
response
}
const GET: &str = " HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n";
/// `POST /api/zero` with the given `Host` and `Origin` headers; returns the status and the response.
fn zero(addr: SocketAddr, host: Option<&str>, origin: Option<&str>) -> (u16, String) {
let mut request = String::from("POST /api/zero HTTP/1.1\r\n");
for (name, value) in [("Host:", host), ("Origin:", origin)] {
if let Some(value) = value {
request.push_str(&format!("{name} {value}\r\n"));
}
}
request.push_str("Content-Length: 0\r\nConnection: close\r\n\r\n");
let response = send(addr, &request);
let code = response
.split_whitespace()
.nth(1)
.and_then(|c| c.parse().ok());
(code.unwrap_or(0), response)
}
#[test]
fn zero_is_refused_for_a_foreign_origin_or_host() {
let fake = Fake::new();
let (app, task, addr) = start(&fake);
// A page anywhere else, in any shape: a bare host, another port, or "null".
for origin in [
"https://evil.example",
"http://127.0.0.1:1",
"http://localhost.evil.example:{port}",
"null",
] {
let (code, response) = zero(addr, Some("127.0.0.1:{port}"), Some(origin));
assert_eq!(
(code, response.contains("refused")),
(403, true),
"Origin {origin}"
);
}
// A host name that merely leads here (DNS rebinding) or is not plainly localhost.
for host in [
"evil.example:{port}",
"127.0.0.1.evil.example:{port}",
"localhost:{port}@evil.example",
"[::1]:{port}",
] {
let (code, _) = zero(addr, Some(host), None);
assert_eq!(code, 403, "Host {host}");
}
let (code, _) = zero(addr, None, None);
assert_eq!(code, 403, "no Host at all");
assert!(
!fake.calls().iter().any(|c| c == "--zero-stats"),
"sccache was never asked to zero: {:?}",
fake.calls()
);
assert_eq!(
task.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, mut task, addr) = start(&fake);
let (code, response) = zero(
addr,
Some("127.0.0.1:{port}"),
Some("http://127.0.0.1:{port}"),
);
assert_eq!(
(code, response.contains("the saved history is kept")),
(200, true),
"{response}"
);
assert_eq!(
zero(addr, Some("localhost:{port}"), None).0,
200,
"no Origin, as from curl"
);
// What the polling task then does, woken by the request: it reads the counters again.
task.poll(&app, unix_now());
let calls = fake.calls();
assert_eq!(calls.iter().filter(|c| *c == "--zero-stats").count(), 2);
assert_eq!(calls.last().unwrap(), "--show-stats --stats-format json");
assert_eq!(
task.history.row_count().unwrap(),
1,
"the history stays, and the zeroing is one more row"
);
assert!(
task.history.last_reset().unwrap().is_some(),
"the zeroing shows in the history as a reset"
);
assert_eq!(
task.history.sums(0, i64::MAX).unwrap(),
Some(stats::Counters::default()),
"nothing has been compiled since"
);
let v = app.view(Range::SinceReset);
assert_eq!(
v.totals,
Totals::default(),
"sccache's counters read zero now"
);
assert!(
v.buckets[0].reset,
"and its chart starts at the reset: {:?}",
v.buckets
);
}
#[test]
fn view_export_and_the_page_answer() {
let fake = Fake::new();
let (_app, _task, addr) = start(&fake);
let response = send(addr, &format!("GET /api/view?range=reset{GET}"));
assert!(
response.starts_with("HTTP/1.1 200 OK\r\n")
&& response.contains("Content-Type: application/json\r\n"),
"{response}"
);
let body = response.split("\r\n\r\n").nth(1).unwrap();
let v: View = serde_json::from_str(body).unwrap();
assert_eq!(v.totals, stats::parse(LIVE).unwrap().counters.totals);
assert_eq!(
(v.range, v.server.status),
(Some(Range::SinceReset), Status::Idle)
);
assert_eq!(
(
v.server.version.as_deref(),
v.server.client_version.as_deref()
),
(Some("0.18.0"), Some("0.18.0"))
);
assert!(v.summary_markdown.starts_with("**sccache, since reset**\n"));
for range in ["1h", "24h", "7d", "30d"] {
let response = send(addr, &format!("GET /api/view?range={range}{GET}"));
let v: View = serde_json::from_str(response.split("\r\n\r\n").nth(1).unwrap()).unwrap();
assert_eq!(v.buckets.len(), 120, "{range}");
}
let response = send(addr, &format!("GET /api/export{GET}"));
assert!(
response.contains("Content-Type: application/json\r\n"),
"{response}"
);
assert!(
response.contains(&format!(
"Content-Disposition: attachment; filename=\"sccache-stats-{}.json\"",
sccache_dash::pretty::stamp(NOW)
)),
"{response}"
);
assert!(response.ends_with(LIVE), "exactly as sccache printed it");
let response = send(addr, &format!("GET /{GET}"));
assert!(
response.starts_with("HTTP/1.1 200 OK\r\n")
&& response.contains("Content-Type: text/html; charset=utf-8\r\n"),
"{response}"
);
assert!(send(addr, &format!("HEAD /{GET}")).starts_with("HTTP/1.1 200 OK\r\n"));
assert!(send(addr, &format!("GET /api/view?range=bogus{GET}")).starts_with("HTTP/1.1 400"));
assert!(
send(addr, &format!("GET /api/view{GET}")).starts_with("HTTP/1.1 400"),
"no range at all"
);
assert!(send(addr, &format!("GET /../Cargo.toml{GET}")).starts_with("HTTP/1.1 404"));
assert!(send(addr, &format!("GET /no-such-file.wasm{GET}")).starts_with("HTTP/1.1 404"));
assert!(send(addr, &format!("PUT /api/zero{GET}")).starts_with("HTTP/1.1 405"));
}
#[test]
fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() {
let fake = Fake::new();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
task.poll(&app, NOW);
assert_eq!(
task.history.row_count().unwrap(),
0,
"the first reading is a baseline, not a row"
);
task.poll(&app, NOW + 10);
assert_eq!(task.history.row_count().unwrap(), 0, "nothing changed");
fake.answers(&LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"));
task.poll(&app, NOW + 30);
assert_eq!(
task.history.row_count().unwrap(),
0,
"changed, but less than a minute after the baseline"
);
task.poll(&app, NOW + 60);
assert_eq!(
task.history.row_count().unwrap(),
1,
"a minute on, the change is saved"
);
assert_eq!(
task.history
.sums(0, i64::MAX)
.unwrap()
.unwrap()
.totals
.requests,
1
);
assert_eq!(
task.history.last_reset().unwrap(),
None,
"a change is not a reset"
);
task.poll(&app, NOW + 700);
assert_eq!(
task.history.row_count().unwrap(),
1,
"unchanged: nothing more is saved, however long the quiet lasts"
);
assert!(
task.history.build_obs_stamp().unwrap() == (0, 0),
"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();
assert_eq!(history.row_count().unwrap(), 1);
assert_eq!(
history.sums(0, i64::MAX).unwrap().unwrap().totals.requests,
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"
);
assert_eq!(history.row_count().unwrap(), 3);
assert_eq!(
history.first_row().unwrap(),
Some(NOW - 30 * day + 3600),
"the oldest row left"
);
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"
);
}
#[test]
fn a_missing_sccache_server_is_started_once_then_read() {
let fake = Fake::new();
fake.down();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
task.poll(&app, NOW);
let calls = fake.calls();
assert_eq!(
calls.iter().filter(|c| *c == "--start-server").count(),
1,
"{calls:?}"
);
assert_eq!(
calls.last().unwrap(),
"--show-stats --stats-format json",
"the counters are read again after starting"
);
let v = app.view(Range::SinceReset);
assert_eq!(v.server.status, Status::Idle, "{:?}", v.server.error);
assert_eq!(
v.totals,
stats::parse(LIVE).unwrap().counters.totals,
"the started server's counters, not the empty ones"
);
task.poll(&app, NOW + 10);
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
1,
"not started again while it is running"
);
}
#[test]
fn a_server_that_will_not_start_is_reported_and_not_retried_for_a_minute() {
let fake = Fake::new();
fake.down();
std::fs::write(fake.dir.path().join("sccache.no-start"), "").unwrap();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
for at in [NOW, NOW + 10, NOW + 50] {
task.poll(&app, at);
let v = app.view(Range::Day);
assert_eq!(v.server.status, Status::NotRunning, "polled at {at}");
assert!(
v.server
.error
.as_deref()
.is_some_and(|e| e.contains("`sccache --start-server` failed")),
"{:?}",
v.server.error
);
assert!(
v.problems
.iter()
.any(|p| p.severity == Severity::Error && p.title == "sccache is not running"),
"{:?}",
v.problems
);
}
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
1,
"tried once"
);
task.poll(&app, NOW + 60);
assert_eq!(
fake.calls()
.iter()
.filter(|c| *c == "--start-server")
.count(),
2,
"and again a minute later"
);
// Meanwhile the server came up by itself (a compile started it): no more error. Its counters
// differ from the empty ones, so that counts as compiles having arrived.
std::fs::write(fake.dir.path().join("sccache.running"), "").unwrap();
fake.answers(LIVE);
task.poll(&app, NOW + 70);
assert_eq!(app.view(Range::Day).server.status, Status::Running);
assert_eq!(app.view(Range::Day).server.error, None);
}
/// The real output with `more` more Rust builds in it: that many more requests, misses and compiles.
fn with_more_rust_builds(more: u64) -> String {
let text = LIVE.replace(
"\"compile_requests\":7351",
&format!("\"compile_requests\":{}", 7351 + more),
);
let text = text.replace("\"Rust\":3256", &format!("\"Rust\":{}", 3256 + more));
let text = text.replace("\"rust\":3256", &format!("\"rust\":{}", 3256 + more));
let text = text.replace(
"\"compilations\":3256",
&format!("\"compilations\":{}", 3256 + more),
);
let text = text.replace(
"\"cache_writes\":3256",
&format!("\"cache_writes\":{}", 3256 + more),
);
text.replace(
"\"compiler_write_duration\":{\"secs\":25343",
&format!(
"\"compiler_write_duration\":{{\"secs\":{}",
25343 + 8 * more
),
)
}
#[test]
fn the_bootstrap_is_not_redrawn_on_every_poll_of_a_build_in_flight() {
let fake = Fake::new();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
let rust_builds = |app: &App| {
app.view(Range::Day)
.build_times
.first()
.map_or(0, |t| t.compiles)
};
task.poll(&app, NOW);
assert_eq!(rust_builds(&app), 0, "nothing seen yet");
// A build adds one Rust build between every pair of polls. Each is stored at once, but the
// histogram (and with it the bootstrap) waits for the one-minute beat.
for step in 1..6u64 {
fake.answers(&with_more_rust_builds(step));
task.poll(&app, NOW + (step as i64) * 10);
assert_eq!(
task.history.build_obs_stamp().unwrap().0,
step as i64,
"observation {step} is stored at once"
);
assert_eq!(
rust_builds(&app),
0,
"but the bootstrap drawn at the first poll stands (step {step})"
);
}
fake.answers(&with_more_rust_builds(6));
task.poll(&app, NOW + 60);
assert_eq!(
rust_builds(&app),
6,
"a minute after the last draw, everything seen so far is drawn in"
);
fake.answers(&with_more_rust_builds(7));
task.poll(&app, NOW + 70);
assert_eq!(
rust_builds(&app),
6,
"and it stands again until the next beat"
);
}
#[test]
fn a_full_history_costs_few_rows_on_the_second_poll() {
// Thirty days with a row every minute: the most there can ever be. Two languages miss most
// minutes, so only one minute in ten gives a build observation.
let fake = Fake::new();
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::memory();
let day = 86_400;
let mut c = stats::Counters::default();
let mut readings = Vec::new();
for step in 0..43_200i64 {
let (rust, cxx) = if step % 10 == 0 { (2, 0) } else { (1, 1) };
c.totals.requests += 10;
c.totals.executed += 8;
c.totals.hits += 6;
c.totals.misses += rust + cxx;
c.totals.not_cacheable += 2;
c.totals.cache_writes += rust + cxx;
c.compilations += rust + cxx;
c.ns = [
c.ns[0] + 6 * 10_000_000,
c.ns[1] + (rust + cxx) * 1_000_000_000,
c.ns[2] + (rust + cxx) * 8_000_000_000,
];
c.langs = vec![
("Assembler".to_owned(), [2, 0, 0]),
("C/C++".to_owned(), [4, cxx, 0]),
("Rust".to_owned(), [0, rust, 0]),
];
readings.push((NOW - 30 * day + step * 60, c.clone()));
}
task.history.fill(&readings).unwrap();
assert_eq!(
task.history.row_count().unwrap(),
43_199,
"the first reading is the baseline"
);
let observations = task.history.build_obs_stamp().unwrap().0;
assert_eq!(observations, 4_319, "one for every tenth minute after the baseline");
task.poll(&app, NOW);
let first = app.lock().views_rows;
task.poll(&app, NOW + 10);
let second = app.lock().views_rows;
eprintln!("rows handed out: first poll {first} (reading {observations} build observations once), second poll {second}");
assert!(
first >= observations as usize,
"the first poll reads every observation once"
);
assert!(second < 3_000, "the second poll handed out {second} rows");
let v = app.view(Range::Day);
assert_eq!(v.buckets.len(), 120);
}