Files
sccache-dash/crates/server/tests/http.rs
T
swaits 16ba94517b Bucket in SQLite, draw the build-time bootstrap once, start sccache's server
Speed: the chart's counts come from GROUP BY over the bucket number, so
about 120 rows per table per range reach Rust instead of every saved row;
a range total is one indexed SUM. History counts the rows it hands out.

Build times: crates/stats gains Resampled, which draws the bootstrap once
for a set of languages and applies it to any number of hit sets; the
server keeps it and redraws only when an observation was added. The
views fill build_times, time saved and the 90% interval from the stats
crate, and the time-saved arithmetic of the server is gone.

Starting sccache: when nothing listens where the client looks
(SCCACHE_SERVER_UDS, or 127.0.0.1 at SCCACHE_SERVER_PORT), sccache
--start-server is run once and the counters read again; a failure is
reported as NotRunning and not retried for a minute.

Uses the api's Range::ALL, parse and label.
2026-11-28 11:57:10 -07:00

528 lines
17 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"
);
let row = &task.history.rows(0, i64::MAX).unwrap()[0];
assert!(row.reset, "the zeroing shows in the history as a reset");
assert_eq!(
row.delta,
stats::Counters::default(),
"nothing has been compiled since"
);
assert_eq!(task.history.last_reset().unwrap(), Some(row.t));
let v = app.view(Range::SinceReset);
assert_eq!(
v.totals,
Totals::default(),
"sccache's counters read zero now"
);
assert!(
v.buckets[0].reset,
"and its chart starts at the reset: {:?}",
v.buckets
);
}
#[test]
fn view_export_and_the_page_answer() {
let fake = Fake::new();
let (_app, _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"
);
let row = &task.history.rows(0, i64::MAX).unwrap()[0];
assert_eq!(
(row.t, row.delta.totals.requests, row.reset),
(NOW + 60, 1, false)
);
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_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"
);
}
#[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);
}