Server half of sccache-dash

Polls sccache's counters every 10 s, keeps a JSON-lines history, and serves
the page and its API on 127.0.0.1: one difference-with-reset mechanism behind
every range, per-language time saved, problems, a copyable summary, and
extra tables for multi-level and distributed caches.

The page is embedded from crates/ui/dist when it exists, with a placeholder
until then. POST /api/zero refuses foreign Host and Origin headers.
Tests run against a stand-in sccache script; sample fixtures for the
multi-level and distributed shapes are made up.
This commit is contained in:
swaits committed 2026-11-28 11:23:39 -07:00
1 parent a8e7bd66cf
commit 3cbc02e631
18 files changed
+3654

No files matched your search

+176
View File
@@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 sccache-dash contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+60
View File
@@ -0,0 +1,60 @@
# sccache-dash
A small Linux program in the manner of Syncthing: one binary that watches the local
[sccache](https://github.com/mozilla/sccache) compiler cache, remembers what it did, and serves
a dashboard for it at <http://127.0.0.1:8226>. It listens on this machine only.
It asks sccache for its counters every 10 seconds, works out hit rates, time saved and what looks
wrong, and sends the page one `View` to draw (the contract is `crates/api`).
## Install
```
just build # builds the page (trunk) and then the server
sccache-dash # serves http://127.0.0.1:8226 and opens it
sccache-dash install # the same, as a systemd user service that starts at login
sccache-dash uninstall
```
`sccache-dash [--port N] [--no-open]` serves. `install` writes
`~/.config/systemd/user/sccache-dash.service` with the absolute path of the binary and the `PATH`
of the shell that ran it, so that `sccache` is found; the service never opens a browser.
`SCCACHE_DASH_SCCACHE` names the sccache command when it is not simply `sccache` on `PATH`.
Until the page has been built (`crates/ui/dist`), the server serves a placeholder saying so; its
API answers either way.
## Routes
| Route | What it does |
| --- | --- |
| `GET /api/view?range=1h\|24h\|7d\|30d\|reset` | one `View`: totals, the period before, timing, time saved, languages, buckets, problems, a summary |
| `GET /api/export` | sccache's current stats exactly as `sccache --show-stats --stats-format json` prints them, as a download |
| `POST /api/zero` | runs `sccache --zero-stats`; the saved history is kept |
| `GET /` | the page |
`/api/zero` is refused unless the request's `Host` is localhost and, when it has an `Origin`,
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.
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
reading ever is a baseline and counts for nothing.
## Notes on sccache
While sccache's server is running, being asked for its stats every 10 seconds keeps it from its
10-minute idle shutdown. When it is not running, `sccache --show-stats` does not start it (it
prints empty counters) and neither does this program; the next compile starts it, as usual.
## Licence
MIT or Apache-2.0, at your choice (`LICENSE-MIT`, `LICENSE-APACHE`).
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "sccache-dash"
description = "Records sccache's counters and serves a dashboard for them on localhost"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
sccache-dash-api = { path = "../api" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tiny_http = "0.12"
wait-timeout = "0.2"
dirs = "6"
include_dir = "0.7"
[dev-dependencies]
tempfile = "3"
+37
View File
@@ -0,0 +1,37 @@
//! Puts the page into the binary. The page is what `trunk build --release` writes to
//! `crates/ui/dist`; until it has been built, a placeholder page stands in for it.
use std::path::Path;
const PLACEHOLDER: &str = "<!doctype html>
<meta charset=\"utf-8\">
<title>sccache-dash</title>
<body style=\"font: 16px sans-serif; margin: 3em auto; max-width: 34em;\">
<h1>The sccache dashboard page is not built</h1>
<p>The server is running and its <a href=\"/api/view?range=24h\">API</a> answers, but the page
that draws it is missing. Run <code>just build</code> in the repository (it runs
<code>trunk build --release</code> in <code>crates/ui</code>) and start sccache-dash again.
";
fn main() {
let crates = Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
.parent()
.expect("crates/server has a parent")
.to_path_buf();
let dist = crates.join("ui").join("dist");
// Checked on every build, so the page is picked up as soon as `trunk build` has made it.
println!(
"cargo:rerun-if-changed={}",
dist.join("index.html").display()
);
let site = if dist.join("index.html").is_file() {
dist
} else {
let out = Path::new(&std::env::var("OUT_DIR").unwrap()).join("site");
std::fs::create_dir_all(&out).unwrap();
std::fs::write(out.join("index.html"), PLACEHOLDER).unwrap();
out
};
println!("cargo:rustc-env=DASH_SITE={}", site.display());
}
+295
View File
@@ -0,0 +1,295 @@
//! What the service knows right now, and how it is kept up to date.
use std::ffi::{OsStr, OsString};
use std::io::{ErrorKind, Read};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::thread;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
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::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);
pub struct Config {
/// The sccache command the service runs.
pub sccache: OsString,
/// Where the history is saved.
pub history: PathBuf,
}
impl Config {
/// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset); the history
/// lives in `$XDG_DATA_HOME/sccache-dash`.
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"),
})
}
}
pub fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.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,
pub snapshot: Snapshot,
/// sccache's output, exactly as it printed it.
pub raw_text: String,
}
#[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();
}
}
pub struct App {
pub cfg: Config,
state: Mutex<State>,
pruned: Mutex<Instant>,
}
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 {
cfg,
state: Mutex::new(state),
pruned,
})
}
pub fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn view(&self, range: Range) -> View {
view::build(&self.lock(), range, unix_now())
}
pub fn poll(&self) {
self.poll_at(unix_now());
}
/// Asks sccache for its counters and version, and saves a line when one is due.
pub fn poll_at(&self, now: i64) {
let version = run(&self.cfg.sccache, &["--version"])
.ok()
.and_then(|text| {
text.split_whitespace()
.find(|w| w.starts_with(|c: char| c.is_ascii_digit()))
.map(str::to_owned)
});
let read = run(
&self.cfg.sccache,
&["--show-stats", "--stats-format", "json"],
)
.and_then(|text| stats::parse(&text).map(|snapshot| (text, snapshot)));
let mut state = self.lock();
state.client_version = version;
match read {
Ok((text, snapshot)) => {
let live = 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);
state.live = None;
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()
);
}
}
}
}
/// 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();
Ok(())
}
/// Asks sccache for its counters every [`POLL`] and prunes the history once a day, until
/// the process ends.
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;
eprintln!(
"sccache-dash: cannot prune {}: {e}",
self.cfg.history.display()
);
}
Err(_) => {}
}
}
thread::sleep(POLL);
});
}
}
/// 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)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| match e.kind() {
ErrorKind::NotFound => format!(
"`{} {}`: command not found",
sccache.to_string_lossy(),
args.join(" ")
),
_ => format!("`{} {}`: {e}", sccache.to_string_lossy(), args.join(" ")),
})?;
let named = format!("`{} {}`", sccache.to_string_lossy(), args.join(" "));
match child.wait_timeout(COMMAND_TIMEOUT) {
Ok(Some(status)) if status.success() => {}
Ok(Some(status)) => return Err(format!("{named} exited with {status}")),
Ok(None) => {
let _ = child.kill();
let _ = child.wait();
return Err(format!(
"{named} did not answer within {} seconds",
COMMAND_TIMEOUT.as_secs()
));
}
Err(e) => return Err(format!("{named}: {e}")),
}
let mut text = String::new();
if let Some(mut out) = child.stdout.take() {
out.read_to_string(&mut text)
.map_err(|e| format!("{named}: {e}"))?;
}
Ok(text)
}
+184
View File
@@ -0,0 +1,184 @@
//! The saved history: one compact JSON line per reading, oldest first.
use std::fs::OpenOptions;
use std::io::{self, Write};
use std::path::Path;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::stats::Counters;
/// Readings older than this are deleted.
pub const KEEP_DAYS: i64 = 30;
/// 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,
}
/// 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;
};
for (key, default) in defaults {
match value.get_mut(key) {
None => {
value.insert(key.clone(), default.clone());
}
Some(found) => fill_in(found, default),
}
}
}
/// 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)?;
}
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);
}
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()
},
..Counters::default()
},
}
}
#[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"
);
}
#[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"
);
}
}
+235
View File
@@ -0,0 +1,235 @@
//! The HTTP side: three routes and the page's files, on 127.0.0.1 only.
use std::io::Cursor;
use std::net::SocketAddr;
use std::sync::Arc;
use std::thread;
use include_dir::{include_dir, Dir};
use sccache_dash_api::Range;
use serde_json::Value;
use tiny_http::{Header, Request, Response, Server};
use crate::app::App;
use crate::pretty;
/// The page as `trunk build` wrote it to crates/ui/dist, or a placeholder saying it is not built
/// (the build script names the folder in `DASH_SITE`).
static SITE: Dir<'_> = include_dir!("$DASH_SITE");
type Reply = Response<Cursor<Vec<u8>>>;
/// Serves until the process ends.
pub fn serve(app: Arc<App>, port: u16) -> Result<(), String> {
answer(listen(port)?, app);
Ok(())
}
/// Binds 127.0.0.1 and nothing else; port 0 picks a free one.
pub fn listen(port: u16) -> Result<Server, String> {
Server::http(SocketAddr::from(([127, 0, 0, 1], port)))
.map_err(|e| format!("cannot listen on 127.0.0.1:{port}: {e}"))
}
/// The port a listening server answers on.
pub fn port_of(server: &Server) -> u16 {
server.server_addr().to_ip().map_or(0, |a| a.port())
}
/// Answers requests until the process ends.
pub fn answer(server: Server, app: Arc<App>) {
let port = port_of(&server);
for mut request in server.incoming_requests() {
let app = Arc::clone(&app);
thread::spawn(move || {
let response = handle(&app, port, &mut request);
let _ = request.respond(response);
});
}
}
fn handle(app: &App, port: u16, req: &mut Request) -> Reply {
let url = req.url();
let (path, query) = url.split_once('?').unwrap_or((url, ""));
match (req.method().as_str(), path) {
("GET", "/api/view") => match range_of(query) {
Some(range) => reply(
200,
"application/json",
serde_json::to_vec(&app.view(range)).unwrap_or_default(),
)
.with_header(header("Cache-Control", "no-store")),
None => text(400, "unknown range: use 1h, 24h, 7d, 30d or reset"),
},
("GET" | "HEAD", "/api/export") => export(app),
("POST", "/api/zero") => zero(app, port, req),
(_, "/api/zero") => text(405, "use POST"),
("GET" | "HEAD", _) => site_file(path),
_ => text(404, "not found"),
}
}
/// `range=24h` in the query string.
fn range_of(query: &str) -> Option<Range> {
let value = query.split('&').find_map(|p| p.strip_prefix("range="))?;
serde_json::from_value(Value::String(value.to_owned())).ok()
}
/// sccache's output exactly as it printed it, as a download.
fn export(app: &App) -> Reply {
let state = app.lock();
match &state.live {
Some(live) => reply(200, "application/json", live.raw_text.clone().into_bytes())
.with_header(header(
"Content-Disposition",
&format!(
"attachment; filename=\"sccache-stats-{}.json\"",
pretty::stamp(live.at)
),
)),
None => text(
502,
&format!(
"sccache did not answer: {}",
state.error.as_deref().unwrap_or("no reading yet")
),
),
}
}
/// Runs `sccache --zero-stats`. Only this machine's own dashboard may ask for that.
fn zero(app: &App, port: u16, req: &Request) -> Reply {
if !from_own_page(req, port) {
return text(
403,
"refused: only the dashboard's own page, on this machine, may zero the stats",
);
}
match app.zero() {
Ok(()) => text(
200,
"sccache's counters were zeroed; the saved history is kept",
),
Err(e) => text(502, &format!("could not zero the stats: {e}")),
}
}
/// Whether a request comes from the dashboard itself: its `Host` is localhost, and when a web
/// page sent it (it carries an `Origin`) that page is this server. A page anywhere else must
/// not be able to zero the stats, and neither may a host name that merely resolves here.
fn from_own_page(req: &Request, port: u16) -> bool {
let header = |name: &'static str| {
req.headers()
.iter()
.find(|h| h.field.equiv(name))
.map(|h| h.value.as_str())
};
// `name` or `name:port`, with a port made of digits and nothing else.
let host_is_local = |host: &str| {
let mut parts = host.splitn(2, ':');
let name = parts.next().unwrap_or_default();
let port = parts.next().unwrap_or("");
(name.eq_ignore_ascii_case("127.0.0.1") || name.eq_ignore_ascii_case("localhost"))
&& port.bytes().all(|b| b.is_ascii_digit())
};
let own_origins = [
format!("http://127.0.0.1:{port}"),
format!("http://localhost:{port}"),
];
header("Host").is_some_and(host_is_local)
&& header("Origin").is_none_or(|origin| own_origins.iter().any(|own| own == origin))
}
/// A file of the page; `/` is its index.
fn site_file(path: &str) -> Reply {
let name = path.trim_start_matches('/');
let name = if name.is_empty() { "index.html" } else { name };
match SITE.get_file(name) {
Some(file) => reply(200, content_type(name), file.contents().to_vec()),
None => text(404, "not found"),
}
}
/// Content types by file extension, as the page's own files need them.
fn content_type(path: &str) -> &'static str {
match path.rsplit_once('.').map(|(_, ext)| ext) {
Some("html") => "text/html; charset=utf-8",
Some("js" | "mjs") => "text/javascript; charset=utf-8",
Some("wasm") => "application/wasm",
Some("css") => "text/css; charset=utf-8",
Some("json" | "map") => "application/json",
Some("svg") => "image/svg+xml",
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
Some("ico") => "image/x-icon",
Some("woff") => "font/woff",
Some("woff2") => "font/woff2",
Some("ttf") => "font/ttf",
Some("otf") => "font/otf",
Some("txt" | "md") => "text/plain; charset=utf-8",
_ => "application/octet-stream",
}
}
fn header(name: &'static str, value: &str) -> Header {
Header::from_bytes(name.as_bytes(), value.as_bytes()).expect("a header made of plain ASCII")
}
fn reply(code: u16, content_type: &str, body: Vec<u8>) -> Reply {
Response::from_data(body)
.with_status_code(code)
.with_header(header("Content-Type", content_type))
}
fn text(code: u16, body: &str) -> Reply {
reply(code, "text/plain; charset=utf-8", body.as_bytes().to_vec())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_page_or_its_placeholder_is_in_the_binary() {
assert!(
SITE.get_file("index.html").is_some(),
"`/` must answer with a page"
);
assert!(
SITE.get_file("../Cargo.toml").is_none(),
"nothing outside the page is served"
);
assert!(SITE.get_file("no-such-file").is_none());
}
#[test]
fn content_types_are_what_browsers_need() {
assert_eq!(content_type("index.html"), "text/html; charset=utf-8");
assert_eq!(
content_type("app-a1b2c3.js"),
"text/javascript; charset=utf-8"
);
assert_eq!(content_type("app-a1b2c3.wasm"), "application/wasm");
assert_eq!(content_type("app.css"), "text/css; charset=utf-8");
assert_eq!(content_type("icons/sccache.svg"), "image/svg+xml");
assert_eq!(content_type("data"), "application/octet-stream");
}
#[test]
fn the_range_comes_from_the_query_string() {
for (query, expected) in [
("range=1h", Some(Range::Hour)),
("range=24h", Some(Range::Day)),
("range=7d", Some(Range::Week)),
("range=30d", Some(Range::Month)),
("range=reset", Some(Range::SinceReset)),
("other=1&range=24h", Some(Range::Day)),
("", None),
("range=all", None),
] {
assert_eq!(range_of(query), expected, "{query:?}");
}
}
}
+10
View File
@@ -0,0 +1,10 @@
//! The server half of sccache-dash: it asks sccache for its counters, keeps their history and
//! serves the page that draws them.
pub mod app;
pub mod history;
pub mod http;
pub mod pretty;
pub mod stats;
pub mod systemd;
pub mod view;
+163
View File
@@ -0,0 +1,163 @@
//! `sccache-dash`: serves the dashboard, or installs itself as a user service.
use std::process::{Command as Process, Stdio};
use std::sync::Arc;
use sccache_dash::app::{unix_now, App, Config};
use sccache_dash::{http, systemd};
const USAGE: &str = "\
sccache-dash [--port N] [--no-open] serve the dashboard on http://127.0.0.1:8226 and open it
sccache-dash install start it at login, as a systemd user service
sccache-dash uninstall remove that service again";
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if let Err(e) = run(&args) {
eprintln!("sccache-dash: {e}");
std::process::exit(1);
}
}
fn run(args: &[String]) -> Result<(), String> {
match parse(args)? {
Command::Help => println!("{USAGE}"),
Command::Install => systemd::install()?,
Command::Uninstall => systemd::uninstall()?,
Command::Serve { port, open } => serve(port, open)?,
}
Ok(())
}
/// What the command line asks for.
#[derive(Debug)]
enum Command {
Serve { port: u16, open: bool },
Install,
Uninstall,
Help,
}
fn parse(args: &[String]) -> Result<Command, String> {
let mut serve = Command::Serve {
port: sccache_dash_api::DEFAULT_PORT,
open: true,
};
let mut i = 0;
while let Some(arg) = args.get(i) {
i += 1;
match arg.as_str() {
"--no-open" => {
if let Command::Serve { open, .. } = &mut serve {
*open = false;
}
}
"--help" | "-h" => return Ok(Command::Help),
"install" => return Ok(Command::Install),
"uninstall" => return Ok(Command::Uninstall),
a if a == "--port" || a.starts_with("--port=") => {
let value = match a.strip_prefix("--port=") {
Some(value) => value.to_owned(),
None => {
i += 1;
args.get(i - 1)
.ok_or("--port needs a number, as in --port 8226")?
.clone()
}
};
let port = value
.parse()
.map_err(|_| format!("`{value}` is not a port number"))?;
if let Command::Serve { port: p, .. } = &mut serve {
*p = port;
}
}
a => return Err(format!("unknown argument `{a}`\n\n{USAGE}")),
}
}
Ok(serve)
}
fn serve(port: u16, open: bool) -> Result<(), String> {
let app = Arc::new(App::new(Config::from_env()?, unix_now())?);
let server = http::listen(port)?;
let port = http::port_of(&server);
let url = format!("http://127.0.0.1:{port}");
println!(
"sccache-dash: serving {url}, history in {}",
app.cfg.history.display()
);
app.clone().keep_updated();
if open {
// Left to finish on its own: a browser that will not open is not worth stopping for.
let browser = Process::new("xdg-open")
.arg(&url)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn();
if let Ok(mut browser) = browser {
std::thread::spawn(move || {
let _ = browser.wait();
});
}
}
http::answer(server, app);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_args(args: &[&str]) -> Result<Command, String> {
parse(&args.iter().map(|a| a.to_string()).collect::<Vec<_>>())
}
#[test]
fn the_command_line() {
assert!(matches!(
parse_args(&[]),
Ok(Command::Serve {
port: 8226,
open: true
})
));
assert!(matches!(
parse_args(&["--port", "18226"]),
Ok(Command::Serve {
port: 18226,
open: true
})
));
assert!(matches!(
parse_args(&["--port=9000", "--no-open"]),
Ok(Command::Serve {
port: 9000,
open: false
})
));
assert!(matches!(
parse_args(&["--no-open", "--port", "1"]),
Ok(Command::Serve {
port: 1,
open: false
})
));
assert!(matches!(parse_args(&["install"]), Ok(Command::Install)));
assert!(matches!(parse_args(&["uninstall"]), Ok(Command::Uninstall)));
assert!(matches!(parse_args(&["--help"]), Ok(Command::Help)));
assert!(parse_args(&["18226"])
.unwrap_err()
.starts_with("unknown argument `18226`"));
assert!(parse_args(&["--port"])
.unwrap_err()
.contains("--port needs a number"));
assert!(parse_args(&["--port", "x"])
.unwrap_err()
.contains("`x` is not a port number"));
assert!(parse_args(&["--port", "70000"])
.unwrap_err()
.contains("is not a port number"));
}
}
+135
View File
@@ -0,0 +1,135 @@
//! How numbers, times and sizes are written for people.
/// `2815` as "2,815".
pub fn thousands(n: u64) -> String {
let digits = n.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, c) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push(',');
}
out.push(c);
}
out
}
/// A share as a percentage with one decimal, dropping a needless ".0": `0.076` as "7.6", `1.0` as "100".
pub fn pct(share: f64) -> String {
let s = format!("{:.1}", share * 100.0);
s.strip_suffix(".0").unwrap_or(&s).to_owned()
}
/// Seconds rounded down to minutes, the way the summary says them: "3h 05m", "48m", "<1m".
pub fn hours_and_minutes(secs: f64) -> String {
let mins = (secs / 60.0).floor() as u64;
match mins {
0 => "<1m".to_owned(),
1..=59 => format!("{mins}m"),
_ => format!("{}h {:02}m", mins / 60, mins % 60),
}
}
/// A short length of time: "210 ms", "0.9 s", "7.8 s", "20 min".
pub fn short(secs: f64) -> String {
if secs < 1.0 {
format!("{:.0} ms", secs * 1000.0)
} else if secs < 600.0 {
let s = format!("{secs:.1}");
format!("{} s", s.strip_suffix(".0").unwrap_or(&s))
} else {
format!("{:.0} min", secs / 60.0)
}
}
/// Two sizes as one phrase: sccache's 10G limit reads "10.0 of 10.0 GB", and sizes in different
/// units read "900.0 MB of 10.0 GB".
pub fn bytes_of(size: u64, max: u64) -> String {
let (a, au) = amount(size);
let (b, bu) = amount(max);
if au == bu {
format!("{a} of {b} {au}")
} else {
format!("{a} {au} of {b} {bu}")
}
}
fn amount(b: u64) -> (String, &'static str) {
const K: f64 = 1024.0;
let b = b as f64;
if b >= K * K * K * K {
(format!("{:.1}", b / (K * K * K * K)), "TB")
} else if b >= K * K * K {
(format!("{:.1}", b / (K * K * K)), "GB")
} else if b >= K * K {
(format!("{:.1}", b / (K * K)), "MB")
} else {
(format!("{b:.0}"), "KB")
}
}
/// Unix seconds as a file-name-friendly UTC time: `0` as "19700101-000000".
pub fn stamp(secs: i64) -> String {
let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
// Days since 1970-01-01 to a date, by Howard Hinnant's algorithm.
let z = days + 719_468;
let (era, doe) = (z.div_euclid(146_097), z.rem_euclid(146_097));
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!(
"{y:04}{m:02}{d:02}-{:02}{:02}{:02}",
rem / 3600,
rem % 3600 / 60,
rem % 60
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn numbers_as_written() {
assert_eq!(thousands(0), "0");
assert_eq!(thousands(2815), "2,815");
assert_eq!(thousands(1_234_567), "1,234,567");
assert_eq!(pct(0.076), "7.6");
assert_eq!(pct(0.5018), "50.2");
assert_eq!(pct(1.0), "100");
}
#[test]
fn times_as_written() {
assert_eq!(hours_and_minutes(11100.0), "3h 05m");
assert_eq!(hours_and_minutes(48.4 * 60.0), "48m");
assert_eq!(hours_and_minutes(20.0), "<1m");
assert_eq!(short(0.21), "210 ms");
assert_eq!(short(0.9), "900 ms");
assert_eq!(short(10.0), "10 s");
assert_eq!(short(60.0), "60 s");
assert_eq!(short(1200.0), "20 min");
}
#[test]
fn sizes_and_dates_as_written() {
assert_eq!(
bytes_of(10 * 1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
"10.0 of 10.0 GB"
);
assert_eq!(bytes_of(1024 * 1024, 1024 * 1024), "1.0 of 1.0 MB");
assert_eq!(bytes_of(10_726_353_131, 10_737_418_240), "10.0 of 10.0 GB");
assert_eq!(
bytes_of(9 * 1024 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
"9.0 of 10.0 GB"
);
assert_eq!(
bytes_of(900 * 1024 * 1024, 10 * 1024 * 1024 * 1024),
"900.0 MB of 10.0 GB"
);
assert_eq!(stamp(0), "19700101-000000");
assert_eq!(stamp(1_764_000_000), "20251124-160000"); // what `date -u -d @1764000000` says
}
}
+579
View File
@@ -0,0 +1,579 @@
//! sccache's counters: reading them out of its JSON and telling two readings apart.
use std::collections::BTreeMap;
use sccache_dash_api::{Extra, Totals};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::pretty;
/// Positions in [`Counters::ns`].
pub const HIT_READ: usize = 0;
pub const CACHE_WRITE: usize = 1;
pub const COMPILE: usize = 2;
/// sccache's counters at one moment. Each only grows, until sccache resets them.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Counters {
#[serde(default)]
pub totals: Totals,
/// Compiler runs: misses, plus compiles that could not be cached or failed.
#[serde(default)]
pub compilations: u64,
/// Nanoseconds spent reading hits, writing cache entries and running compilers.
#[serde(default)]
pub ns: [u64; 3],
/// (language, [hits, misses, errors]) by name, for languages that have counted something.
#[serde(default)]
pub langs: Vec<(String, [u64; 3])>,
/// (reason, count) by name, for reasons that have counted something.
#[serde(default)]
pub not_cached: Vec<(String, u64)>,
}
impl Counters {
/// What happened between `older` and `self`, and whether sccache reset its counters in between.
///
/// A counter that went down can only mean sccache zeroed its counters (a new server, or
/// `--zero-stats`), and it zeroes all of them at once: every difference is then the new value.
pub fn since(&self, older: &Counters) -> (Counters, bool) {
let mut reset = false;
let mut sub = |a: u64, b: u64| {
if b < a {
reset = true;
}
b.saturating_sub(a)
};
let (a, b) = (&older.totals, &self.totals);
let totals = Totals {
requests: sub(a.requests, b.requests),
executed: sub(a.executed, b.executed),
hits: sub(a.hits, b.hits),
misses: sub(a.misses, b.misses),
not_cacheable: sub(a.not_cacheable, b.not_cacheable),
unsupported_compiler: sub(a.unsupported_compiler, b.unsupported_compiler),
not_compile: sub(a.not_compile, b.not_compile),
timeouts: sub(a.timeouts, b.timeouts),
read_errors: sub(a.read_errors, b.read_errors),
write_errors: sub(a.write_errors, b.write_errors),
other_errors: sub(a.other_errors, b.other_errors),
compile_fails: sub(a.compile_fails, b.compile_fails),
forced_recaches: sub(a.forced_recaches, b.forced_recaches),
cache_writes: sub(a.cache_writes, b.cache_writes),
};
let compilations = sub(older.compilations, self.compilations);
let mut ns = [0; 3];
for (d, (a, b)) in ns.iter_mut().zip(older.ns.iter().zip(self.ns.iter())) {
*d = sub(*a, *b);
}
let langs = self
.langs
.iter()
.filter_map(|(name, v)| {
let o = older
.langs
.iter()
.find(|(k, _)| k == name)
.map_or([0; 3], |(_, o)| *o);
let mut d = [0; 3];
for (d, (a, b)) in d.iter_mut().zip(o.iter().zip(v.iter())) {
*d = sub(*a, *b);
}
(d != [0; 3]).then(|| (name.clone(), d))
})
.collect();
let not_cached = self
.not_cached
.iter()
.filter_map(|(name, v)| {
let o = older
.not_cached
.iter()
.find(|(k, _)| k == name)
.map_or(0, |(_, o)| *o);
let d = sub(o, *v);
(d > 0).then(|| (name.clone(), d))
})
.collect();
let diff = Counters {
totals,
compilations,
ns,
langs,
not_cached,
};
(if reset { self.clone() } else { diff }, reset)
}
/// Adds another set of counters into this one.
pub fn add(&mut self, other: &Counters) {
macro_rules! sum {
($($f:ident),* $(,)?) => { $( self.totals.$f += other.totals.$f; )* };
}
sum!(
requests,
executed,
hits,
misses,
not_cacheable,
unsupported_compiler,
not_compile,
timeouts,
read_errors,
write_errors,
other_errors,
compile_fails,
forced_recaches,
cache_writes,
);
self.compilations += other.compilations;
for (n, x) in self.ns.iter_mut().zip(other.ns.iter()) {
*n += x;
}
for (name, v) in &other.langs {
match self.langs.iter_mut().find(|(k, _)| k == name) {
Some((_, have)) => {
for (h, x) in have.iter_mut().zip(v.iter()) {
*h += x;
}
}
None => self.langs.push((name.clone(), *v)),
}
}
for (name, v) in &other.not_cached {
match self.not_cached.iter_mut().find(|(k, _)| k == name) {
Some((_, have)) => *have += v,
None => self.not_cached.push((name.clone(), *v)),
}
}
}
}
/// One level of a multi-level cache, as sccache 0.18 reports it in `stats.multi_level`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Level {
pub name: String,
pub location: String,
pub hits: u64,
pub misses: u64,
pub writes: u64,
pub write_failures: u64,
pub backfills_from: u64,
pub backfills_to: u64,
pub hit_ns: u64,
pub write_ns: u64,
}
/// What one run of `sccache --show-stats --stats-format json` said.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Snapshot {
pub counters: Counters,
pub version: Option<String>,
pub cache_location: Option<String>,
pub cache_size: Option<u64>,
pub max_cache_size: Option<u64>,
pub multi_level: Vec<Level>,
/// (server, compiles) by server, sorted by server.
pub dist_compiles: Vec<(String, u64)>,
pub dist_errors: u64,
}
/// Reads sccache's JSON. Unknown fields are ignored and missing ones read as zero, so a new
/// sccache cannot break this; only output that is not JSON with a `stats` object is an error.
pub fn parse(text: &str) -> Result<Snapshot, String> {
let root: Value =
serde_json::from_str(text).map_err(|e| format!("sccache's output is not JSON ({e})"))?;
let stats = root
.get("stats")
.ok_or("sccache's output has no \"stats\" object")?;
let (hits, misses, errors) = (
counts(stats, "cache_hits"),
counts(stats, "cache_misses"),
counts(stats, "cache_errors"),
);
let mut by_lang: BTreeMap<&str, [u64; 3]> = BTreeMap::new();
for (map, i) in [(&hits, 0), (&misses, 1), (&errors, 2)] {
for (name, n) in map {
by_lang.entry(name.as_str()).or_default()[i] = *n;
}
}
let n = |field: &str| num(stats.get(field));
let totals = Totals {
requests: n("compile_requests"),
executed: n("requests_executed"),
hits: hits.values().sum(),
misses: misses.values().sum(),
not_cacheable: n("requests_not_cacheable"),
unsupported_compiler: n("requests_unsupported_compiler"),
not_compile: n("requests_not_compile"),
timeouts: n("cache_timeouts"),
read_errors: n("cache_read_errors"),
write_errors: n("cache_write_errors"),
other_errors: errors.values().sum(),
compile_fails: n("compile_fails"),
forced_recaches: n("forced_recaches"),
cache_writes: n("cache_writes"),
};
let counters = Counters {
totals,
compilations: n("compilations"),
ns: [
nanos(stats.get("cache_read_hit_duration")),
nanos(stats.get("cache_write_duration")),
nanos(stats.get("compiler_write_duration")),
],
langs: by_lang
.into_iter()
.map(|(name, v)| (name.to_owned(), v))
.collect(),
not_cached: pairs(stats.get("not_cached")).into_iter().collect(),
};
let text = |field: &str| root.get(field).and_then(Value::as_str).map(str::to_owned);
let multi_level = stats
.get("multi_level")
.and_then(Value::as_array)
.map(|levels| {
levels
.iter()
.filter_map(|l| {
let s = |f: &str| Some(l.get(f)?.as_str()?.to_owned());
Some(Level {
name: s("name")?,
location: s("location")?,
hits: num(l.get("hits")),
misses: num(l.get("misses")),
writes: num(l.get("writes")),
write_failures: num(l.get("write_failures")),
backfills_from: num(l.get("backfills_from")),
backfills_to: num(l.get("backfills_to")),
hit_ns: nanos(l.get("hit_duration")),
write_ns: nanos(l.get("write_duration")),
})
})
.collect()
})
.unwrap_or_default();
Ok(Snapshot {
counters,
version: text("version"),
cache_location: text("cache_location"),
cache_size: root.get("cache_size").and_then(Value::as_u64),
max_cache_size: root.get("max_cache_size").and_then(Value::as_u64),
multi_level,
dist_compiles: pairs(stats.get("dist_compiles"))
.into_iter()
.filter(|(_, n)| *n > 0)
.collect(),
dist_errors: n("dist_errors"),
})
}
/// A number as sccache writes it; anything else reads as zero.
fn num(v: Option<&Value>) -> u64 {
v.and_then(Value::as_u64).unwrap_or(0)
}
/// `{"secs": 1, "nanos": 2}` as nanoseconds.
fn nanos(v: Option<&Value>) -> u64 {
let o = v.and_then(Value::as_object);
let get = |k: &str| {
o.and_then(|o| o.get(k))
.and_then(Value::as_u64)
.unwrap_or(0)
};
get("secs") * 1_000_000_000 + get("nanos")
}
/// A JSON object of counts as a sorted map.
fn pairs(v: Option<&Value>) -> BTreeMap<String, u64> {
v.and_then(Value::as_object)
.map(|o| {
o.iter()
.filter_map(|(k, v)| Some((k.clone(), v.as_u64()?)))
.collect()
})
.unwrap_or_default()
}
/// `{"counts": {...}}` as a sorted map.
fn counts(parent: &Value, field: &str) -> BTreeMap<String, u64> {
pairs(parent.get(field).and_then(|f| f.get("counts")))
}
/// The tables for what sccache reports beyond the usual counters, empty when it reports nothing.
pub fn extras(s: &Snapshot) -> Vec<Extra> {
let mut out = Vec::new();
if !s.multi_level.is_empty() {
let rows = s
.multi_level
.iter()
.map(|l| {
let per = |total: u64, n: u64| (n > 0).then(|| total as f64 / n as f64 / 1e9);
(
format!("{} \u{2014} {}", l.name, l.location),
format!(
"{} hits \u{b7} {} misses \u{b7} {} writes, {} failed \u{b7} backfilled {} in, {} out \u{b7} avg hit read {} \u{b7} avg write {}",
pretty::thousands(l.hits),
pretty::thousands(l.misses),
pretty::thousands(l.writes),
pretty::thousands(l.write_failures),
pretty::thousands(l.backfills_from),
pretty::thousands(l.backfills_to),
per(l.hit_ns, l.hits).map_or_else(|| "\u{2014}".to_owned(), pretty::short),
per(l.write_ns, l.writes).map_or_else(|| "\u{2014}".to_owned(), pretty::short),
),
)
})
.collect();
out.push(Extra {
title: "Multi-level cache".to_owned(),
rows,
});
}
if !s.dist_compiles.is_empty() || s.dist_errors > 0 {
let mut rows: Vec<_> = s
.dist_compiles
.iter()
.map(|(server, n)| (server.clone(), pretty::thousands(*n)))
.collect();
rows.push((
"Errors (re-run locally)".to_owned(),
pretty::thousands(s.dist_errors),
));
out.push(Extra {
title: "Distributed compiles".to_owned(),
rows,
});
}
out
}
#[cfg(test)]
mod tests {
use super::*;
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
const MULTILEVEL: &str = include_str!("../../../fixtures/sample-multilevel.json");
const DIST: &str = include_str!("../../../fixtures/sample-dist.json");
fn counters(requests: u64, hits: u64, misses: u64) -> Counters {
Counters {
totals: Totals {
requests,
hits,
misses,
..Totals::default()
},
compilations: misses,
langs: vec![("Rust".to_owned(), [hits, misses, 0])],
..Counters::default()
}
}
#[test]
fn live_output_is_read_as_it_is() {
let s = parse(LIVE).unwrap();
assert_eq!(
s.counters.totals,
Totals {
requests: 7351,
executed: 6495,
hits: 3197,
misses: 3256,
not_cacheable: 829,
not_compile: 27,
other_errors: 0,
compile_fails: 39,
cache_writes: 3256,
..Totals::default()
}
);
assert_eq!(s.counters.compilations, 3256);
assert_eq!(
s.counters.ns,
[2_190_691_578, 8_758_680_079, 25_343_119_040_435]
);
assert_eq!(
s.counters.langs,
vec![
("Assembler".to_owned(), [886, 0, 0]),
("C/C++".to_owned(), [2082, 0, 0]),
("Rust".to_owned(), [229, 3256, 0]),
]
);
assert_eq!(s.counters.not_cached.len(), 7);
assert_eq!(s.counters.not_cached[0], ("-".to_owned(), 35));
assert_eq!(s.version.as_deref(), Some("0.18.0"));
assert_eq!(
s.cache_location.as_deref(),
Some("Local disk: \"/home/swaits/.cache/sccache\"")
);
assert_eq!(
(s.cache_size, s.max_cache_size),
(Some(10_726_353_131), Some(10_737_418_240))
);
assert!(s.multi_level.is_empty() && s.dist_compiles.is_empty() && s.dist_errors == 0);
assert!(
extras(&s).is_empty(),
"nothing extra is reported, so there are no extra tables"
);
}
#[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
);
}
#[test]
fn unknown_and_missing_fields_do_not_break_it() {
let s = parse(
"{\"stats\":{\"compile_requests\":\"many\",\"cache_hits\":{\"counts\":{\"Rust\":-1}},\"new_field\":1},\"extra\":2}",
)
.unwrap();
assert_eq!(s.counters, Counters::default());
assert_eq!(parse("{\"stats\":{}}").unwrap(), Snapshot::default());
assert_eq!(
parse("{\"stats\":null,\"version\":\"1.0\"}")
.unwrap()
.version
.as_deref(),
Some("1.0")
);
assert!(parse("not json").is_err());
assert!(parse("{\"error\":\"no server\"}").is_err());
}
#[test]
fn differences_are_what_grew() {
let (older, newer) = (counters(100, 60, 40), counters(130, 80, 50));
let (diff, reset) = newer.since(&older);
assert_eq!(diff.totals.requests, 30);
assert_eq!(diff.totals.hits, 20);
assert_eq!(diff.totals.misses, 10);
assert_eq!(diff.langs, vec![("Rust".to_owned(), [20, 10, 0])]);
assert!(!reset);
let (same, _) = newer.since(&newer);
assert!(same.totals == Totals::default() && same.langs.is_empty());
}
#[test]
fn a_counter_going_down_zeroes_the_whole_reading() {
let mut older = counters(100, 60, 40);
older.not_cached.push(("crate-type".to_owned(), 9));
older.ns[COMPILE] = 400;
let mut newer = counters(130, 5, 0);
newer.not_cached.push(("crate-type".to_owned(), 2));
newer.not_cached.push(("-o".to_owned(), 1));
newer.ns[COMPILE] = 7;
let (diff, reset) = newer.since(&older);
assert!(
reset,
"hits went down, so the counters were zeroed in between"
);
assert_eq!(
diff, newer,
"every difference is the new value, even where the counter grew"
);
}
#[test]
fn sums_merge_languages_and_reasons() {
let mut a = counters(10, 4, 6);
a.not_cached.push(("crate-type".to_owned(), 1));
let mut b = counters(1, 1, 0);
b.compilations = 0;
b.langs = vec![
("C/C++".to_owned(), [1, 0, 0]),
("Rust".to_owned(), [0, 0, 2]),
];
b.not_cached.push(("crate-type".to_owned(), 2));
b.not_cached.push(("incremental".to_owned(), 1));
a.add(&b);
assert_eq!(a.totals.requests, 11);
assert_eq!(a.totals.hits, 5);
assert_eq!(a.compilations, 6);
assert_eq!(
a.langs,
vec![
("Rust".to_owned(), [4, 6, 2]),
("C/C++".to_owned(), [1, 0, 0])
]
);
assert_eq!(
a.not_cached,
vec![("crate-type".to_owned(), 3), ("incremental".to_owned(), 1)]
);
}
#[test]
fn multilevel_sample_becomes_a_table() {
let s = parse(MULTILEVEL).unwrap();
assert_eq!(s.multi_level.len(), 2);
assert_eq!(s.multi_level[1].name, "L1 (s3)");
assert_eq!(s.multi_level[0].hit_ns, 1_500_000_000);
assert_eq!(s.multi_level[1].write_ns, 36_500_000_000);
let extras = extras(&s);
assert_eq!(extras.len(), 1);
assert_eq!(extras[0].title, "Multi-level cache");
assert_eq!(extras[0].rows.len(), 2);
assert_eq!(
extras[0].rows[0].0,
"L0 (disk) \u{2014} Local disk: \"/home/me/.cache/sccache\""
);
assert_eq!(
extras[0].rows[0].1,
"1,500 hits \u{b7} 1,000 misses \u{b7} 1,400 writes, 2 failed \u{b7} backfilled 300 in, 0 out \u{b7} avg hit read 1 ms \u{b7} avg write 2 ms"
);
}
#[test]
fn dist_sample_becomes_a_table() {
let s = parse(DIST).unwrap();
assert_eq!(
s.dist_compiles,
vec![
("10.0.0.11:4226".to_owned(), 402),
("10.0.0.12:4226".to_owned(), 379),
("buildbox.local:4228".to_owned(), 9),
]
);
assert_eq!(s.dist_errors, 7);
let extras = extras(&s);
assert_eq!(extras.len(), 1);
assert_eq!(extras[0].title, "Distributed compiles");
assert_eq!(
extras[0].rows[2],
("buildbox.local:4228".to_owned(), "9".to_owned())
);
assert_eq!(
extras[0].rows[3],
("Errors (re-run locally)".to_owned(), "7".to_owned())
);
}
#[test]
fn only_dist_errors_still_makes_a_table() {
let mut s = parse(DIST).unwrap();
s.dist_compiles.clear();
assert_eq!(
extras(&s)[0].rows,
vec![("Errors (re-run locally)".to_owned(), "7".to_owned())]
);
}
}
+130
View File
@@ -0,0 +1,130 @@
//! Living in systemd: the unit file, and installing or removing it.
use std::path::PathBuf;
use std::process::Command;
use sccache_dash_api::DEFAULT_PORT;
pub const UNIT: &str = "sccache-dash.service";
/// The unit file that runs this program from login on, without opening a browser.
pub fn unit_file(exe: &str, path: &str) -> String {
format!(
"[Unit]\n\
Description=sccache-dash, a dashboard for sccache's cache at http://127.0.0.1:{DEFAULT_PORT}\n\
\n\
[Service]\n\
ExecStart={} --no-open\n\
Environment={}\n\
Restart=on-failure\n\
RestartSec=5\n\
\n\
[Install]\n\
WantedBy=default.target\n",
quote(exe),
quote(&format!("PATH={path}")),
)
}
/// Quotes a value the way systemd unit files read it; `%` would otherwise start a specifier.
fn quote(value: &str) -> String {
format!(
"\"{}\"",
value
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('%', "%%")
)
}
fn unit_path() -> Result<PathBuf, String> {
let config = dirs::config_dir()
.ok_or("cannot find the config directory ($XDG_CONFIG_HOME, or ~/.config)")?;
Ok(config.join("systemd").join("user").join(UNIT))
}
fn systemctl(args: &[&str]) -> Result<(), String> {
let output = Command::new("systemctl")
.args(args)
.output()
.map_err(|e| format!("cannot run systemctl: {e}"))?;
if output.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned();
Err(format!(
"systemctl {} failed: {}",
args.join(" "),
[stdout, stderr].join(" ").trim()
))
}
/// Writes the unit file for the program as it is running right now, then starts it.
pub fn install() -> Result<(), String> {
let exe =
std::env::current_exe().map_err(|e| format!("cannot find where this program is: {e}"))?;
let path = std::env::var("PATH").unwrap_or_default();
let unit = unit_path()?;
if let Some(dir) = unit.parent() {
std::fs::create_dir_all(dir)
.map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
}
std::fs::write(&unit, unit_file(&exe.to_string_lossy(), &path))
.map_err(|e| format!("cannot write {}: {e}", unit.display()))?;
systemctl(&["--user", "daemon-reload"])?;
systemctl(&["--user", "enable", "--now", UNIT])?;
println!(
"Installed {}. The dashboard is at http://127.0.0.1:{DEFAULT_PORT}",
unit.display()
);
Ok(())
}
/// Stops the service and deletes the unit file.
pub fn uninstall() -> Result<(), String> {
let unit = unit_path()?;
if unit.exists() {
systemctl(&["--user", "disable", "--now", UNIT])?;
std::fs::remove_file(&unit)
.map_err(|e| format!("cannot remove {}: {e}", unit.display()))?;
} else {
println!("{} is not installed; nothing to remove.", unit.display());
}
systemctl(&["--user", "daemon-reload"])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_unit_runs_this_binary_without_a_browser_and_with_the_shell_s_path() {
let unit = unit_file("/home/me/bin/sccache-dash", "/usr/bin:/home/me/.cargo/bin");
assert_eq!(
unit,
"[Unit]\n\
Description=sccache-dash, a dashboard for sccache's cache at http://127.0.0.1:8226\n\
\n\
[Service]\n\
ExecStart=\"/home/me/bin/sccache-dash\" --no-open\n\
Environment=\"PATH=/usr/bin:/home/me/.cargo/bin\"\n\
Restart=on-failure\n\
RestartSec=5\n\
\n\
[Install]\n\
WantedBy=default.target\n"
);
assert!(unit_file("/a b/sccache-dash", "/x")
.contains("ExecStart=\"/a b/sccache-dash\" --no-open\n"));
assert!(
unit_file("/x", "/a%b\"c").contains("Environment=\"PATH=/a%%b\\\"c\"\n"),
"% and quotes cannot change what systemd reads"
);
assert!(
unit_file("relative/sccache-dash", "/x")
.contains("ExecStart=\"relative/sccache-dash\""),
"quoting is the caller's path, verbatim"
);
}
}
File diff suppressed because it is too large. Load diff
+310
View File
@@ -0,0 +1,310 @@
//! 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::stats;
use sccache_dash::view;
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 {
script,
log: dir.path().join("sccache.log"),
history: dir.path().join("data").join("history.jsonl"),
_dir: dir,
}
}
/// 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()
}
}
/// 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);
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)
}
/// 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, 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!(app.lock().readings.len(), 1, "and the history is as it was");
}
#[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 (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"
);
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"
);
let state = app.lock();
assert_eq!(
state.readings.len(),
2,
"the baseline is kept and a line was added for the reset"
);
assert_eq!(state.intervals.len(), 1);
assert!(
state.intervals[0].reset,
"the zeroing shows in the history as a reset"
);
let v = view::build(&state, Range::SinceReset, unix_now());
assert_eq!(
v.totals,
Totals::default(),
"sccache's counters read zero now"
);
assert!(v.buckets[0].reset);
}
#[test]
fn view_export_and_the_page_answer() {
let fake = Fake::new();
let (_app, 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"));
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 lines_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();
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");
std::fs::write(
fake._dir.path().join("sccache.out"),
LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"),
)
.unwrap();
app.poll_at(NOW + 30);
assert_eq!(
lines(&app),
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"
);
assert!(
app.lock().intervals[1].delta.totals == Totals::default(),
"the heartbeat line records no change"
);
}
+1
View File
@@ -0,0 +1 @@
{"stats":{"compile_requests":820,"requests_unsupported_compiler":0,"requests_not_compile":2,"requests_not_cacheable":18,"requests_executed":800,"cache_errors":{"counts":{},"adv_counts":{}},"cache_hits":{"counts":{"C/C++":3},"adv_counts":{"c [gcc]":3}},"cache_misses":{"counts":{"C/C++":797},"adv_counts":{"c [gcc]":797}},"cache_timeouts":0,"cache_read_errors":0,"non_cacheable_compilations":0,"forced_recaches":0,"cache_write_errors":0,"cache_writes":797,"cache_write_duration":{"secs":9,"nanos":0},"cache_read_hit_duration":{"secs":0,"nanos":3000000},"compilations":797,"compiler_write_duration":{"secs":1200,"nanos":0},"compile_fails":0,"not_cached":{},"dist_compiles":{"10.0.0.12:4226":379,"buildbox.local:4228":9,"10.0.0.11:4226":402},"dist_errors":7,"multi_level":null},"cache_location":"Local disk: \"/home/me/.cache/sccache\"","cache_size":107374182,"max_cache_size":1073741824,"use_preprocessor_cache_mode":false,"version":"0.18.0","basedirs":[]}
+1
View File
@@ -0,0 +1 @@
{"stats":{"compile_requests":5000,"requests_unsupported_compiler":0,"requests_not_compile":12,"requests_not_cacheable":150,"requests_executed":4838,"cache_errors":{"counts":{},"adv_counts":{}},"cache_hits":{"counts":{"C/C++":2100,"Rust":400},"adv_counts":{"c [gcc]":2100,"rust":400}},"cache_misses":{"counts":{"Rust":2300,"C/C++":38},"adv_counts":{"rust":2300,"c [gcc]":38}},"cache_timeouts":12,"cache_read_errors":0,"non_cacheable_compilations":0,"forced_recaches":0,"cache_write_errors":5,"cache_writes":2338,"cache_write_duration":{"secs":40,"nanos":0},"cache_read_hit_duration":{"secs":0,"nanos":600000000},"compilations":2338,"compiler_write_duration":{"secs":18000,"nanos":0},"compile_fails":0,"not_cached":{"crate-type":150},"dist_compiles":{},"dist_errors":0,"multi_level":[{"name":"L0 (disk)","location":"Local disk: \"/home/me/.cache/sccache\"","hits":1500,"misses":1000,"writes":1400,"write_failures":2,"backfills_from":300,"backfills_to":0,"hit_duration":{"secs":1,"nanos":500000000},"write_duration":{"secs":2,"nanos":500000000}},{"name":"L1 (s3)","location":"s3, name: bucket, prefix: /p/","hits":1000,"misses":1800,"writes":900,"write_failures":0,"backfills_from":0,"backfills_to":300,"hit_duration":{"secs":6,"nanos":0},"write_duration":{"secs":36,"nanos":500000000}}]},"cache_location":"Multi-level: \"L0 (disk)\" + \"L1 (s3)\"","cache_size":1234567890,"max_cache_size":10737418240,"use_preprocessor_cache_mode":true,"version":"0.18.0","basedirs":[]}
+10
View File
@@ -0,0 +1,10 @@
# Build the page first, then the server with the page inside it.
build:
cd crates/ui && trunk build --release
cargo build --release -p sccache-dash
test:
cargo test -p sccache-dash -p sccache-dash-api
run:
cargo run -p sccache-dash