Files
sccache-dash/crates/server/tests/http.rs
T
swaits 7f58931b7b 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.
2026-11-28 11:44:50 -07:00

409 lines
13 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};
use sccache_dash::history::History;
use sccache_dash::stats;
use sccache_dash_api::{Range, 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" ;;
*) 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.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()
}
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>, 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, history, 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, history, 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!(
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, history, 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.
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");
assert_eq!(
history.row_count().unwrap(),
1,
"the history stays, and the zeroing is one more row"
);
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"
);
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,
"and its chart starts at the reset: {:?}",
v.buckets
);
}
#[test]
fn view_export_and_the_page_answer() {
let fake = Fake::new();
let (_app, _history, 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 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!(
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::new(fake.config());
let history = History::memory().unwrap();
let rows = || history.row_count().unwrap();
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");
fake.answers(&LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"));
app.poll_at(&history, NOW + 30);
assert_eq!(
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,
"unchanged: nothing more is saved, however long the quiet lasts"
);
assert!(
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"
);
}