Compare commits
32
Commits
90a6302149
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a2bcefd38 | ||
|
|
06abc4de80 | ||
|
|
e3b56cb213 | ||
|
|
c2b07734c6 | ||
|
|
30643390a7 | ||
|
|
0759cbaa25 | ||
|
|
29e5103648 | ||
|
|
9630b96c1b | ||
|
|
f08f4655e4 | ||
|
|
a8c69567b4 | ||
|
|
0f4df265a5 | ||
|
|
4a1dfadfb0 | ||
|
|
3ede855fbb | ||
|
|
3e76fad51f | ||
|
|
0cb8206d43 | ||
|
|
7e864ad749 | ||
|
|
03ffdf887a | ||
|
|
a7d836d45a | ||
|
|
72fcf8f976 | ||
|
|
73c8138072 | ||
|
|
d7351a5d5e | ||
|
|
c56aaefa72 | ||
|
|
bcc178330b | ||
|
|
f277737e12 | ||
|
|
46b8dcf274 | ||
|
|
dc876b5a5c | ||
|
|
e282b40a18 | ||
|
|
693dca6cdf | ||
|
|
7ab1543315 | ||
|
|
16ba94517b | ||
|
|
c589b7c868 | ||
|
|
b80749ebb5 |
No files matched your search
@@ -1,3 +1,4 @@
|
|||||||
target/
|
target/
|
||||||
dist/
|
dist/
|
||||||
.sisi/
|
.sisi/
|
||||||
|
AGENTS.md
|
||||||
Generated
+2635
File diff suppressed because it is too large.
Load diff
@@ -1,11 +1,30 @@
|
|||||||
# sccache-dash
|
# sccache-dash
|
||||||
|
|
||||||
A small Linux program in the manner of Syncthing: one binary that watches the local
|
Is [sccache](https://github.com/mozilla/sccache) actually saving you time? sccache-dash answers
|
||||||
[sccache](https://github.com/mozilla/sccache) compiler cache, remembers what it did, and serves
|
that with a dashboard in your browser.
|
||||||
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
|
It is one small Linux program. It runs in the background, reads sccache's counters every 10
|
||||||
wrong, and sends the page one `View` to draw (the contract is `crates/api`).
|
seconds, keeps 30 days of history, and shows the result at <http://127.0.0.1:8226>. Only the
|
||||||
|
machine it runs on can open that page.
|
||||||
|
|
||||||
|
The page shows, for the last hour, 24 hours, 7 days or 30 days:
|
||||||
|
|
||||||
|
- how many compiles came from the cache, overall and per language
|
||||||
|
- roughly how much time that saved, with a 90% range
|
||||||
|
- what looks wrong: cache errors, timeouts, a language that rarely hits, a cache close to full
|
||||||
|
- where the other compiles went, and why some could not be cached
|
||||||
|
- how long a cache hit takes compared with a build, and how build times are spread
|
||||||
|
|
||||||
|
## What it looks like
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<td width="72%"><img src="docs/screenshots/desktop-light.png" alt="The dashboard on a wide screen, light"></td>
|
||||||
|
<td><img src="docs/screenshots/phone-dark.png" alt="The dashboard at phone width, dark"></td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
@@ -55,9 +74,17 @@ reading ever is a baseline and counts for nothing.
|
|||||||
|
|
||||||
## Notes on sccache
|
## Notes on sccache
|
||||||
|
|
||||||
While sccache's server is running, being asked for its stats every 10 seconds keeps it from its
|
sccache-dash never starts or stops sccache's server by itself. When none is running it shows
|
||||||
10-minute idle shutdown. When it is not running, `sccache --show-stats` does not start it (it
|
"not running"; sccache starts its own server on your next build, with your build's settings.
|
||||||
prints empty counters) and neither does this program; the next compile starts it, as usual.
|
|
||||||
|
To have sccache-dash start the server when none is running, set `SCCACHE_DASH_START_SCCACHE=1`
|
||||||
|
in its environment. Be careful with this: a server started that way gets sccache-dash's
|
||||||
|
environment, not your build's. If your cache size or folder is set only in your build's
|
||||||
|
environment, the server comes up with sccache's defaults, and sccache deletes cache entries
|
||||||
|
until the cache fits the 10 GB default.
|
||||||
|
|
||||||
|
While sccache-dash runs, sccache's server stays up: being asked for its stats every 10 seconds
|
||||||
|
keeps it from shutting itself down after 10 idle minutes.
|
||||||
|
|
||||||
## Licence
|
## Licence
|
||||||
|
|
||||||
|
|||||||
+19
-2
@@ -78,8 +78,9 @@ pub struct View {
|
|||||||
pub build_times: Vec<BuildTimes>,
|
pub build_times: Vec<BuildTimes>,
|
||||||
/// Sorted by hits + misses, largest first.
|
/// Sorted by hits + misses, largest first.
|
||||||
pub languages: Vec<Language>,
|
pub languages: Vec<Language>,
|
||||||
/// Why compiles were not cacheable, largest first, e.g. ("crate-type", 562).
|
/// Why compiles were not cacheable: reasons you can fix first, then expected ones,
|
||||||
pub not_cached: Vec<(String, u64)>,
|
/// each largest first.
|
||||||
|
pub not_cached: Vec<NotCached>,
|
||||||
/// Oldest first, evenly spaced, at most 120.
|
/// Oldest first, evenly spaced, at most 120.
|
||||||
pub buckets: Vec<Bucket>,
|
pub buckets: Vec<Bucket>,
|
||||||
/// Most serious first. Empty means no problems.
|
/// Most serious first. Empty means no problems.
|
||||||
@@ -92,6 +93,22 @@ pub struct View {
|
|||||||
pub summary_markdown: String,
|
pub summary_markdown: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One reason sccache gave for not caching a compile, with what to do about it.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct NotCached {
|
||||||
|
/// Exactly as sccache words it, e.g. "crate-type".
|
||||||
|
pub reason: String,
|
||||||
|
pub count: u64,
|
||||||
|
/// A plain name, e.g. "Incremental compilation is on".
|
||||||
|
pub name: String,
|
||||||
|
/// One sentence on what the reason means.
|
||||||
|
pub meaning: String,
|
||||||
|
/// What to change, or why nothing needs changing.
|
||||||
|
pub action: String,
|
||||||
|
/// True when a setting you control would make these compiles cacheable.
|
||||||
|
pub fixable: bool,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub enum Status {
|
pub enum Status {
|
||||||
/// Compiles arrived in the last five minutes.
|
/// Compiles arrived in the last five minutes.
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ license.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
sccache-dash-api = { path = "../api" }
|
sccache-dash-api = { path = "../api" }
|
||||||
|
sccache-dash-stats = { path = "../stats" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
tiny_http = "0.12"
|
tiny_http = "0.12"
|
||||||
|
|||||||
@@ -0,0 +1,289 @@
|
|||||||
|
//! What each "not cacheable" reason means and what to do about it.
|
||||||
|
//!
|
||||||
|
//! Every statement here was checked against the sccache 0.18.0 source (the file and line
|
||||||
|
//! of the code that produces each reason is beside its entry) and, where a command is
|
||||||
|
//! named, by running it. A reason that is not listed is shown as sccache words it, with
|
||||||
|
//! "sccache does not say more": we do not guess.
|
||||||
|
|
||||||
|
use sccache_dash_api::NotCached;
|
||||||
|
|
||||||
|
/// What we know about one reason.
|
||||||
|
pub struct Advice {
|
||||||
|
pub name: String,
|
||||||
|
pub meaning: String,
|
||||||
|
pub action: String,
|
||||||
|
pub fixable: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entry(name: &str, meaning: &str, action: &str, fixable: bool) -> Advice {
|
||||||
|
Advice {
|
||||||
|
name: name.to_owned(),
|
||||||
|
meaning: meaning.to_owned(),
|
||||||
|
action: action.to_owned(),
|
||||||
|
fixable,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The advice for `reason`, exactly as sccache's "Non-cacheable reasons" prints it.
|
||||||
|
pub fn advise(reason: &str) -> Advice {
|
||||||
|
let expected = |name: &str, meaning: &str, why: &str| {
|
||||||
|
entry(name, meaning, &format!("Nothing to do, this is expected. {why}"), false)
|
||||||
|
};
|
||||||
|
match reason {
|
||||||
|
// rust.rs:1208 `("incremental", _) => cannot_cache!("incremental")`
|
||||||
|
"incremental" => entry(
|
||||||
|
"Incremental compilation is on",
|
||||||
|
"rustc was told to compile incrementally (-C incremental=...), and sccache 0.18.0 never caches those compiles; its own note says rustc in incremental mode is likely to be faster than fetching from the cache.",
|
||||||
|
"To cache them, turn incremental off: set CARGO_INCREMENTAL=0 in the environment, or incremental = false under [profile.dev] in Cargo.toml, or incremental = false under [build] in ~/.cargo/config.toml. The trade-off: incremental makes rebuilds of your own crates faster, while the cache helps clean builds and dependency builds.",
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
// rust.rs:1187 and rust.rs:1298: only lib, rlib and staticlib are cached.
|
||||||
|
"crate-type" => expected(
|
||||||
|
"Programs and libraries that get linked",
|
||||||
|
"sccache only caches the crate types lib, rlib and staticlib. Anything else (bin, which includes build scripts and test programs, plus proc-macro, dylib and cdylib), or a call with no crate type, is not cached because rustc runs the system linker and sccache cannot know all of the linker's inputs.",
|
||||||
|
"Cargo builds each of these in every project, and they cannot be cached.",
|
||||||
|
),
|
||||||
|
// rust.rs:1026 `flag!("-", TooHardFlag)`, gcc.rs:190
|
||||||
|
"-" => expected(
|
||||||
|
"Source read from standard input",
|
||||||
|
"The compiler was given a bare - (read the source from standard input), which sccache does not cache.",
|
||||||
|
"Cargo makes one such call per run to ask rustc about the target it builds for.",
|
||||||
|
),
|
||||||
|
// rust.rs:1062 `take_arg!("-o", ..., TooHardPath)`; rust.rs doc: "We don't support `-o file`"
|
||||||
|
"-o" => entry(
|
||||||
|
"rustc called with -o",
|
||||||
|
"rustc was given -o <file>, which sccache 0.18.0 does not cache; it needs --out-dir (cargo passes that for normal builds).",
|
||||||
|
"Nothing to change in sccache. The tool that called rustc directly would have to use --out-dir instead.",
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
// rust.rs:1280 req!(input) (macro at 1269-1276). Seen in the log as CannotCache(missing input): ["-vV"].
|
||||||
|
"missing input" => expected(
|
||||||
|
"rustc call with no source file",
|
||||||
|
"A rustc call had no source file on its command line, so there was nothing to cache.",
|
||||||
|
"Cargo starts every run with `rustc -vV` to read the compiler's version, and that is counted here.",
|
||||||
|
),
|
||||||
|
// rust.rs:1282 req!(output_dir)
|
||||||
|
"missing output_dir" => expected(
|
||||||
|
"rustc call without --out-dir",
|
||||||
|
"A rustc call had no --out-dir, which sccache requires.",
|
||||||
|
"It comes from the tool that called rustc; cargo's normal builds pass --out-dir.",
|
||||||
|
),
|
||||||
|
// rust.rs:1283 req!(emit)
|
||||||
|
"missing emit" => expected(
|
||||||
|
"rustc call without --emit",
|
||||||
|
"A rustc call had no --emit, which sccache requires.",
|
||||||
|
"It comes from the tool that called rustc; cargo's normal builds pass --emit.",
|
||||||
|
),
|
||||||
|
// rust.rs:1284 req!(crate_name)
|
||||||
|
"missing crate_name" => expected(
|
||||||
|
"rustc call without --crate-name",
|
||||||
|
"A rustc call had no --crate-name, which sccache requires.",
|
||||||
|
"It comes from the tool that called rustc; cargo's normal builds pass --crate-name.",
|
||||||
|
),
|
||||||
|
// rust.rs:1173
|
||||||
|
"more than one --emit" => expected(
|
||||||
|
"rustc call with --emit given twice",
|
||||||
|
"rustc was given --emit more than once, which sccache does not handle.",
|
||||||
|
"It comes from the tool that called rustc.",
|
||||||
|
),
|
||||||
|
// rust.rs:1303 ALLOWED_EMIT = link, metadata, dep-info
|
||||||
|
"unsupported --emit" => expected(
|
||||||
|
"rustc asked for extra output",
|
||||||
|
"rustc was asked to emit something other than link, metadata and dep-info (for example asm or llvm-ir), which sccache does not cache.",
|
||||||
|
"Those outputs were asked for on purpose.",
|
||||||
|
),
|
||||||
|
// rust.rs:1198
|
||||||
|
"extra-filename" => expected(
|
||||||
|
"-C extra-filename without a value",
|
||||||
|
"rustc was given -C extra-filename with no value, which sccache cannot use.",
|
||||||
|
"It comes from the tool that called rustc.",
|
||||||
|
),
|
||||||
|
// rust.rs:1232 ArgTarget::Unsure, rust.rs:955-980
|
||||||
|
"target unsure" => entry(
|
||||||
|
"Ambiguous --target",
|
||||||
|
"The --target value is a plain name, but a file with that name plus .json exists, so sccache cannot tell whether a built-in target or your target file is meant.",
|
||||||
|
"Pass the target file by its path ending in .json (--target path/to/target.json); sccache then hashes the file's contents.",
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
// rust.rs:1048 `take_arg!("--sysroot", ..., TooHardPath)`
|
||||||
|
"--sysroot" => entry(
|
||||||
|
"rustc given --sysroot",
|
||||||
|
"rustc was given --sysroot, which sccache 0.18.0 does not cache.",
|
||||||
|
"If it comes from RUSTFLAGS or build.rustflags and you do not need a custom sysroot, remove it.",
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
// rust.rs:1248, gcc.rs:666, msvc.rs:791
|
||||||
|
"multiple input files" => entry(
|
||||||
|
"Several source files in one compiler call",
|
||||||
|
"One compiler call named more than one source file, and sccache caches only one source file per call.",
|
||||||
|
"If your build passes several files to one compiler call, change it to compile one file per call.",
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
// gcc.rs:362 and diab.rs:206
|
||||||
|
"@" => expected(
|
||||||
|
"Option value starting with @",
|
||||||
|
"An option's value began with @: an @file that sccache could not read or expand, or one attached straight to an option. sccache gives up on both.",
|
||||||
|
"It comes from how the build passes its flags.",
|
||||||
|
),
|
||||||
|
// gcc.rs:466
|
||||||
|
"-x" => entry(
|
||||||
|
"Unknown language after -x",
|
||||||
|
"The call said -x <language> with a language sccache does not know.",
|
||||||
|
"Use a language sccache knows (c, c++, objective-c, objective-c++, assembler, assembler-with-cpp, cu, cuda, hip, or a header kind) or drop -x.",
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
// gcc.rs:472
|
||||||
|
"multiple different -arch, and SCCACHE_CACHE_MULTIARCH not set" => entry(
|
||||||
|
"Several -arch values in one call",
|
||||||
|
"The call had more than one different -arch, and sccache only caches that when SCCACHE_CACHE_MULTIARCH is set.",
|
||||||
|
"Set SCCACHE_CACHE_MULTIARCH=1 in the environment sccache's server starts with.",
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
// gcc.rs:674, msvc.rs:802
|
||||||
|
"no input file" => expected(
|
||||||
|
"C/C++ call with no source file",
|
||||||
|
"The compiler call had no source file, so there was nothing to cache.",
|
||||||
|
"It comes from the tool that called the compiler.",
|
||||||
|
),
|
||||||
|
// gcc.rs:688, msvc.rs:799
|
||||||
|
"unknown source language" => entry(
|
||||||
|
"Source file type not recognised",
|
||||||
|
"sccache could not tell the language from the file's extension and the call had no -x.",
|
||||||
|
"Give the file a standard extension, or add -x c or -x c++ to the call.",
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
// gcc.rs:414
|
||||||
|
"unknown module output format" => expected(
|
||||||
|
"Unknown clang module output option",
|
||||||
|
"A clang module-output option had a value sccache does not understand.",
|
||||||
|
"Only clang modules builds do this.",
|
||||||
|
),
|
||||||
|
// gcc.rs:593-604
|
||||||
|
"Can't handle complex arguments through clang"
|
||||||
|
| "Can't handle Raw arguments with -Xclang"
|
||||||
|
| "Can't handle UnknownFlag arguments with -Xclang" => expected(
|
||||||
|
"Complicated -Xclang options",
|
||||||
|
"The call passes options through -Xclang that sccache cannot follow.",
|
||||||
|
"Remove the -Xclang options if you do not need them.",
|
||||||
|
),
|
||||||
|
// msvc.rs:610, msvc.rs:911, msvc.rs:831
|
||||||
|
"output to nul" | "shared pdb" | "invalid input file" => expected(
|
||||||
|
"Visual C++ call sccache cannot cache",
|
||||||
|
"The Visual C++ call writes its output to nul, uses a program database file shared by every compile in the folder (-Zi or -ZI without -Fd), or has an input path with no file name; sccache caches none of these.",
|
||||||
|
"These come from the call's own options.",
|
||||||
|
),
|
||||||
|
// gcc.rs:201-214 TooHardFlag: preprocess-only and dependency-only calls
|
||||||
|
"-E" | "-M" | "-MM" | "-P" => expected(
|
||||||
|
"Preprocess-only or dependency-only call",
|
||||||
|
"The call only preprocesses the source or only writes dependency rules (-E, -M, -MM, -P), so it produces no object file; sccache lists these options as too hard to cache.",
|
||||||
|
"Your build tool runs these calls on purpose.",
|
||||||
|
),
|
||||||
|
// gcc.rs:352, rust.rs:1147, msvc.rs:590
|
||||||
|
"argument parse" => entry(
|
||||||
|
"A compiler option sccache could not read",
|
||||||
|
"sccache could not parse one of the compiler's arguments.",
|
||||||
|
"sccache does not say more in its counters; run the server with SCCACHE_LOG=debug to see the call.",
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
// gcc.rs:375, clang.rs:192-295, msvc.rs:593: the reason is the option's own name.
|
||||||
|
other if other.starts_with('-') && other.len() > 1 => entry(
|
||||||
|
&format!("Option {other} is never cached"),
|
||||||
|
&format!(
|
||||||
|
"The compiler call contains {other}, which sccache's option table lists as too hard to cache, so every call with it runs uncached."
|
||||||
|
),
|
||||||
|
"If you do not need the option, remove it from the build's flags.",
|
||||||
|
true,
|
||||||
|
),
|
||||||
|
other => entry(
|
||||||
|
other,
|
||||||
|
"sccache does not say more.",
|
||||||
|
"",
|
||||||
|
false,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dress counted reasons with their advice: fixable ones first, then expected ones, each
|
||||||
|
/// largest first.
|
||||||
|
pub fn describe(reasons: &[(String, u64)]) -> Vec<NotCached> {
|
||||||
|
let mut out: Vec<NotCached> = reasons
|
||||||
|
.iter()
|
||||||
|
.map(|(reason, count)| {
|
||||||
|
let a = advise(reason);
|
||||||
|
NotCached {
|
||||||
|
reason: reason.clone(),
|
||||||
|
count: *count,
|
||||||
|
name: a.name,
|
||||||
|
meaning: a.meaning,
|
||||||
|
action: a.action,
|
||||||
|
fixable: a.fixable,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
out.sort_by(|a, b| {
|
||||||
|
b.fixable
|
||||||
|
.cmp(&a.fixable)
|
||||||
|
.then_with(|| b.count.cmp(&a.count))
|
||||||
|
.then_with(|| a.reason.cmp(&b.reason))
|
||||||
|
});
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many compiles were lost to reasons that can be fixed, and the biggest of them.
|
||||||
|
pub fn fixable_loss(reasons: &[NotCached]) -> Option<(u64, &NotCached)> {
|
||||||
|
let top = reasons.iter().filter(|r| r.fixable).max_by_key(|r| r.count)?;
|
||||||
|
Some((reasons.iter().filter(|r| r.fixable).map(|r| r.count).sum(), top))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incremental_says_how_to_turn_it_off_and_what_it_costs() {
|
||||||
|
let a = advise("incremental");
|
||||||
|
assert!(a.fixable);
|
||||||
|
assert!(a.action.contains("CARGO_INCREMENTAL=0"));
|
||||||
|
assert!(a.action.contains("[profile.dev]"));
|
||||||
|
assert!(a.action.contains("[build]"));
|
||||||
|
assert!(a.action.contains("trade-off"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn crate_type_is_expected_and_names_what_is_cached() {
|
||||||
|
let a = advise("crate-type");
|
||||||
|
assert!(!a.fixable);
|
||||||
|
assert!(a.action.starts_with("Nothing to do"));
|
||||||
|
assert!(a.meaning.contains("lib, rlib and staticlib"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unknown_reason_is_shown_as_it_came() {
|
||||||
|
let a = advise("something new in 0.19");
|
||||||
|
assert_eq!(a.name, "something new in 0.19");
|
||||||
|
assert_eq!(a.meaning, "sccache does not say more.");
|
||||||
|
assert!(!a.fixable);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_option_name_is_a_fixable_reason_but_the_known_dashes_are_not() {
|
||||||
|
assert!(advise("-fplugin").fixable);
|
||||||
|
assert!(!advise("-").fixable);
|
||||||
|
assert!(!advise("-o").fixable);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixable_reasons_come_first_then_the_biggest() {
|
||||||
|
let out = describe(&[
|
||||||
|
("crate-type".to_owned(), 1548),
|
||||||
|
("-".to_owned(), 156),
|
||||||
|
("incremental".to_owned(), 1642),
|
||||||
|
("multiple input files".to_owned(), 63),
|
||||||
|
]);
|
||||||
|
let order: Vec<&str> = out.iter().map(|r| r.reason.as_str()).collect();
|
||||||
|
assert_eq!(order, ["incremental", "multiple input files", "crate-type", "-"]);
|
||||||
|
let (lost, top) = fixable_loss(&out).unwrap();
|
||||||
|
assert_eq!((lost, top.reason.as_str()), (1705, "incremental"));
|
||||||
|
assert!(fixable_loss(&out[2..]).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
+218
-100
@@ -1,8 +1,10 @@
|
|||||||
//! What the service knows right now, and how it is kept up to date.
|
//! What the service knows right now, and how it is kept up to date. One task polls sccache, and
|
||||||
|
//! it alone holds the history and makes the views; requests only read what it made.
|
||||||
|
|
||||||
use std::ffi::{OsStr, OsString};
|
use std::ffi::{OsStr, OsString};
|
||||||
use std::io::{ErrorKind, Read};
|
use std::io::{ErrorKind, Read};
|
||||||
use std::path::PathBuf;
|
use std::net::{SocketAddr, TcpStream};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
use std::process::{Command, Stdio};
|
use std::process::{Command, Stdio};
|
||||||
use std::sync::mpsc::{channel, Receiver, Sender};
|
use std::sync::mpsc::{channel, Receiver, Sender};
|
||||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||||
@@ -14,32 +16,34 @@ use serde_json::Value;
|
|||||||
use wait_timeout::ChildExt;
|
use wait_timeout::ChildExt;
|
||||||
|
|
||||||
use crate::history::{History, Tracker};
|
use crate::history::{History, Tracker};
|
||||||
use crate::stats::{self, Snapshot};
|
use crate::stats::Snapshot;
|
||||||
use crate::view;
|
use crate::view::{self, Builds};
|
||||||
|
|
||||||
/// How often sccache is asked for its counters.
|
/// How often sccache is asked for its counters.
|
||||||
pub const POLL: Duration = Duration::from_secs(10);
|
pub const POLL: Duration = Duration::from_secs(10);
|
||||||
/// A sccache command that takes longer than this counts as failed.
|
/// A sccache command that takes longer than this counts as failed.
|
||||||
const COMMAND_TIMEOUT: Duration = Duration::from_secs(20);
|
const COMMAND_TIMEOUT: Duration = Duration::from_secs(20);
|
||||||
const PRUNE_EVERY: Duration = Duration::from_secs(86_400);
|
const PRUNE_EVERY: Duration = Duration::from_secs(86_400);
|
||||||
/// The ranges a view is kept for, in the order they are cached.
|
/// When starting sccache's server fails, it is not tried again sooner than this.
|
||||||
pub const RANGES: [Range; 5] = [
|
pub const START_EVERY: i64 = 60;
|
||||||
Range::Hour,
|
/// The port sccache's server listens on when `SCCACHE_SERVER_PORT` does not say.
|
||||||
Range::Day,
|
const SCCACHE_PORT: u16 = 4226;
|
||||||
Range::Week,
|
|
||||||
Range::Month,
|
|
||||||
Range::SinceReset,
|
|
||||||
];
|
|
||||||
|
|
||||||
pub struct Config {
|
pub struct Config {
|
||||||
/// The sccache command the service runs.
|
/// The sccache command the service runs.
|
||||||
pub sccache: OsString,
|
pub sccache: OsString,
|
||||||
/// The SQLite file the history is saved in.
|
/// The SQLite file the history is saved in.
|
||||||
pub history: PathBuf,
|
pub history: PathBuf,
|
||||||
|
/// Whether to start sccache's server when none is listening. Off unless asked for: a
|
||||||
|
/// server started from here has this program's environment, not the builds', so it can
|
||||||
|
/// come up with another cache size or folder, and sccache trims the cache to the size
|
||||||
|
/// it is started with.
|
||||||
|
pub start_sccache: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Config {
|
impl Config {
|
||||||
/// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset); the history
|
/// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset);
|
||||||
|
/// `SCCACHE_DASH_START_SCCACHE=1` lets it start sccache's server; the history
|
||||||
/// lives in `$XDG_DATA_HOME/sccache-dash/history.db`.
|
/// lives in `$XDG_DATA_HOME/sccache-dash/history.db`.
|
||||||
pub fn from_env() -> Result<Config, String> {
|
pub fn from_env() -> Result<Config, String> {
|
||||||
let sccache = std::env::var_os("SCCACHE_DASH_SCCACHE").unwrap_or_else(|| "sccache".into());
|
let sccache = std::env::var_os("SCCACHE_DASH_SCCACHE").unwrap_or_else(|| "sccache".into());
|
||||||
@@ -48,6 +52,7 @@ impl Config {
|
|||||||
Ok(Config {
|
Ok(Config {
|
||||||
sccache,
|
sccache,
|
||||||
history: dir.join("sccache-dash").join("history.db"),
|
history: dir.join("sccache-dash").join("history.db"),
|
||||||
|
start_sccache: std::env::var_os("SCCACHE_DASH_START_SCCACHE").is_some_and(|v| v == "1"),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,32 +77,54 @@ pub struct State {
|
|||||||
/// sccache's output of the last good reading, as JSON.
|
/// sccache's output of the last good reading, as JSON.
|
||||||
pub raw: Option<Value>,
|
pub raw: Option<Value>,
|
||||||
pub client_version: Option<String>,
|
pub client_version: Option<String>,
|
||||||
/// Why there is no live reading.
|
/// Why sccache counts as not running.
|
||||||
pub error: Option<String>,
|
pub error: Option<String>,
|
||||||
/// What the previous poll and the last saved row saw.
|
/// What the previous poll and the last saved row saw.
|
||||||
pub tracker: Tracker,
|
pub tracker: Tracker,
|
||||||
/// One view per range of [`RANGES`], made after every poll.
|
/// One view per range of [`Range::ALL`], made after every poll.
|
||||||
pub views: Vec<View>,
|
pub views: Vec<View>,
|
||||||
/// How long making those views took at the last poll.
|
/// How long making those views took at the last poll, and how many rows the database
|
||||||
|
/// handed out for it: a count of the work, which does not depend on how busy the machine is.
|
||||||
pub views_took: Duration,
|
pub views_took: Duration,
|
||||||
/// Whether a failure to save, and the first timing, have already been reported.
|
pub views_rows: usize,
|
||||||
pub reported: bool,
|
/// Whether a failure to save has already been reported.
|
||||||
|
pub warned: bool,
|
||||||
|
/// How many polls have had their timing reported: the first two.
|
||||||
|
pub reported: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether an sccache server is listening.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Probe {
|
||||||
|
Running,
|
||||||
|
NotRunning,
|
||||||
|
/// It could not be told; nothing is started then.
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type Prober = Arc<dyn Fn() -> Probe + Send + Sync>;
|
||||||
|
|
||||||
pub struct App {
|
pub struct App {
|
||||||
pub cfg: Config,
|
pub cfg: Config,
|
||||||
state: Mutex<State>,
|
state: Mutex<State>,
|
||||||
/// Wakes the polling task, as `/api/zero` needs: only that task holds the database.
|
/// Wakes the polling task, as `/api/zero` needs: only that task holds the database.
|
||||||
wake: (Sender<()>, Mutex<Option<Receiver<()>>>),
|
wake: (Sender<()>, Mutex<Option<Receiver<()>>>),
|
||||||
|
probe: Prober,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl App {
|
impl App {
|
||||||
pub fn new(cfg: Config) -> App {
|
pub fn new(cfg: Config) -> App {
|
||||||
|
App::with_probe(cfg, Arc::new(server_listening))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// With a stand-in for the check on sccache's server, as tests need.
|
||||||
|
pub fn with_probe(cfg: Config, probe: Prober) -> App {
|
||||||
let (send, receive) = channel();
|
let (send, receive) = channel();
|
||||||
App {
|
App {
|
||||||
cfg,
|
cfg,
|
||||||
state: Mutex::new(State::default()),
|
state: Mutex::new(State::default()),
|
||||||
wake: (send, Mutex::new(Some(receive))),
|
wake: (send, Mutex::new(Some(receive))),
|
||||||
|
probe,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,7 +135,8 @@ impl App {
|
|||||||
/// The view made for `range` at the last poll. A request never touches the database.
|
/// The view made for `range` at the last poll. A request never touches the database.
|
||||||
pub fn view(&self, range: Range) -> View {
|
pub fn view(&self, range: Range) -> View {
|
||||||
let state = self.lock();
|
let state = self.lock();
|
||||||
match state.views.get(index(range)) {
|
let index = Range::ALL.iter().position(|r| *r == range).unwrap_or(1);
|
||||||
|
match state.views.get(index) {
|
||||||
Some(view) => view.clone(),
|
Some(view) => view.clone(),
|
||||||
None => View {
|
None => View {
|
||||||
range: Some(range),
|
range: Some(range),
|
||||||
@@ -117,80 +145,6 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Opens the history for the polling task: what is too old is deleted, and what the
|
|
||||||
/// previous run remembered is taken over.
|
|
||||||
pub fn open_history(&self, now: i64) -> Result<History, String> {
|
|
||||||
let file = self.cfg.history.display().to_string();
|
|
||||||
let history =
|
|
||||||
History::open(&self.cfg.history).map_err(|e| format!("cannot open {file}: {e}"))?;
|
|
||||||
history
|
|
||||||
.prune(now)
|
|
||||||
.map_err(|e| format!("cannot prune {file}: {e}"))?;
|
|
||||||
self.lock().tracker = history.tracker();
|
|
||||||
Ok(history)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn poll(&self, history: &History) {
|
|
||||||
self.poll_at(history, unix_now());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Asks sccache for its counters and version, records what changed, and makes the views.
|
|
||||||
pub fn poll_at(&self, history: &History, now: i64) {
|
|
||||||
let version = run(&self.cfg.sccache, &["--version"])
|
|
||||||
.ok()
|
|
||||||
.and_then(|text| {
|
|
||||||
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)) => {
|
|
||||||
state.error = None;
|
|
||||||
state.raw = serde_json::from_str(&text).ok();
|
|
||||||
state.live = Some(Live {
|
|
||||||
at: now,
|
|
||||||
snapshot,
|
|
||||||
raw_text: text,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
state.error = Some(e);
|
|
||||||
state.live = None;
|
|
||||||
state.raw = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let file = self.cfg.history.display().to_string();
|
|
||||||
if let Some(counters) = state.live.as_ref().map(|l| l.snapshot.counters.clone()) {
|
|
||||||
match history.record(&mut state.tracker, &counters, now) {
|
|
||||||
Ok(()) => {}
|
|
||||||
Err(e) if !state.reported => {
|
|
||||||
state.reported = true;
|
|
||||||
eprintln!("sccache-dash: cannot save history to {file}: {e}");
|
|
||||||
}
|
|
||||||
Err(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let started = Instant::now();
|
|
||||||
state.views = view::all(history, &state, now);
|
|
||||||
state.views_took = started.elapsed();
|
|
||||||
if !state.reported {
|
|
||||||
state.reported = true;
|
|
||||||
eprintln!(
|
|
||||||
"sccache-dash: {} rows of history in {}; the five views take {:.2} ms per poll",
|
|
||||||
history.row_count().unwrap_or(0),
|
|
||||||
file,
|
|
||||||
state.views_took.as_secs_f64() * 1e3
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Runs `sccache --zero-stats`; the saved history stays as it is.
|
/// Runs `sccache --zero-stats`; the saved history stays as it is.
|
||||||
pub fn zero(&self) -> Result<(), String> {
|
pub fn zero(&self) -> Result<(), String> {
|
||||||
run(&self.cfg.sccache, &["--zero-stats"])?;
|
run(&self.cfg.sccache, &["--zero-stats"])?;
|
||||||
@@ -203,8 +157,8 @@ impl App {
|
|||||||
/// until the process ends. This task alone holds the database.
|
/// until the process ends. This task alone holds the database.
|
||||||
pub fn keep_updated(self: Arc<Self>) {
|
pub fn keep_updated(self: Arc<Self>) {
|
||||||
thread::spawn(move || {
|
thread::spawn(move || {
|
||||||
let history = match self.open_history(unix_now()) {
|
let mut task = match Task::open(&self.cfg.history, unix_now()) {
|
||||||
Ok(history) => history,
|
Ok(task) => task,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("sccache-dash: {e}");
|
eprintln!("sccache-dash: {e}");
|
||||||
std::process::exit(1);
|
std::process::exit(1);
|
||||||
@@ -218,10 +172,10 @@ impl App {
|
|||||||
.take();
|
.take();
|
||||||
let mut pruned = Instant::now();
|
let mut pruned = Instant::now();
|
||||||
loop {
|
loop {
|
||||||
self.poll(&history);
|
task.poll(&self, unix_now());
|
||||||
if pruned.elapsed() >= PRUNE_EVERY {
|
if pruned.elapsed() >= PRUNE_EVERY {
|
||||||
pruned = Instant::now();
|
pruned = Instant::now();
|
||||||
if let Err(e) = history.prune(unix_now()) {
|
if let Err(e) = task.history.prune(unix_now()) {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"sccache-dash: cannot prune {}: {e}",
|
"sccache-dash: cannot prune {}: {e}",
|
||||||
self.cfg.history.display()
|
self.cfg.history.display()
|
||||||
@@ -239,9 +193,173 @@ impl App {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where a range's view is kept.
|
/// The polling task's own things: the history, whose connection is not shared, and what it has
|
||||||
fn index(range: Range) -> usize {
|
/// learned of build times.
|
||||||
RANGES.iter().position(|r| *r == range).unwrap_or(1)
|
pub struct Task {
|
||||||
|
pub history: History,
|
||||||
|
builds: Builds,
|
||||||
|
/// When sccache's server was last tried to start, and why it is still not running.
|
||||||
|
started_at: Option<i64>,
|
||||||
|
start_error: Option<String>,
|
||||||
|
/// Whether the totals the last run remembered have been put back into the shared state.
|
||||||
|
resumed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Task {
|
||||||
|
/// Opens the history file, deleting what is too old.
|
||||||
|
pub fn open(path: &Path, now: i64) -> Result<Task, String> {
|
||||||
|
let history = History::open(path)?;
|
||||||
|
history
|
||||||
|
.prune(now)
|
||||||
|
.map_err(|e| format!("cannot prune {}: {e}", path.display()))?;
|
||||||
|
Ok(Task::with(history))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An empty history that is never written to disk, for tests.
|
||||||
|
pub fn memory() -> Task {
|
||||||
|
Task::with(History::memory().expect("an in-memory database"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with(history: History) -> Task {
|
||||||
|
Task {
|
||||||
|
history,
|
||||||
|
builds: Builds::new(),
|
||||||
|
started_at: None,
|
||||||
|
start_error: None,
|
||||||
|
resumed: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks sccache for its counters and version, starting its server if none is listening,
|
||||||
|
/// records what changed, and makes the views.
|
||||||
|
pub fn poll(&mut self, app: &App, now: i64) {
|
||||||
|
let version = run(&app.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 mut read = read_stats(&app.cfg.sccache);
|
||||||
|
// Without a server, `--show-stats` answers with empty counters rather than starting one.
|
||||||
|
let probe = (app.probe)();
|
||||||
|
match (probe, read.is_ok()) {
|
||||||
|
(Probe::NotRunning, true) => match self.start_server(app, now) {
|
||||||
|
Ok(()) => read = read_stats(&app.cfg.sccache),
|
||||||
|
Err(e) => self.start_error = Some(e),
|
||||||
|
},
|
||||||
|
(Probe::Running | Probe::Unknown, _) => self.start_error = None,
|
||||||
|
(Probe::NotRunning, false) => {}
|
||||||
|
}
|
||||||
|
let mut state = app.lock();
|
||||||
|
if !self.resumed {
|
||||||
|
// Carry on where the last run stopped: its running totals are the base that the work
|
||||||
|
// not yet in a row is counted from, so a restart neither drops it nor counts it twice.
|
||||||
|
self.resumed = true;
|
||||||
|
state.tracker = self.history.tracker();
|
||||||
|
}
|
||||||
|
state.client_version = version;
|
||||||
|
match read {
|
||||||
|
Ok((text, snapshot)) => {
|
||||||
|
state.error = self.start_error.clone();
|
||||||
|
state.raw = serde_json::from_str(&text).ok();
|
||||||
|
state.live = Some(Live {
|
||||||
|
at: now,
|
||||||
|
snapshot,
|
||||||
|
raw_text: text,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
state.error = Some(e);
|
||||||
|
state.live = None;
|
||||||
|
state.raw = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(counters) = state.live.as_ref().map(|l| l.snapshot.counters.clone()) {
|
||||||
|
match self.history.record(&mut state.tracker, &counters, now) {
|
||||||
|
Ok(()) => {}
|
||||||
|
Err(e) if !state.warned => {
|
||||||
|
state.warned = true;
|
||||||
|
eprintln!(
|
||||||
|
"sccache-dash: cannot save history to {}: {e}",
|
||||||
|
app.cfg.history.display()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let started = Instant::now();
|
||||||
|
self.history.take_fetched();
|
||||||
|
self.builds.refresh(&self.history, now);
|
||||||
|
state.views = view::all(&self.history, &self.builds, &state, now);
|
||||||
|
state.views_took = started.elapsed();
|
||||||
|
state.views_rows = self.history.take_fetched();
|
||||||
|
// Reported for the first two polls: the first reads the build observations and draws the
|
||||||
|
// bootstrap, the second shows what every later poll costs.
|
||||||
|
if state.reported < 2 {
|
||||||
|
state.reported += 1;
|
||||||
|
eprintln!(
|
||||||
|
"sccache-dash: {} rows of history in {}; the five views take {:.2} ms and {} rows per poll",
|
||||||
|
self.history.row_count().unwrap_or(0),
|
||||||
|
app.cfg.history.display(),
|
||||||
|
state.views_took.as_secs_f64() * 1e3,
|
||||||
|
state.views_rows
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts sccache's server when none is listening and that was asked for, at most once a minute. `Err` says why
|
||||||
|
/// there is none, including when an earlier attempt is still being waited out.
|
||||||
|
fn start_server(&mut self, app: &App, now: i64) -> Result<(), String> {
|
||||||
|
if !app.cfg.start_sccache {
|
||||||
|
return Err("no sccache server is running; your next build starts it".to_owned());
|
||||||
|
}
|
||||||
|
if let Some(when) = self.started_at {
|
||||||
|
if now - when < START_EVERY {
|
||||||
|
return Err(self
|
||||||
|
.start_error
|
||||||
|
.clone()
|
||||||
|
.unwrap_or_else(|| "no sccache server is running".to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.started_at = Some(now);
|
||||||
|
run(&app.cfg.sccache, &["--start-server"])
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|e| {
|
||||||
|
format!("no sccache server is running and `sccache --start-server` failed: {e}")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_stats(sccache: &OsStr) -> Result<(String, Snapshot), String> {
|
||||||
|
run(sccache, &["--show-stats", "--stats-format", "json"])
|
||||||
|
.and_then(|text| crate::stats::parse(&text).map(|snapshot| (text, snapshot)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether an sccache server is listening, found the way its client finds it (`get_addr` in
|
||||||
|
/// sccache 0.18): `SCCACHE_SERVER_UDS` names its socket, otherwise it is on 127.0.0.1 at the
|
||||||
|
/// port `SCCACHE_SERVER_PORT` gives, 4226 by default. Only a connection is made and closed
|
||||||
|
/// again: no request is sent, so nothing is started, read or reset.
|
||||||
|
pub fn server_listening() -> Probe {
|
||||||
|
if let Some(path) = std::env::var_os("SCCACHE_SERVER_UDS").filter(|p| !p.is_empty()) {
|
||||||
|
return match std::os::unix::net::UnixStream::connect(path) {
|
||||||
|
Ok(_) => Probe::Running,
|
||||||
|
Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::ConnectionRefused) => {
|
||||||
|
Probe::NotRunning
|
||||||
|
}
|
||||||
|
Err(_) => Probe::Unknown,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let port = std::env::var("SCCACHE_SERVER_PORT")
|
||||||
|
.ok()
|
||||||
|
.and_then(|s| s.parse().ok())
|
||||||
|
.unwrap_or(SCCACHE_PORT);
|
||||||
|
match TcpStream::connect_timeout(
|
||||||
|
&SocketAddr::from(([127, 0, 0, 1], port)),
|
||||||
|
Duration::from_millis(500),
|
||||||
|
) {
|
||||||
|
Ok(_) => Probe::Running,
|
||||||
|
Err(e) if e.kind() == ErrorKind::ConnectionRefused => Probe::NotRunning,
|
||||||
|
Err(_) => Probe::Unknown,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs sccache and returns what it printed; `Err` says why when it is missing, fails or hangs.
|
/// Runs sccache and returns what it printed; `Err` says why when it is missing, fails or hangs.
|
||||||
|
|||||||
+186
-127
@@ -1,14 +1,16 @@
|
|||||||
//! The saved history in one SQLite file. Each row holds what changed since the row before it,
|
//! The saved history in one SQLite file. Each row holds what changed since the row before it,
|
||||||
//! so that a range total is one indexed `SELECT SUM(...)`. Rows come at most one a minute and
|
//! so that a range total is one indexed `SELECT SUM(...)` and the chart one `GROUP BY`. Rows come
|
||||||
//! only when sccache's counters changed; a stretch without rows is a gap.
|
//! at most one a minute and only when sccache's counters changed; a stretch without rows is a gap.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::cell::Cell;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use rusqlite::{params, params_from_iter, Connection, OptionalExtension};
|
use rusqlite::{params, params_from_iter, Connection, OptionalExtension};
|
||||||
use sccache_dash_api::Totals;
|
use sccache_dash_api::Totals;
|
||||||
use serde::{de::DeserializeOwned, Deserialize, Serialize};
|
use sccache_dash_stats::Observation;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::stats::{Counters, COMPILE};
|
use crate::stats::{Counters, COMPILE};
|
||||||
|
|
||||||
@@ -46,15 +48,13 @@ macro_rules! push {
|
|||||||
const NAMES: &str = each!(names!());
|
const NAMES: &str = each!(names!());
|
||||||
const DEFS: &str = each!(defs!());
|
const DEFS: &str = each!(defs!());
|
||||||
const SUMS: &str = each!(sums!());
|
const SUMS: &str = each!(sums!());
|
||||||
/// One point of the histogram of build times: the builds of one language that finished between
|
|
||||||
/// two polls ten seconds apart.
|
const OTHER_TABLES: &str = "
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
CREATE TABLE IF NOT EXISTS reading_languages (t INTEGER NOT NULL, language TEXT NOT NULL, hits INTEGER NOT NULL, misses INTEGER NOT NULL, errors INTEGER NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
|
||||||
pub struct BuildObs {
|
CREATE TABLE IF NOT EXISTS not_cached (t INTEGER NOT NULL, reason TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (t, reason)) WITHOUT ROWID;
|
||||||
pub t: i64,
|
CREATE TABLE IF NOT EXISTS build_obs (t INTEGER NOT NULL, language TEXT NOT NULL, compiles INTEGER NOT NULL, seconds REAL NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
|
||||||
pub language: String,
|
CREATE INDEX IF NOT EXISTS build_obs_language ON build_obs (language);
|
||||||
pub compiles: u64,
|
CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;";
|
||||||
pub seconds: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What is remembered between polls, so that differences survive a restart of sccache-dash.
|
/// What is remembered between polls, so that differences survive a restart of sccache-dash.
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||||
@@ -67,7 +67,7 @@ pub struct Tracker {
|
|||||||
pub row_at: i64,
|
pub row_at: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One saved row: when it was written, and what had changed since the row before.
|
/// What the live reading adds since the last saved row.
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
pub struct Row {
|
pub struct Row {
|
||||||
pub t: i64,
|
pub t: i64,
|
||||||
@@ -76,8 +76,33 @@ pub struct Row {
|
|||||||
pub delta: Counters,
|
pub delta: Counters,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One bucket of the chart as SQLite adds it up; `b` is the bucket's number.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct BucketRow {
|
||||||
|
pub b: i64,
|
||||||
|
pub reset: bool,
|
||||||
|
/// When the first and the last row in the bucket are dated.
|
||||||
|
pub first: i64,
|
||||||
|
pub last: i64,
|
||||||
|
pub hits: u64,
|
||||||
|
pub misses: u64,
|
||||||
|
pub other: u64,
|
||||||
|
pub errors: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One language's hits and misses in one bucket of the chart.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct BucketLangs {
|
||||||
|
pub b: i64,
|
||||||
|
pub language: String,
|
||||||
|
pub hits: u64,
|
||||||
|
pub misses: u64,
|
||||||
|
}
|
||||||
|
|
||||||
pub struct History {
|
pub struct History {
|
||||||
conn: Connection,
|
conn: Connection,
|
||||||
|
/// How many rows queries have handed out since the last look: a count of the work done.
|
||||||
|
fetched: Cell<usize>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl History {
|
impl History {
|
||||||
@@ -103,7 +128,19 @@ impl History {
|
|||||||
compilations INTEGER NOT NULL DEFAULT 0, hit_read REAL NOT NULL DEFAULT 0, \
|
compilations INTEGER NOT NULL DEFAULT 0, hit_read REAL NOT NULL DEFAULT 0, \
|
||||||
cache_write REAL NOT NULL DEFAULT 0, compile REAL NOT NULL DEFAULT 0);\n{OTHER_TABLES}"
|
cache_write REAL NOT NULL DEFAULT 0, compile REAL NOT NULL DEFAULT 0);\n{OTHER_TABLES}"
|
||||||
))?;
|
))?;
|
||||||
Ok(History { conn })
|
Ok(History {
|
||||||
|
conn,
|
||||||
|
fetched: Cell::new(0),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many rows queries handed out since the last look.
|
||||||
|
pub fn take_fetched(&self) -> usize {
|
||||||
|
self.fetched.replace(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count(&self, rows: usize) {
|
||||||
|
self.fetched.set(self.fetched.get() + rows);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Deletes the rows older than [`KEEP_DAYS`], and says how many went.
|
/// Deletes the rows older than [`KEEP_DAYS`], and says how many went.
|
||||||
@@ -139,6 +176,17 @@ impl History {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Saves a run of readings exactly as the polls would have, in one transaction.
|
||||||
|
pub fn fill(&self, readings: &[(i64, Counters)]) -> rusqlite::Result<()> {
|
||||||
|
self.conn.execute_batch("BEGIN")?;
|
||||||
|
let mut tracker = self.tracker();
|
||||||
|
let result = readings
|
||||||
|
.iter()
|
||||||
|
.try_for_each(|(t, c)| self.record(&mut tracker, c, *t));
|
||||||
|
self.conn.execute_batch("COMMIT")?;
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
/// What the previous run of sccache-dash remembered, so that it carries on where it stopped.
|
/// What the previous run of sccache-dash remembered, so that it carries on where it stopped.
|
||||||
pub fn tracker(&self) -> Tracker {
|
pub fn tracker(&self) -> Tracker {
|
||||||
self.state("tracker").unwrap_or_default()
|
self.state("tracker").unwrap_or_default()
|
||||||
@@ -151,10 +199,9 @@ impl History {
|
|||||||
if let Some(previous) = &tracker.last_poll {
|
if let Some(previous) = &tracker.last_poll {
|
||||||
let (since, _) = c.since(previous);
|
let (since, _) = c.since(previous);
|
||||||
if let Some((language, _)) = since.one_missed_language() {
|
if let Some((language, _)) = since.one_missed_language() {
|
||||||
let seconds = since.ns[COMPILE] as f64 / NANOS;
|
|
||||||
self.conn.execute(
|
self.conn.execute(
|
||||||
"INSERT OR REPLACE INTO build_obs (t, language, compiles, seconds) VALUES (?1, ?2, ?3, ?4)",
|
"INSERT OR REPLACE INTO build_obs (t, language, compiles, seconds) VALUES (?1, ?2, ?3, ?4)",
|
||||||
params![now, language, since.compilations as i64, seconds],
|
params![now, language, since.compilations as i64, since.ns[COMPILE] as f64 / NANOS],
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -166,8 +213,7 @@ impl History {
|
|||||||
}
|
}
|
||||||
Some(base) => {
|
Some(base) => {
|
||||||
let (diff, reset) = c.since(base);
|
let (diff, reset) = c.since(base);
|
||||||
let changed = diff != Counters::default() || reset;
|
if (diff != Counters::default() || reset) && now - tracker.row_at >= MIN_ROW_SECS {
|
||||||
if changed && now - tracker.row_at >= MIN_ROW_SECS {
|
|
||||||
self.save(now, &diff, reset)?;
|
self.save(now, &diff, reset)?;
|
||||||
tracker.row_base = Some(c.clone());
|
tracker.row_base = Some(c.clone());
|
||||||
tracker.row_at = now;
|
tracker.row_at = now;
|
||||||
@@ -192,9 +238,9 @@ impl History {
|
|||||||
);
|
);
|
||||||
self.conn
|
self.conn
|
||||||
.execute(&sql, params_from_iter(values.iter().map(|v| v.as_ref())))?;
|
.execute(&sql, params_from_iter(values.iter().map(|v| v.as_ref())))?;
|
||||||
let mut langs = self.conn.prepare(
|
let mut langs = self
|
||||||
"INSERT INTO reading_languages (t, language, hits, misses, errors) VALUES (?1, ?2, ?3, ?4, ?5)",
|
.conn
|
||||||
)?;
|
.prepare("INSERT INTO reading_languages (t, language, hits, misses, errors) VALUES (?1, ?2, ?3, ?4, ?5)")?;
|
||||||
for (name, v) in &diff.langs {
|
for (name, v) in &diff.langs {
|
||||||
langs.execute(params![t, name, v[0] as i64, v[1] as i64, v[2] as i64])?;
|
langs.execute(params![t, name, v[0] as i64, v[1] as i64, v[2] as i64])?;
|
||||||
}
|
}
|
||||||
@@ -207,45 +253,83 @@ impl History {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The totals of the rows from `from` (inclusive) to `to` (exclusive): one indexed query.
|
/// The counters summed over the rows from `from` (inclusive) to `to` (exclusive): one indexed
|
||||||
/// `None` when there is no row in that time.
|
/// query. `None` when there is no row in that time. Languages and reasons are not part of it.
|
||||||
pub fn sums(&self, from: i64, to: i64) -> rusqlite::Result<Option<Totals>> {
|
pub fn sums(&self, from: i64, to: i64) -> rusqlite::Result<Option<Counters>> {
|
||||||
let sql = format!("SELECT COUNT(*){SUMS} FROM readings WHERE t >= ?1 AND t < ?2");
|
let sql = format!(
|
||||||
|
"SELECT COUNT(*){SUMS}, SUM(compilations) AS compilations, SUM(hit_read) AS hit_read, \
|
||||||
|
SUM(cache_write) AS cache_write, SUM(compile) AS compile FROM readings WHERE t >= ?1 AND t < ?2"
|
||||||
|
);
|
||||||
|
self.count(1);
|
||||||
self.conn.query_row(&sql, params![from, to], |row| {
|
self.conn.query_row(&sql, params![from, to], |row| {
|
||||||
let rows: i64 = row.get(0)?;
|
let rows: i64 = row.get(0)?;
|
||||||
|
let nanos = |name: &str| -> rusqlite::Result<u64> {
|
||||||
|
Ok((row.get::<_, f64>(name)? * NANOS).round().max(0.0) as u64)
|
||||||
|
};
|
||||||
Ok(if rows > 0 {
|
Ok(if rows > 0 {
|
||||||
Some(each!(totals_of!(row)))
|
Some(Counters {
|
||||||
|
totals: each!(totals_of!(row)),
|
||||||
|
compilations: row.get::<_, i64>("compilations")?.max(0) as u64,
|
||||||
|
ns: [nanos("hit_read")?, nanos("cache_write")?, nanos("compile")?],
|
||||||
|
..Counters::default()
|
||||||
|
})
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The rows from `from` (inclusive) to `to` (exclusive), oldest first.
|
/// The chart's counts, one row per bucket: bucket `b` holds the rows dated from
|
||||||
pub fn rows(&self, from: i64, to: i64) -> rusqlite::Result<Vec<Row>> {
|
/// `from + b * len` on, for `t` below `to`.
|
||||||
let sql = format!(
|
pub fn bucket_rows(&self, from: i64, len: i64, to: i64) -> rusqlite::Result<Vec<BucketRow>> {
|
||||||
"SELECT t, reset{NAMES}, compilations, hit_read, cache_write, compile FROM readings WHERE t >= ?1 AND t < ?2 ORDER BY t"
|
let sql = "SELECT (t - ?1) / ?2 AS b, MAX(reset) != 0 AS reset, MIN(t) AS first, MAX(t) AS last, \
|
||||||
);
|
SUM(hits) AS hits, SUM(misses) AS misses, \
|
||||||
let mut stmt = self.conn.prepare(&sql)?;
|
SUM(not_cacheable) + SUM(unsupported_compiler) + SUM(not_compile) AS other, \
|
||||||
let rows = stmt.query_map(params![from, to], |row| {
|
SUM(read_errors) + SUM(write_errors) + SUM(other_errors) AS errors \
|
||||||
let nanos = |name: &str| -> rusqlite::Result<u64> {
|
FROM readings WHERE t >= ?1 AND t < ?3 GROUP BY b";
|
||||||
Ok((row.get::<_, f64>(name)? * NANOS).round().max(0.0) as u64)
|
let mut stmt = self.conn.prepare(sql)?;
|
||||||
};
|
let rows = stmt.query_map(params![from, len, to], |row| {
|
||||||
Ok(Row {
|
Ok(BucketRow {
|
||||||
t: row.get("t")?,
|
b: row.get("b")?,
|
||||||
reset: row.get::<_, i64>("reset")? != 0,
|
reset: row.get::<_, i64>("reset")? != 0,
|
||||||
delta: Counters {
|
first: row.get("first")?,
|
||||||
totals: each!(totals_of!(row)),
|
last: row.get("last")?,
|
||||||
compilations: row.get::<_, i64>("compilations")?.max(0) as u64,
|
hits: row.get::<_, i64>("hits")?.max(0) as u64,
|
||||||
ns: [nanos("hit_read")?, nanos("cache_write")?, nanos("compile")?],
|
misses: row.get::<_, i64>("misses")?.max(0) as u64,
|
||||||
..Counters::default()
|
other: row.get::<_, i64>("other")?.max(0) as u64,
|
||||||
},
|
errors: row.get::<_, i64>("errors")?.max(0) as u64,
|
||||||
})
|
})
|
||||||
})?;
|
})?;
|
||||||
rows.collect()
|
let rows = rows.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||||
|
self.count(rows.len());
|
||||||
|
Ok(rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// (language, hits, misses, errors) summed over the rows from `from` to `to`.
|
/// Each language's hits and misses per bucket of the chart.
|
||||||
|
pub fn bucket_languages(
|
||||||
|
&self,
|
||||||
|
from: i64,
|
||||||
|
len: i64,
|
||||||
|
to: i64,
|
||||||
|
) -> rusqlite::Result<Vec<BucketLangs>> {
|
||||||
|
let mut stmt = self.conn.prepare(
|
||||||
|
"SELECT (t - ?1) / ?2 AS b, language, SUM(hits) AS hits, SUM(misses) AS misses \
|
||||||
|
FROM reading_languages WHERE t >= ?1 AND t < ?3 GROUP BY b, language",
|
||||||
|
)?;
|
||||||
|
let rows = stmt.query_map(params![from, len, to], |row| {
|
||||||
|
Ok(BucketLangs {
|
||||||
|
b: row.get("b")?,
|
||||||
|
language: row.get(1)?,
|
||||||
|
hits: row.get::<_, i64>(2)?.max(0) as u64,
|
||||||
|
misses: row.get::<_, i64>(3)?.max(0) as u64,
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
let rows = rows.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||||
|
self.count(rows.len());
|
||||||
|
Ok(rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (language, [hits, misses, errors]) summed over the rows from `from` to `to`.
|
||||||
pub fn languages(&self, from: i64, to: i64) -> rusqlite::Result<Vec<(String, [u64; 3])>> {
|
pub fn languages(&self, from: i64, to: i64) -> rusqlite::Result<Vec<(String, [u64; 3])>> {
|
||||||
let mut stmt = self.conn.prepare(
|
let mut stmt = self.conn.prepare(
|
||||||
"SELECT language, SUM(hits), SUM(misses), SUM(errors) FROM reading_languages WHERE t >= ?1 AND t < ?2 GROUP BY language ORDER BY language",
|
"SELECT language, SUM(hits), SUM(misses), SUM(errors) FROM reading_languages WHERE t >= ?1 AND t < ?2 GROUP BY language ORDER BY language",
|
||||||
@@ -260,27 +344,9 @@ impl History {
|
|||||||
],
|
],
|
||||||
))
|
))
|
||||||
})?;
|
})?;
|
||||||
out.collect()
|
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||||
}
|
self.count(out.len());
|
||||||
|
Ok(out)
|
||||||
/// (t, language, hits, misses) of the rows from `from` to `to`, for the chart.
|
|
||||||
pub fn language_rows(
|
|
||||||
&self,
|
|
||||||
from: i64,
|
|
||||||
to: i64,
|
|
||||||
) -> rusqlite::Result<Vec<(i64, String, u64, u64)>> {
|
|
||||||
let mut stmt = self.conn.prepare(
|
|
||||||
"SELECT t, language, hits, misses FROM reading_languages WHERE t >= ?1 AND t < ?2 ORDER BY t",
|
|
||||||
)?;
|
|
||||||
let out = stmt.query_map(params![from, to], |row| {
|
|
||||||
Ok((
|
|
||||||
row.get(0)?,
|
|
||||||
row.get(1)?,
|
|
||||||
row.get::<_, i64>(2)?.max(0) as u64,
|
|
||||||
row.get::<_, i64>(3)?.max(0) as u64,
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
out.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// (reason, count) summed over the rows from `from` to `to`.
|
/// (reason, count) summed over the rows from `from` to `to`.
|
||||||
@@ -291,11 +357,39 @@ impl History {
|
|||||||
let out = stmt.query_map(params![from, to], |row| {
|
let out = stmt.query_map(params![from, to], |row| {
|
||||||
Ok((row.get(0)?, row.get::<_, i64>(1)?.max(0) as u64))
|
Ok((row.get(0)?, row.get::<_, i64>(1)?.max(0) as u64))
|
||||||
})?;
|
})?;
|
||||||
out.collect()
|
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||||
|
self.count(out.len());
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When the counters were last seen to be zeroed; `None` when they never were.
|
||||||
|
pub fn last_reset(&self) -> rusqlite::Result<Option<i64>> {
|
||||||
|
self.count(1);
|
||||||
|
self.conn
|
||||||
|
.query_row("SELECT MAX(t) FROM readings WHERE reset != 0", [], |row| {
|
||||||
|
row.get(0)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The oldest row there is: where the `reset` chart starts when no zeroing was ever seen.
|
||||||
|
pub fn first_row(&self) -> rusqlite::Result<Option<i64>> {
|
||||||
|
self.count(1);
|
||||||
|
self.conn
|
||||||
|
.query_row("SELECT MIN(t) FROM readings", [], |row| row.get(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many rows there are, all told.
|
||||||
|
pub fn row_count(&self) -> rusqlite::Result<usize> {
|
||||||
|
Ok(self
|
||||||
|
.conn
|
||||||
|
.query_row("SELECT COUNT(*) FROM readings", [], |row| {
|
||||||
|
row.get::<_, i64>(0)
|
||||||
|
})? as usize)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `requests` summed over the rows from `from` on.
|
/// `requests` summed over the rows from `from` on.
|
||||||
pub fn requests_since(&self, from: i64) -> rusqlite::Result<u64> {
|
pub fn requests_since(&self, from: i64) -> rusqlite::Result<u64> {
|
||||||
|
self.count(1);
|
||||||
let sum: i64 = self.conn.query_row(
|
let sum: i64 = self.conn.query_row(
|
||||||
"SELECT COALESCE(SUM(requests), 0) FROM readings WHERE t >= ?1",
|
"SELECT COALESCE(SUM(requests), 0) FROM readings WHERE t >= ?1",
|
||||||
[from],
|
[from],
|
||||||
@@ -304,68 +398,33 @@ impl History {
|
|||||||
Ok(sum.max(0) as u64)
|
Ok(sum.max(0) as u64)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When the counters were last seen to be zeroed; `None` when they never were.
|
/// How many build observations there are and when the newest one is dated: one row, to tell
|
||||||
pub fn last_reset(&self) -> rusqlite::Result<Option<i64>> {
|
/// whether they changed.
|
||||||
self.conn
|
pub fn build_obs_stamp(&self) -> rusqlite::Result<(i64, i64)> {
|
||||||
.query_row("SELECT MAX(t) FROM readings WHERE reset != 0", [], |row| {
|
self.count(1);
|
||||||
row.get(0)
|
self.conn.query_row(
|
||||||
})
|
"SELECT COUNT(*), COALESCE(MAX(t), 0) FROM build_obs",
|
||||||
|
[],
|
||||||
|
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The oldest row there is.
|
/// The build observations dated after `after`: (language, what was seen).
|
||||||
pub fn first_row(&self) -> rusqlite::Result<Option<i64>> {
|
pub fn build_obs_after(&self, after: i64) -> rusqlite::Result<Vec<(String, Observation)>> {
|
||||||
self.conn
|
|
||||||
.query_row("SELECT MIN(t) FROM readings", [], |row| row.get(0))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many rows there are, all told.
|
|
||||||
pub fn row_count(&self) -> rusqlite::Result<usize> {
|
|
||||||
self.conn
|
|
||||||
.query_row("SELECT COUNT(*) FROM readings", [], |row| row.get(0))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// (seconds spent compiling, compiles) seen for each language, from the build observations.
|
|
||||||
pub fn build_time_totals(&self) -> rusqlite::Result<BTreeMap<String, (f64, u64)>> {
|
|
||||||
let mut stmt = self.conn.prepare(
|
|
||||||
"SELECT language, SUM(seconds), SUM(compiles) FROM build_obs GROUP BY language",
|
|
||||||
)?;
|
|
||||||
let out = stmt.query_map([], |row| {
|
|
||||||
Ok((
|
|
||||||
row.get(0)?,
|
|
||||||
(row.get::<_, f64>(1)?, row.get::<_, i64>(2)?.max(0) as u64),
|
|
||||||
))
|
|
||||||
})?;
|
|
||||||
out.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The build-time observations, per language and oldest first: the raw data of the histogram.
|
|
||||||
pub fn build_observations(&self) -> rusqlite::Result<BTreeMap<String, Vec<BuildObs>>> {
|
|
||||||
let mut stmt = self
|
let mut stmt = self
|
||||||
.conn
|
.conn
|
||||||
.prepare("SELECT t, language, compiles, seconds FROM build_obs ORDER BY language, t")?;
|
.prepare("SELECT language, compiles, seconds FROM build_obs WHERE t > ?1 ORDER BY t")?;
|
||||||
let out = stmt.query_map([], |row| {
|
let out = stmt.query_map([after], |row| {
|
||||||
Ok(BuildObs {
|
Ok((
|
||||||
t: row.get(0)?,
|
row.get(0)?,
|
||||||
language: row.get(1)?,
|
Observation {
|
||||||
compiles: row.get::<_, i64>(2)?.max(0) as u64,
|
compiles: row.get::<_, i64>(1)?.max(0) as u64,
|
||||||
seconds: row.get(3)?,
|
seconds: row.get(2)?,
|
||||||
})
|
},
|
||||||
|
))
|
||||||
})?;
|
})?;
|
||||||
let mut by_language: BTreeMap<String, Vec<BuildObs>> = BTreeMap::new();
|
let out = out.collect::<rusqlite::Result<Vec<_>>>()?;
|
||||||
for obs in out {
|
self.count(out.len());
|
||||||
let obs = obs?;
|
Ok(out)
|
||||||
by_language
|
|
||||||
.entry(obs.language.clone())
|
|
||||||
.or_default()
|
|
||||||
.push(obs);
|
|
||||||
}
|
|
||||||
Ok(by_language)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const OTHER_TABLES: &str = "
|
|
||||||
CREATE TABLE IF NOT EXISTS reading_languages (t INTEGER NOT NULL, language TEXT NOT NULL, hits INTEGER NOT NULL, misses INTEGER NOT NULL, errors INTEGER NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
|
|
||||||
CREATE TABLE IF NOT EXISTS not_cached (t INTEGER NOT NULL, reason TEXT NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (t, reason)) WITHOUT ROWID;
|
|
||||||
CREATE TABLE IF NOT EXISTS build_obs (t INTEGER NOT NULL, language TEXT NOT NULL, compiles INTEGER NOT NULL, seconds REAL NOT NULL, PRIMARY KEY (t, language)) WITHOUT ROWID;
|
|
||||||
CREATE INDEX IF NOT EXISTS build_obs_language ON build_obs (language);
|
|
||||||
CREATE TABLE IF NOT EXISTS state (key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;";
|
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
//! The server half of sccache-dash: it asks sccache for its counters, keeps their history and
|
//! The server half of sccache-dash: it asks sccache for its counters, keeps their history and
|
||||||
//! serves the page that draws them.
|
//! serves the page that draws them.
|
||||||
|
|
||||||
|
pub mod advice;
|
||||||
pub mod app;
|
pub mod app;
|
||||||
pub mod history;
|
pub mod history;
|
||||||
pub mod http;
|
pub mod http;
|
||||||
|
|||||||
+517
-214
@@ -1,15 +1,15 @@
|
|||||||
//! Turning the saved history into the five `View`s the page draws, one per range. They are made
|
//! Turning the saved history into the five `View`s the page draws, one per range. They are made
|
||||||
//! after every poll and kept; a request never waits for the database.
|
//! after every poll and kept; a request never waits for the database.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
use sccache_dash_api::{
|
use sccache_dash_api::{
|
||||||
Bucket, Language, Problem, Range, Server, Severity, Status, TimeSaved, Timing, View,
|
Bucket, BuildTimes, Language, NotCached, Problem, Range, Server, Severity, Status, TimeSaved, Timing, View,
|
||||||
};
|
};
|
||||||
|
use sccache_dash_stats::{LanguageHits, Observation, Resampled, Saved};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::app::{State, RANGES};
|
use crate::advice;
|
||||||
use crate::history::{History, Row};
|
use crate::app::State;
|
||||||
|
use crate::history::{BucketLangs, BucketRow, History, Row};
|
||||||
use crate::pretty;
|
use crate::pretty;
|
||||||
use crate::stats::{self, Counters, CACHE_WRITE, COMPILE, HIT_READ};
|
use crate::stats::{self, Counters, CACHE_WRITE, COMPILE, HIT_READ};
|
||||||
|
|
||||||
@@ -29,6 +29,9 @@ pub mod levels {
|
|||||||
pub const RUNNING_WINDOW: Duration = Duration::from_secs(5 * 60);
|
pub const RUNNING_WINDOW: Duration = Duration::from_secs(5 * 60);
|
||||||
/// The chart has at most this many buckets.
|
/// The chart has at most this many buckets.
|
||||||
pub const BUCKETS: i64 = 120;
|
pub const BUCKETS: i64 = 120;
|
||||||
|
/// The build-time bootstrap is drawn again at most this often, however many observations
|
||||||
|
/// a build in flight keeps adding.
|
||||||
|
pub const BOOTSTRAP_EVERY_SECS: i64 = 60;
|
||||||
/// While anything changes a row comes at least this often, so a bucket with no row between
|
/// While anything changes a row comes at least this often, so a bucket with no row between
|
||||||
/// two rows further apart than this is a gap.
|
/// two rows further apart than this is a gap.
|
||||||
pub const GAP_SECS: i64 = 120;
|
pub const GAP_SECS: i64 = 120;
|
||||||
@@ -55,22 +58,224 @@ fn soft<T: Default>(result: rusqlite::Result<T>) -> T {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a compile of each language takes, from the build observations: the polls after which
|
/// All that the history says about how long a build of each language takes. The build-time data
|
||||||
/// every build that had finished was of that one language.
|
/// is the same for every range, so its bootstrap is drawn here, once per change.
|
||||||
#[derive(Default)]
|
pub struct Builds {
|
||||||
struct Learned(BTreeMap<String, (f64, u64)>);
|
/// The languages with observations, in the order their observations were given to the draws.
|
||||||
|
languages: Vec<String>,
|
||||||
|
obs: Vec<Vec<Observation>>,
|
||||||
|
/// Each language's histogram, sorted by compiles seen, largest first.
|
||||||
|
pub times: Vec<BuildTimes>,
|
||||||
|
/// Each language's average build time in seconds, when it has seen enough to be counted.
|
||||||
|
means: Vec<Option<f64>>,
|
||||||
|
draws: Resampled,
|
||||||
|
/// (how many observations there are, when the newest is dated) this was made from.
|
||||||
|
stamp: Option<(i64, i64)>,
|
||||||
|
/// When the bootstrap was last drawn.
|
||||||
|
drawn_at: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
impl Learned {
|
impl Default for Builds {
|
||||||
/// (average build time in seconds, compiles it was learned from).
|
fn default() -> Self {
|
||||||
fn build_time(&self, lang: &str) -> Option<(f64, u64)> {
|
Self::new()
|
||||||
let (seconds, n) = self.0.get(lang).filter(|(_, n)| *n > 0)?;
|
|
||||||
Some((*seconds / *n as f64, *n))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Builds {
|
||||||
|
/// Nothing learned yet.
|
||||||
|
pub fn new() -> Builds {
|
||||||
|
Builds {
|
||||||
|
languages: Vec::new(),
|
||||||
|
obs: Vec::new(),
|
||||||
|
times: Vec::new(),
|
||||||
|
means: Vec::new(),
|
||||||
|
draws: Resampled::new(&[]),
|
||||||
|
stamp: None,
|
||||||
|
drawn_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes in any observations added since the last look, and when there are some works out
|
||||||
|
/// the histograms and draws the bootstrap again: once per change, not once per range.
|
||||||
|
pub fn refresh(&mut self, h: &History, now: i64) {
|
||||||
|
let stamp = soft(h.build_obs_stamp());
|
||||||
|
if self.stamp == Some(stamp) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Observations were added, but the bootstrap was drawn less than a minute ago: they wait
|
||||||
|
// for that beat, so that a build in flight does not have it redrawn on every poll.
|
||||||
|
if self
|
||||||
|
.drawn_at
|
||||||
|
.is_some_and(|at| now - at < levels::BOOTSTRAP_EVERY_SECS)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let added = match self.stamp {
|
||||||
|
// Rows were only added: read just those.
|
||||||
|
Some((count, newest)) if stamp.0 > count && stamp.1 >= newest => {
|
||||||
|
soft(h.build_obs_after(newest))
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
self.languages.clear();
|
||||||
|
self.obs.clear();
|
||||||
|
soft(h.build_obs_after(i64::MIN))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (language, observation) in added {
|
||||||
|
let known = self.languages.iter().position(|l| *l == language);
|
||||||
|
let i = known.unwrap_or_else(|| {
|
||||||
|
self.languages.push(language.clone());
|
||||||
|
self.obs.push(Vec::new());
|
||||||
|
self.languages.len() - 1
|
||||||
|
});
|
||||||
|
self.obs[i].push(observation);
|
||||||
|
}
|
||||||
|
let mut times: Vec<BuildTimes> = self
|
||||||
|
.languages
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, l)| sccache_dash_stats::build_times(l, &self.obs[i]))
|
||||||
|
.collect();
|
||||||
|
self.means = (0..self.languages.len())
|
||||||
|
.map(|i| counted(&self.obs[i]).then_some(times[i].mean_ms / 1000.0))
|
||||||
|
.collect();
|
||||||
|
times.sort_by(|a, b| {
|
||||||
|
b.compiles
|
||||||
|
.cmp(&a.compiles)
|
||||||
|
.then_with(|| a.language.cmp(&b.language))
|
||||||
|
});
|
||||||
|
let obs: Vec<&[Observation]> = self.obs.iter().map(Vec::as_slice).collect();
|
||||||
|
self.draws = Resampled::new(&obs);
|
||||||
|
self.times = times;
|
||||||
|
self.stamp = Some(stamp);
|
||||||
|
// Drawing nothing is free, so it does not start the minute's wait: the first
|
||||||
|
// observations are drawn at the very next poll.
|
||||||
|
if stamp.0 > 0 {
|
||||||
|
self.drawn_at = Some(now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Time saved for one range's hits, from the draws already made.
|
||||||
|
fn saved(&self, hits: &[(String, [u64; 3])], hit_read: f64) -> Saved {
|
||||||
|
let mut unknown = 0;
|
||||||
|
let langs: Vec<LanguageHits<'_>> = self
|
||||||
|
.languages
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, name)| LanguageHits {
|
||||||
|
hits: hits
|
||||||
|
.iter()
|
||||||
|
.find(|(n, _)| n == name)
|
||||||
|
.map_or(0, |(_, v)| v[0]),
|
||||||
|
obs: &self.obs[i],
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
for (name, v) in hits {
|
||||||
|
if !self.languages.iter().any(|l| l == name) {
|
||||||
|
unknown += v[0];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let saved = self.draws.time_saved(&langs, hit_read);
|
||||||
|
Saved {
|
||||||
|
hits_left_out: saved.hits_left_out + unknown,
|
||||||
|
..saved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one hit of this language saves on average, for the chart; `None` when the language
|
||||||
|
/// is left out.
|
||||||
|
fn saving(&self, language: &str, hit_read: f64) -> Option<f64> {
|
||||||
|
Some(positive(
|
||||||
|
self.means[self.languages.iter().position(|l| l == language)?]? - hit_read,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the figure was reached, in plain words with the numbers used.
|
||||||
|
fn note(&self, hits: &[(String, [u64; 3])], hit_read: f64, saved: &Saved) -> String {
|
||||||
|
let counted: Vec<String> = hits
|
||||||
|
.iter()
|
||||||
|
.filter(|(name, v)| v[0] > 0 && self.saving(name, 0.0).is_some())
|
||||||
|
.map(|(name, _)| {
|
||||||
|
let i = self
|
||||||
|
.languages
|
||||||
|
.iter()
|
||||||
|
.position(|l| l == name)
|
||||||
|
.expect("a language with hits");
|
||||||
|
let t = &self
|
||||||
|
.times
|
||||||
|
.iter()
|
||||||
|
.find(|t| t.language == *name)
|
||||||
|
.expect("its histogram");
|
||||||
|
format!(
|
||||||
|
"{} {} (from {} builds)",
|
||||||
|
name,
|
||||||
|
pretty::short(self.means[i].unwrap_or(0.0)),
|
||||||
|
pretty::thousands(t.compiles)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let mut left_out: Vec<(u64, &String)> = hits
|
||||||
|
.iter()
|
||||||
|
.filter(|(name, v)| v[0] > 0 && self.saving(name, 0.0).is_none())
|
||||||
|
.map(|(name, v)| (v[0], name))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
left_out.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
|
||||||
|
let left_out: Vec<String> = left_out
|
||||||
|
.iter()
|
||||||
|
.map(|(hits, name)| format!("{} {name}", pretty::thousands(*hits)))
|
||||||
|
.collect();
|
||||||
|
if hits.iter().all(|(_, v)| v[0] == 0) {
|
||||||
|
return "There were no hits in this range, so nothing was saved.".to_owned();
|
||||||
|
}
|
||||||
|
if counted.is_empty() {
|
||||||
|
return format!(
|
||||||
|
"Nothing is counted: no language has {} build times seen yet, each the average over the builds that finished between two polls ten seconds apart. {} hits left out.",
|
||||||
|
sccache_dash_stats::MIN_OBSERVATIONS,
|
||||||
|
pretty::thousands(saved.hits_left_out)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut note = format!(
|
||||||
|
"Learned build times: {}. A hit saves that minus the {} average cache read",
|
||||||
|
counted.join(", "),
|
||||||
|
pretty::short(hit_read)
|
||||||
|
);
|
||||||
|
if let Some((lo, hi)) = saved.interval_90 {
|
||||||
|
note.push_str(&format!(
|
||||||
|
"; in 9 of 10 such draws the total falls between {} and {}",
|
||||||
|
pretty::hours_and_minutes(lo),
|
||||||
|
pretty::hours_and_minutes(hi)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
note.push('.');
|
||||||
|
if !left_out.is_empty() {
|
||||||
|
note.push_str(&format!(
|
||||||
|
" Left out: {} hits, too few build times seen to count.",
|
||||||
|
left_out.join(", ")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
note
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A saving is never negative, and never a negative zero (which JSON would print as `-0.0`).
|
||||||
|
fn positive(value: f64) -> f64 {
|
||||||
|
if value > 0.0 {
|
||||||
|
value
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a language has seen enough usable observations for its saving to be counted.
|
||||||
|
fn counted(obs: &[Observation]) -> bool {
|
||||||
|
obs.iter()
|
||||||
|
.filter(|o| o.compiles > 0 && o.seconds.is_finite() && o.seconds >= 0.0)
|
||||||
|
.count()
|
||||||
|
>= sccache_dash_stats::MIN_OBSERVATIONS
|
||||||
|
}
|
||||||
|
|
||||||
/// What every range needs the same way, gathered once per poll.
|
/// What every range needs the same way, gathered once per poll.
|
||||||
struct Known {
|
struct Known {
|
||||||
learned: Learned,
|
|
||||||
/// What the live reading adds since the last saved row, dated when it was read.
|
/// What the live reading adds since the last saved row, dated when it was read.
|
||||||
pending: Option<Row>,
|
pending: Option<Row>,
|
||||||
server: Server,
|
server: Server,
|
||||||
@@ -92,13 +297,12 @@ fn gather(h: &History, st: &State, now: i64) -> Known {
|
|||||||
.is_some_and(|p| p.delta.totals.requests > 0)
|
.is_some_and(|p| p.delta.totals.requests > 0)
|
||||||
|| soft(h.requests_since(since + 1)) > 0;
|
|| soft(h.requests_since(since + 1)) > 0;
|
||||||
Known {
|
Known {
|
||||||
learned: Learned(soft(h.build_time_totals())),
|
|
||||||
pending,
|
pending,
|
||||||
server: Server {
|
server: Server {
|
||||||
status: match live {
|
status: match (live, st.error.as_ref()) {
|
||||||
None => Status::NotRunning,
|
(None, _) | (_, Some(_)) => Status::NotRunning,
|
||||||
Some(_) if changed_recently => Status::Running,
|
(Some(_), None) if changed_recently => Status::Running,
|
||||||
Some(_) => Status::Idle,
|
(Some(_), None) => Status::Idle,
|
||||||
},
|
},
|
||||||
version: live.and_then(|l| l.snapshot.version.clone()),
|
version: live.and_then(|l| l.snapshot.version.clone()),
|
||||||
client_version: st.client_version.clone(),
|
client_version: st.client_version.clone(),
|
||||||
@@ -110,146 +314,119 @@ fn gather(h: &History, st: &State, now: i64) -> Known {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The rough, deliberately low saving: a hit counts only when the build time of its language
|
/// A language's hits and misses go into a bucket's list, and its saving into the bucket's.
|
||||||
/// is known. Also returns the average time a hit took to read, which the chart needs.
|
fn add_language(
|
||||||
fn time_saved(c: &Counters, learned: &Learned) -> (TimeSaved, f64) {
|
bucket: &mut Bucket,
|
||||||
let t = &c.totals;
|
name: &str,
|
||||||
let hit_read = if t.hits > 0 {
|
hits: u64,
|
||||||
c.ns[HIT_READ] as f64 / t.hits as f64 / 1e9
|
misses: u64,
|
||||||
} else {
|
builds: &Builds,
|
||||||
0.0
|
hit_read: f64,
|
||||||
};
|
) {
|
||||||
let (mut seconds, mut left_out, mut used, mut unknown) = (0.0, 0, Vec::new(), Vec::new());
|
match bucket.languages.iter_mut().find(|(k, _, _)| k == name) {
|
||||||
for (name, v) in &c.langs {
|
Some((_, h, m)) => {
|
||||||
if v[0] == 0 {
|
*h += hits;
|
||||||
continue;
|
*m += misses;
|
||||||
}
|
|
||||||
match learned.build_time(name) {
|
|
||||||
Some((build, compiles)) => {
|
|
||||||
seconds += v[0] as f64 * (build - hit_read).max(0.0);
|
|
||||||
used.push(format!(
|
|
||||||
"{} {} (from {} compiles)",
|
|
||||||
name,
|
|
||||||
pretty::short(build),
|
|
||||||
pretty::thousands(compiles)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
left_out += v[0];
|
|
||||||
unknown.push((v[0], name));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
None => bucket.languages.push((name.to_owned(), hits, misses)),
|
||||||
}
|
}
|
||||||
let note = if t.hits == 0 {
|
bucket.saved_seconds += hits as f64 * builds.saving(name, hit_read).unwrap_or(0.0);
|
||||||
"There were no hits in this range, so nothing was saved.".to_owned()
|
|
||||||
} else if used.is_empty() {
|
|
||||||
format!(
|
|
||||||
"Nothing is counted: no build time has been learned yet, which takes polls after which every build that finished was of one language. {} hits left out.",
|
|
||||||
pretty::thousands(left_out)
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
let mut note = format!(
|
|
||||||
"Learned build times: {}. A hit saves that minus the {} average cache read.",
|
|
||||||
used.join(", "),
|
|
||||||
pretty::short(hit_read)
|
|
||||||
);
|
|
||||||
if left_out > 0 {
|
|
||||||
unknown.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(b.1)));
|
|
||||||
let names: Vec<String> = unknown
|
|
||||||
.iter()
|
|
||||||
.map(|(hits, name)| format!("{} {name}", pretty::thousands(*hits)))
|
|
||||||
.collect();
|
|
||||||
note.push_str(&format!(
|
|
||||||
" Left out: {} hits ({}), no build time learned for them yet.",
|
|
||||||
pretty::thousands(left_out),
|
|
||||||
names.join(", ")
|
|
||||||
));
|
|
||||||
}
|
|
||||||
note
|
|
||||||
};
|
|
||||||
(
|
|
||||||
TimeSaved {
|
|
||||||
seconds,
|
|
||||||
hits_left_out: left_out,
|
|
||||||
note,
|
|
||||||
interval_90: None,
|
|
||||||
},
|
|
||||||
hit_read,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The chart: at most [`levels::BUCKETS`] buckets from `from` up to and including `to`, each
|
/// What the chart of one range is drawn from: the rows and languages SQLite added up per
|
||||||
/// holding the rows dated in it. `live` says the service is running now, so `to` itself was seen.
|
/// bucket of `chart.len` seconds from `chart.from`, and the live reading.
|
||||||
fn buckets(
|
struct Chart<'a> {
|
||||||
rows: &[&Row],
|
rows: &'a [BucketRow],
|
||||||
langs: &[(i64, String, u64, u64)],
|
langs: &'a [BucketLangs],
|
||||||
|
pending: Option<&'a Row>,
|
||||||
from: i64,
|
from: i64,
|
||||||
to: i64,
|
len: i64,
|
||||||
learned: &Learned,
|
}
|
||||||
hit_read: f64,
|
|
||||||
live: bool,
|
/// The chart: at most [`levels::BUCKETS`] buckets up to and including `now`. `live` says the
|
||||||
) -> Vec<Bucket> {
|
/// service is running now, so `now` itself was seen.
|
||||||
let span = (to - from).max(1);
|
fn buckets(chart: Chart<'_>, now: i64, builds: &Builds, hit_read: f64, live: bool) -> Vec<Bucket> {
|
||||||
let len = (span + levels::BUCKETS - 1) / levels::BUCKETS;
|
let count = (((now - chart.from).max(1) + chart.len - 1) / chart.len) as usize;
|
||||||
let count = ((span + len - 1) / len) as usize;
|
// The last bucket takes the moment `now` itself, which is always the live reading.
|
||||||
// The last bucket takes the moment `to` itself, which is always the live reading.
|
let bucket_of = |t: i64| (((t - chart.from) / chart.len) as usize).min(count - 1);
|
||||||
let bucket_of = |t: i64| (((t - from) / len) as usize).min(count - 1);
|
|
||||||
let mut out: Vec<Bucket> = (0..count as i64)
|
let mut out: Vec<Bucket> = (0..count as i64)
|
||||||
.map(|i| Bucket {
|
.map(|i| Bucket {
|
||||||
start: from + i * len,
|
start: chart.from + i * chart.len,
|
||||||
gap: true,
|
gap: true,
|
||||||
..Bucket::default()
|
..Bucket::default()
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
for row in rows {
|
let add = |b: &mut Bucket, hits: u64, misses: u64, other: u64, errors: u64, reset: bool| {
|
||||||
if row.t < from || row.t > to {
|
b.reset |= reset;
|
||||||
continue;
|
b.hits += hits;
|
||||||
}
|
b.misses += misses;
|
||||||
let b = &mut out[bucket_of(row.t)];
|
b.other += other;
|
||||||
let t = &row.delta.totals;
|
b.errors += errors;
|
||||||
b.reset |= row.reset;
|
};
|
||||||
b.hits += t.hits;
|
for r in chart.rows {
|
||||||
b.misses += t.misses;
|
add(
|
||||||
b.other += t.not_cacheable + t.unsupported_compiler + t.not_compile;
|
&mut out[(r.b.max(0) as usize).min(count - 1)],
|
||||||
b.errors += t.errors();
|
r.hits,
|
||||||
|
r.misses,
|
||||||
|
r.other,
|
||||||
|
r.errors,
|
||||||
|
r.reset,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
for (t, name, hits, misses) in langs {
|
for l in chart.langs {
|
||||||
if *t < from || *t > to {
|
add_language(
|
||||||
continue;
|
&mut out[(l.b.max(0) as usize).min(count - 1)],
|
||||||
|
&l.language,
|
||||||
|
l.hits,
|
||||||
|
l.misses,
|
||||||
|
builds,
|
||||||
|
hit_read,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(p) = chart.pending.filter(|p| p.t >= chart.from && p.t <= now) {
|
||||||
|
let t = &p.delta.totals;
|
||||||
|
add(
|
||||||
|
&mut out[bucket_of(p.t)],
|
||||||
|
t.hits,
|
||||||
|
t.misses,
|
||||||
|
t.not_cacheable + t.unsupported_compiler + t.not_compile,
|
||||||
|
t.errors(),
|
||||||
|
p.reset,
|
||||||
|
);
|
||||||
|
for (name, v) in &p.delta.langs {
|
||||||
|
add_language(&mut out[bucket_of(p.t)], name, v[0], v[1], builds, hit_read);
|
||||||
}
|
}
|
||||||
let b = &mut out[bucket_of(*t)];
|
|
||||||
match b.languages.iter_mut().find(|(k, _, _)| k == name) {
|
|
||||||
Some((_, h, m)) => {
|
|
||||||
*h += hits;
|
|
||||||
*m += misses;
|
|
||||||
}
|
|
||||||
None => b.languages.push((name.clone(), *hits, *misses)),
|
|
||||||
}
|
|
||||||
b.saved_seconds += *hits as f64
|
|
||||||
* learned
|
|
||||||
.build_time(name)
|
|
||||||
.map_or(0.0, |(build, _)| (build - hit_read).max(0.0));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// A bucket is open when a row falls in it, or when it lies between rows less than two
|
// A bucket is open when a row falls in it, or when it lies between rows less than two
|
||||||
// minutes apart: rows come every minute while anything changes.
|
// minutes apart: rows come every minute while anything changes.
|
||||||
let mut times: Vec<i64> = rows
|
let mut first = vec![None::<i64>; count];
|
||||||
.iter()
|
let mut last = vec![None::<i64>; count];
|
||||||
.map(|r| r.t)
|
for r in chart.rows {
|
||||||
.filter(|&t| t >= from && t <= to)
|
let i = (r.b.max(0) as usize).min(count - 1);
|
||||||
.collect();
|
if first[i].is_none_or(|f| r.first < f) {
|
||||||
if live {
|
first[i] = Some(r.first);
|
||||||
times.push(to);
|
|
||||||
}
|
|
||||||
for &t in × {
|
|
||||||
out[bucket_of(t)].gap = false;
|
|
||||||
}
|
|
||||||
for w in times.windows(2) {
|
|
||||||
if w[1] - w[0] <= levels::GAP_SECS {
|
|
||||||
for b in &mut out[bucket_of(w[0])..bucket_of(w[1])] {
|
|
||||||
b.gap = false;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
if last[i].is_none_or(|l| r.last > l) {
|
||||||
|
last[i] = Some(r.last);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut previous = None;
|
||||||
|
for i in 0..count {
|
||||||
|
if let Some(l) = last[i] {
|
||||||
|
out[i].gap = false;
|
||||||
|
previous = Some(l);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let next = (i + 1..count)
|
||||||
|
.find_map(|j| first[j])
|
||||||
|
.or_else(|| live.then_some(now));
|
||||||
|
out[i].gap = !previous
|
||||||
|
.zip(next)
|
||||||
|
.is_some_and(|(p, n)| n - p <= levels::GAP_SECS);
|
||||||
|
}
|
||||||
|
if live {
|
||||||
|
out[count - 1].gap = false;
|
||||||
}
|
}
|
||||||
for b in &mut out {
|
for b in &mut out {
|
||||||
b.languages.sort_by(|a, b| a.0.cmp(&b.0));
|
b.languages.sort_by(|a, b| a.0.cmp(&b.0));
|
||||||
@@ -257,6 +434,34 @@ fn buckets(
|
|||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a low hit rate means and what to try. Everything said about why a Rust compile misses
|
||||||
|
/// is what sccache 0.18.0's hash key for Rust (src/compiler/rust.rs, `generate_hash_key`) is
|
||||||
|
/// made of, and was checked by building the same crate twice, in two directories, through a
|
||||||
|
/// throwaway server.
|
||||||
|
fn low_hit_rate_detail(name: &str, hits: u64, n: u64, reasons: &[NotCached]) -> String {
|
||||||
|
let mut text = format!(
|
||||||
|
"Only {}% of {} {name} compiles came from the cache.",
|
||||||
|
pretty::pct(hits as f64 / n as f64),
|
||||||
|
pretty::thousands(n)
|
||||||
|
);
|
||||||
|
if let Some((lost, top)) = advice::fixable_loss(reasons) {
|
||||||
|
text.push_str(&format!(
|
||||||
|
" Another {} were skipped for reasons you can fix, mostly \"{}\" ({}): see \"Why compiles were not cacheable\".",
|
||||||
|
pretty::thousands(lost),
|
||||||
|
top.name,
|
||||||
|
pretty::thousands(top.count),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if name == "Rust" {
|
||||||
|
text.push_str(
|
||||||
|
" A Rust compile misses when the folder it is built in, the compiler version, the flags or a CARGO_* variable differ from last time, so the same crate built in two folders (two git worktrees, or a different CARGO_TARGET_DIR variable) is built twice.",
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
text.push_str(" sccache's counters do not say why a compile missed.");
|
||||||
|
}
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
fn problems(c: &Counters, server: &Server) -> Vec<Problem> {
|
fn problems(c: &Counters, server: &Server) -> Vec<Problem> {
|
||||||
let t = &c.totals;
|
let t = &c.totals;
|
||||||
let (mut errors, mut warnings) = (Vec::new(), Vec::new());
|
let (mut errors, mut warnings) = (Vec::new(), Vec::new());
|
||||||
@@ -316,15 +521,12 @@ fn problems(c: &Counters, server: &Server) -> Vec<Problem> {
|
|||||||
.map(|(name, v)| (name, v[0], v[0] + v[1]))
|
.map(|(name, v)| (name, v[0], v[0] + v[1]))
|
||||||
.collect();
|
.collect();
|
||||||
low.sort_by(|a, b| (a.1 * b.2).cmp(&(b.1 * a.2)).then_with(|| a.0.cmp(b.0)));
|
low.sort_by(|a, b| (a.1 * b.2).cmp(&(b.1 * a.2)).then_with(|| a.0.cmp(b.0)));
|
||||||
|
let reasons = advice::describe(&c.not_cached);
|
||||||
for (name, hits, n) in low {
|
for (name, hits, n) in low {
|
||||||
warnings.push(problem(
|
warnings.push(problem(
|
||||||
Severity::Warning,
|
Severity::Warning,
|
||||||
format!("{name} hit rate {}%", pretty::pct(hits as f64 / n as f64)),
|
format!("{name} hit rate {}%", pretty::pct(hits as f64 / n as f64)),
|
||||||
format!(
|
low_hit_rate_detail(name, hits, n, &reasons),
|
||||||
"Only {}% of {} {name} compiles came from the cache, so most were rebuilt; a different toolchain, compiler flags or environment makes sccache miss, so compare those between two builds.",
|
|
||||||
pretty::pct(hits as f64 / n as f64),
|
|
||||||
pretty::thousands(n)
|
|
||||||
),
|
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
|
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
|
||||||
@@ -359,13 +561,7 @@ fn problems(c: &Counters, server: &Server) -> Vec<Problem> {
|
|||||||
/// The text "Copy Summary" puts on the clipboard.
|
/// The text "Copy Summary" puts on the clipboard.
|
||||||
pub fn summary(view: &View) -> String {
|
pub fn summary(view: &View) -> String {
|
||||||
let t = &view.totals;
|
let t = &view.totals;
|
||||||
let range = match view.range {
|
let range = view.range.map_or("", Range::label);
|
||||||
Some(Range::Hour) => "last hour",
|
|
||||||
Some(Range::Day) => "last 24 hours",
|
|
||||||
Some(Range::Week) => "last 7 days",
|
|
||||||
Some(Range::Month) => "last 30 days",
|
|
||||||
_ => "since last reset",
|
|
||||||
};
|
|
||||||
let hit_rate = match t.hit_rate() {
|
let hit_rate = match t.hit_rate() {
|
||||||
Some(r) => format!(
|
Some(r) => format!(
|
||||||
"{}% ({} of {} compiles from cache)",
|
"{}% ({} of {} compiles from cache)",
|
||||||
@@ -403,8 +599,16 @@ pub fn summary(view: &View) -> String {
|
|||||||
pretty::thousands(t.timeouts),
|
pretty::thousands(t.timeouts),
|
||||||
);
|
);
|
||||||
if view.time_saved.seconds > 0.0 {
|
if view.time_saved.seconds > 0.0 {
|
||||||
|
let interval = match view.time_saved.interval_90 {
|
||||||
|
Some((lo, hi)) => format!(
|
||||||
|
"; 90% range {} \u{2013} {}",
|
||||||
|
pretty::hours_and_minutes(lo),
|
||||||
|
pretty::hours_and_minutes(hi)
|
||||||
|
),
|
||||||
|
None => String::new(),
|
||||||
|
};
|
||||||
s += &format!(
|
s += &format!(
|
||||||
"- Time saved: ~{} (rough)\n",
|
"- Time saved: ~{} (rough{interval})\n",
|
||||||
pretty::hours_and_minutes(view.time_saved.seconds)
|
pretty::hours_and_minutes(view.time_saved.seconds)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -426,9 +630,16 @@ pub fn summary(view: &View) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Makes the view for one range.
|
/// Makes the view for one range.
|
||||||
fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> View {
|
fn compute(
|
||||||
|
h: &History,
|
||||||
|
builds: &Builds,
|
||||||
|
st: &State,
|
||||||
|
known: &Known,
|
||||||
|
range: Range,
|
||||||
|
now: i64,
|
||||||
|
) -> View {
|
||||||
let live = st.live.as_ref();
|
let live = st.live.as_ref();
|
||||||
// When the chart starts: at the last zeroing for `reset`, a range's length back otherwise.
|
// When the chart starts: a range's length back, or at the last zeroing for `reset`.
|
||||||
let from = match range {
|
let from = match range {
|
||||||
Range::SinceReset => soft(h.last_reset())
|
Range::SinceReset => soft(h.last_reset())
|
||||||
.or_else(|| soft(h.first_row()))
|
.or_else(|| soft(h.first_row()))
|
||||||
@@ -440,8 +651,7 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
|
|||||||
} else {
|
} else {
|
||||||
now + 1
|
now + 1
|
||||||
};
|
};
|
||||||
// The saved rows are read once: they make the totals and the chart, so the two always agree.
|
let len = ((now - from).max(1) + levels::BUCKETS - 1) / levels::BUCKETS;
|
||||||
let saved = soft(h.rows(from, to));
|
|
||||||
let (counters, previous) = match range {
|
let (counters, previous) = match range {
|
||||||
// The counters as they are.
|
// The counters as they are.
|
||||||
Range::SinceReset => (
|
Range::SinceReset => (
|
||||||
@@ -449,32 +659,19 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
|
|||||||
None,
|
None,
|
||||||
),
|
),
|
||||||
_ => {
|
_ => {
|
||||||
let mut counters = Counters::default();
|
let mut counters = soft(h.sums(from, to)).unwrap_or_default();
|
||||||
for row in &saved {
|
|
||||||
counters.add(&row.delta);
|
|
||||||
}
|
|
||||||
counters.langs = soft(h.languages(from, to));
|
counters.langs = soft(h.languages(from, to));
|
||||||
counters.not_cached = soft(h.reasons(from, to));
|
counters.not_cached = soft(h.reasons(from, to));
|
||||||
if let Some(pending) = &known.pending {
|
if let Some(pending) = &known.pending {
|
||||||
counters.add(&pending.delta);
|
counters.add(&pending.delta);
|
||||||
}
|
}
|
||||||
// The period of the same length just before: one indexed SUM.
|
// The period of the same length just before: one indexed SUM.
|
||||||
(counters, soft(h.sums(now - 2 * length(range), from)))
|
(
|
||||||
|
counters,
|
||||||
|
soft(h.sums(now - 2 * length(range), from)).map(|p| p.totals),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let mut chart: Vec<&Row> = saved.iter().collect();
|
|
||||||
let mut langs = soft(h.language_rows(from, to));
|
|
||||||
if let Some(pending) = &known.pending {
|
|
||||||
chart.push(pending);
|
|
||||||
langs.extend(
|
|
||||||
pending
|
|
||||||
.delta
|
|
||||||
.langs
|
|
||||||
.iter()
|
|
||||||
.map(|(name, v)| (pending.t, name.clone(), v[0], v[1])),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let t = &counters.totals;
|
let t = &counters.totals;
|
||||||
let per = |total_ns: u64, n: u64| (n > 0).then(|| total_ns as f64 / n as f64 / 1e6);
|
let per = |total_ns: u64, n: u64| (n > 0).then(|| total_ns as f64 / n as f64 / 1e6);
|
||||||
let timing = Timing {
|
let timing = Timing {
|
||||||
@@ -482,7 +679,16 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
|
|||||||
avg_cache_write_ms: per(counters.ns[CACHE_WRITE], t.cache_writes),
|
avg_cache_write_ms: per(counters.ns[CACHE_WRITE], t.cache_writes),
|
||||||
avg_compile_ms: per(counters.ns[COMPILE], counters.compilations),
|
avg_compile_ms: per(counters.ns[COMPILE], counters.compilations),
|
||||||
};
|
};
|
||||||
let (time_saved, hit_read) = time_saved(&counters, &known.learned);
|
let hit_read = per(counters.ns[HIT_READ], t.hits).unwrap_or(0.0) / 1e3;
|
||||||
|
let saved = builds.saved(&counters.langs, hit_read);
|
||||||
|
let time_saved = TimeSaved {
|
||||||
|
seconds: positive(saved.seconds),
|
||||||
|
hits_left_out: saved.hits_left_out,
|
||||||
|
interval_90: saved
|
||||||
|
.interval_90
|
||||||
|
.map(|(lo, hi)| (positive(lo), positive(hi))),
|
||||||
|
note: builds.note(&counters.langs, hit_read, &saved),
|
||||||
|
};
|
||||||
let mut languages: Vec<Language> = counters
|
let mut languages: Vec<Language> = counters
|
||||||
.langs
|
.langs
|
||||||
.iter()
|
.iter()
|
||||||
@@ -498,8 +704,7 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
|
|||||||
.cmp(&(a.hits + a.misses))
|
.cmp(&(a.hits + a.misses))
|
||||||
.then_with(|| a.name.cmp(&b.name))
|
.then_with(|| a.name.cmp(&b.name))
|
||||||
});
|
});
|
||||||
let mut not_cached = counters.not_cached.clone();
|
let not_cached = advice::describe(&counters.not_cached);
|
||||||
not_cached.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
|
||||||
|
|
||||||
let mut view = View {
|
let mut view = View {
|
||||||
range: Some(range),
|
range: Some(range),
|
||||||
@@ -513,29 +718,33 @@ fn compute(h: &History, known: &Known, st: &State, range: Range, now: i64) -> Vi
|
|||||||
languages,
|
languages,
|
||||||
not_cached,
|
not_cached,
|
||||||
buckets: buckets(
|
buckets: buckets(
|
||||||
&chart,
|
Chart {
|
||||||
&langs,
|
rows: &soft(h.bucket_rows(from, len, to)),
|
||||||
from,
|
langs: &soft(h.bucket_languages(from, len, to)),
|
||||||
|
pending: known.pending.as_ref(),
|
||||||
|
from,
|
||||||
|
len,
|
||||||
|
},
|
||||||
now,
|
now,
|
||||||
&known.learned,
|
builds,
|
||||||
hit_read,
|
hit_read,
|
||||||
live.is_some(),
|
live.is_some(),
|
||||||
),
|
),
|
||||||
extras: live.map_or_else(Vec::new, |l| stats::extras(&l.snapshot)),
|
extras: live.map_or_else(Vec::new, |l| stats::extras(&l.snapshot)),
|
||||||
raw: st.raw.clone().unwrap_or(Value::Null),
|
raw: st.raw.clone().unwrap_or(Value::Null),
|
||||||
summary_markdown: String::new(),
|
summary_markdown: String::new(),
|
||||||
build_times: Vec::new(),
|
build_times: builds.times.clone(),
|
||||||
};
|
};
|
||||||
view.summary_markdown = summary(&view);
|
view.summary_markdown = summary(&view);
|
||||||
view
|
view
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The five views, one per range of [`RANGES`], made after every poll.
|
/// The five views, one per range, made after every poll.
|
||||||
pub fn all(h: &History, st: &State, now: i64) -> Vec<View> {
|
pub fn all(h: &History, builds: &Builds, st: &State, now: i64) -> Vec<View> {
|
||||||
let known = gather(h, st, now);
|
let known = gather(h, st, now);
|
||||||
RANGES
|
Range::ALL
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&range| compute(h, &known, st, range, now))
|
.map(|&range| compute(h, builds, st, &known, range, now))
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -554,6 +763,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
|
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
|
||||||
|
const NOW: i64 = 100_000;
|
||||||
|
|
||||||
/// A reading with these totals, all of it Rust, taking 1 s per hit read, 1 s per cache
|
/// A reading with these totals, all of it Rust, taking 1 s per hit read, 1 s per cache
|
||||||
/// write and 60 s per compile.
|
/// write and 60 s per compile.
|
||||||
@@ -583,13 +793,15 @@ mod tests {
|
|||||||
/// A saved history with a state, as the service has them.
|
/// A saved history with a state, as the service has them.
|
||||||
struct Scene {
|
struct Scene {
|
||||||
history: History,
|
history: History,
|
||||||
|
builds: Builds,
|
||||||
state: State,
|
state: State,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Scene {
|
impl Scene {
|
||||||
fn view(&self, range: Range, now: i64) -> View {
|
fn view(&self, range: Range, now: i64) -> View {
|
||||||
all(&self.history, &self.state, now)[RANGES.iter().position(|r| *r == range).unwrap()]
|
all(&self.history, &self.builds, &self.state, now)
|
||||||
.clone()
|
[Range::ALL.iter().position(|r| *r == range).unwrap()]
|
||||||
|
.clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -611,7 +823,13 @@ mod tests {
|
|||||||
raw_text: text.to_owned(),
|
raw_text: text.to_owned(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Scene { history, state }
|
let mut builds = Builds::new();
|
||||||
|
builds.refresh(&history, NOW);
|
||||||
|
Scene {
|
||||||
|
history,
|
||||||
|
builds,
|
||||||
|
state,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The readings, with a live reading at `at` that saw nothing change since the last of them.
|
/// The readings, with a live reading at `at` that saw nothing change since the last of them.
|
||||||
@@ -859,11 +1077,15 @@ mod tests {
|
|||||||
errors: 0
|
errors: 0
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
let order: Vec<&str> = v.not_cached.iter().map(|r| r.reason.as_str()).collect();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
v.not_cached[0],
|
order,
|
||||||
("crate-type".to_owned(), 621),
|
["incremental", "multiple input files", "crate-type", "-o", "-", "missing input", "missing emit"],
|
||||||
"largest reason first"
|
"reasons you can fix first, then the expected ones, each largest first"
|
||||||
);
|
);
|
||||||
|
assert_eq!((v.not_cached[0].count, v.not_cached[0].fixable), (105, true));
|
||||||
|
assert_eq!(v.not_cached[2].count, 621);
|
||||||
|
assert!(!v.not_cached[2].fixable);
|
||||||
assert_eq!(v.raw, serde_json::from_str::<Value>(LIVE).unwrap());
|
assert_eq!(v.raw, serde_json::from_str::<Value>(LIVE).unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -933,24 +1155,25 @@ mod tests {
|
|||||||
};
|
};
|
||||||
let history = History::memory().unwrap();
|
let history = History::memory().unwrap();
|
||||||
let mut tracker = Tracker::default();
|
let mut tracker = Tracker::default();
|
||||||
for (t, misses) in [(0, 0), (10, 1), (70, 2), (130, 3)] {
|
for step in 0..12 {
|
||||||
|
let (t, misses) = (step * 10, step as u64);
|
||||||
history.record(&mut tracker, &taught(misses), t).unwrap();
|
history.record(&mut tracker, &taught(misses), t).unwrap();
|
||||||
}
|
}
|
||||||
let mut c = stats::parse(LIVE).unwrap().counters;
|
let mut c = stats::parse(LIVE).unwrap().counters;
|
||||||
c.langs = vec![
|
c.langs = vec![
|
||||||
("Assembler".to_owned(), [733, 0, 0]),
|
("Assembler".to_owned(), [733, 0, 0]),
|
||||||
("C/C++".to_owned(), [2082, 0, 0]),
|
("C/C++".to_owned(), [2082, 0, 0]),
|
||||||
("Rust".to_owned(), [229, 3, 0]),
|
("Rust".to_owned(), [229, 11, 0]),
|
||||||
];
|
];
|
||||||
c.totals = Totals {
|
c.totals = Totals {
|
||||||
requests: 3047,
|
requests: 3055,
|
||||||
hits: 3044,
|
hits: 3044,
|
||||||
misses: 3,
|
misses: 11,
|
||||||
cache_writes: 3,
|
cache_writes: 11,
|
||||||
..Totals::default()
|
..Totals::default()
|
||||||
};
|
};
|
||||||
c.compilations = 3;
|
c.compilations = 11;
|
||||||
c.ns = [3_044 * 500_000_000, 3_000_000_000, 3 * 60_000_000_000];
|
c.ns = [3_044 * 500_000_000, 11_000_000_000, 11 * 60_000_000_000];
|
||||||
let snapshot = stats::Snapshot {
|
let snapshot = stats::Snapshot {
|
||||||
counters: c,
|
counters: c,
|
||||||
..stats::parse(LIVE).unwrap()
|
..stats::parse(LIVE).unwrap()
|
||||||
@@ -959,7 +1182,13 @@ mod tests {
|
|||||||
tracker: history.tracker(),
|
tracker: history.tracker(),
|
||||||
..State::default()
|
..State::default()
|
||||||
};
|
};
|
||||||
let mut scene = Scene { history, state };
|
let mut builds = Builds::new();
|
||||||
|
builds.refresh(&history, NOW);
|
||||||
|
let mut scene = Scene {
|
||||||
|
history,
|
||||||
|
builds,
|
||||||
|
state,
|
||||||
|
};
|
||||||
scene.state.live = Some(Live {
|
scene.state.live = Some(Live {
|
||||||
at: 240,
|
at: 240,
|
||||||
snapshot,
|
snapshot,
|
||||||
@@ -977,7 +1206,7 @@ mod tests {
|
|||||||
assert_eq!(ts.hits_left_out, 2082 + 733);
|
assert_eq!(ts.hits_left_out, 2082 + 733);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
ts.note,
|
ts.note,
|
||||||
"Learned build times: Rust 60 s (from 3 compiles). A hit saves that minus the 500 ms average cache read. Left out: 2,815 hits (2,082 C/C++, 733 Assembler), no build time learned for them yet."
|
"Learned build times: Rust 60 s (from 11 builds). A hit saves that minus the 500 ms average cache read; in 9 of 10 such draws the total falls between 3h 47m and 3h 47m. Left out: 2,082 C/C++, 733 Assembler hits, too few build times seen to count."
|
||||||
);
|
);
|
||||||
assert_eq!(v.timing.avg_hit_read_ms, Some(500.0));
|
assert_eq!(v.timing.avg_hit_read_ms, Some(500.0));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -993,6 +1222,62 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_empty_range_saves_exactly_zero_never_a_negative_zero() {
|
||||||
|
let c = |misses: u64| Counters {
|
||||||
|
totals: Totals {
|
||||||
|
requests: misses,
|
||||||
|
misses,
|
||||||
|
cache_writes: misses,
|
||||||
|
..Totals::default()
|
||||||
|
},
|
||||||
|
compilations: misses,
|
||||||
|
ns: [0, 0, misses * 60_000_000_000],
|
||||||
|
langs: vec![("Rust".to_owned(), [0, misses, 0])],
|
||||||
|
..Counters::default()
|
||||||
|
};
|
||||||
|
// Twelve polls after each of which one Rust build finished: enough to count Rust. Then a
|
||||||
|
// live reading with no hit anywhere.
|
||||||
|
let history = History::memory().unwrap();
|
||||||
|
let mut tracker = Tracker::default();
|
||||||
|
for step in 0..12u64 {
|
||||||
|
history
|
||||||
|
.record(&mut tracker, &c(step), (step * 10) as i64)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let live = Live {
|
||||||
|
at: 130,
|
||||||
|
snapshot: stats::Snapshot {
|
||||||
|
counters: c(11),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
raw_text: String::new(),
|
||||||
|
};
|
||||||
|
let state = State {
|
||||||
|
tracker: history.tracker(),
|
||||||
|
live: Some(live),
|
||||||
|
..State::default()
|
||||||
|
};
|
||||||
|
let mut builds = Builds::new();
|
||||||
|
builds.refresh(&history, 130);
|
||||||
|
assert_eq!(builds.times[0].compiles, 11, "Rust is counted");
|
||||||
|
|
||||||
|
let views = all(&history, &builds, &state, 130);
|
||||||
|
for (range, v) in Range::ALL.iter().zip(&views) {
|
||||||
|
let ts = &v.time_saved;
|
||||||
|
assert_eq!((ts.seconds, ts.hits_left_out), (0.0, 0), "{range:?}");
|
||||||
|
assert!(!ts.seconds.is_sign_negative(), "{range:?}: {}", ts.seconds);
|
||||||
|
let json = serde_json::to_string(ts).unwrap();
|
||||||
|
assert!(!json.contains('-'), "{range:?}: no minus sign in {json}");
|
||||||
|
assert!(
|
||||||
|
v.buckets
|
||||||
|
.iter()
|
||||||
|
.all(|b| b.saved_seconds == 0.0 && !b.saved_seconds.is_sign_negative()),
|
||||||
|
"{range:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn time_saved_is_zero_and_explained_when_nothing_is_learned() {
|
fn time_saved_is_zero_and_explained_when_nothing_is_learned() {
|
||||||
let assembler = |hits: u64| Counters {
|
let assembler = |hits: u64| Counters {
|
||||||
@@ -1032,7 +1317,7 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
ts.note
|
ts.note
|
||||||
.starts_with("Nothing is counted: no build time has been learned yet"),
|
.starts_with("Nothing is counted: no language has 10 build times seen yet"),
|
||||||
"{}",
|
"{}",
|
||||||
ts.note
|
ts.note
|
||||||
);
|
);
|
||||||
@@ -1060,12 +1345,12 @@ mod tests {
|
|||||||
let v = taught().view(Range::Day, 240);
|
let v = taught().view(Range::Day, 240);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
v.totals.hit_rate(),
|
v.totals.hit_rate(),
|
||||||
Some(3044.0 / 3047.0),
|
Some(3044.0 / 3055.0),
|
||||||
"hits out of cacheable compiles"
|
"hits out of cacheable compiles"
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
v.totals.hit_rate_of_all(),
|
v.totals.hit_rate_of_all(),
|
||||||
Some(3044.0 / 3047.0),
|
Some(3044.0 / 3055.0),
|
||||||
"here every request was a cacheable compile"
|
"here every request was a cacheable compile"
|
||||||
);
|
);
|
||||||
let mixed = Totals {
|
let mixed = Totals {
|
||||||
@@ -1084,10 +1369,10 @@ mod tests {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
v.summary_markdown,
|
v.summary_markdown,
|
||||||
"**sccache, last 24 hours**\n\
|
"**sccache, last 24 hours**\n\
|
||||||
- Hit rate: 99.9% (3,044 of 3,047 compiles from cache)\n\
|
- Hit rate: 99.6% (3,044 of 3,055 compiles from cache)\n\
|
||||||
- By language: C/C++ 100%, Assembler 100%, Rust 98.7%\n\
|
- By language: C/C++ 100%, Assembler 100%, Rust 95.4%\n\
|
||||||
- Not cacheable: 0 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\
|
- Not cacheable: 0 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\
|
||||||
- Time saved: ~3h 47m (rough)\n\
|
- Time saved: ~3h 47m (rough; 90% range 3h 47m \u{2013} 3h 47m)\n\
|
||||||
- Cache: local disk, 10.0 of 10.0 GB \u{b7} sccache 0.18.0\n"
|
- Cache: local disk, 10.0 of 10.0 GB \u{b7} sccache 0.18.0\n"
|
||||||
);
|
);
|
||||||
assert!(taught()
|
assert!(taught()
|
||||||
@@ -1107,7 +1392,7 @@ mod tests {
|
|||||||
plain.state.client_version = Some("0.18.0".to_owned());
|
plain.state.client_version = Some("0.18.0".to_owned());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
plain.view(Range::SinceReset, 100).summary_markdown,
|
plain.view(Range::SinceReset, 100).summary_markdown,
|
||||||
"**sccache, since last reset**\n\
|
"**sccache, since reset**\n\
|
||||||
- Hit rate: 49.5% (3,197 of 6,453 compiles from cache)\n\
|
- Hit rate: 49.5% (3,197 of 6,453 compiles from cache)\n\
|
||||||
- By language: Rust 6.6%, C/C++ 100%, Assembler 100%\n\
|
- By language: Rust 6.6%, C/C++ 100%, Assembler 100%\n\
|
||||||
- Not cacheable: 856 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\
|
- Not cacheable: 856 \u{b7} Errors: 0 \u{b7} Timeouts: 0\n\
|
||||||
@@ -1194,7 +1479,24 @@ mod tests {
|
|||||||
);
|
);
|
||||||
assert!(rate(vec![("Rust", [4, 46, 0])]).problems[0]
|
assert!(rate(vec![("Rust", [4, 46, 0])]).problems[0]
|
||||||
.detail
|
.detail
|
||||||
.starts_with("Only 8% of 50 Rust compiles came from the cache, so most were rebuilt;"));
|
.starts_with("Only 8% of 50 Rust compiles came from the cache."));
|
||||||
|
let detail = seen(
|
||||||
|
|s| {
|
||||||
|
s.counters.langs = vec![("Rust".to_owned(), [4, 46, 0])];
|
||||||
|
s.counters.not_cached = vec![("incremental".to_owned(), 30), ("crate-type".to_owned(), 90)];
|
||||||
|
},
|
||||||
|
"0.18.0",
|
||||||
|
)
|
||||||
|
.problems[0]
|
||||||
|
.detail
|
||||||
|
.clone();
|
||||||
|
assert!(
|
||||||
|
detail.contains("Another 30 were skipped for reasons you can fix")
|
||||||
|
&& detail.contains("\"Incremental compilation is on\" (30)")
|
||||||
|
&& detail.contains("the folder it is built in")
|
||||||
|
&& !detail.contains("Programs and libraries"),
|
||||||
|
"{detail}"
|
||||||
|
);
|
||||||
assert!(
|
assert!(
|
||||||
rate(vec![("Rust", [19, 30, 0])]).problems.is_empty(),
|
rate(vec![("Rust", [19, 30, 0])]).problems.is_empty(),
|
||||||
"49 compiles is too few to say"
|
"49 compiles is too few to say"
|
||||||
@@ -1289,8 +1591,9 @@ mod tests {
|
|||||||
assert!(
|
assert!(
|
||||||
all.problems
|
all.problems
|
||||||
.iter()
|
.iter()
|
||||||
.all(|p| p.detail.split(". ").count() == 1 && p.detail.ends_with('.')),
|
.all(|p| p.detail.ends_with('.')
|
||||||
"each detail is one sentence: {:?}",
|
&& (p.title.contains("hit rate") || p.detail.split(". ").count() == 1)),
|
||||||
|
"each detail is one sentence, except the hit-rate one that says what to change: {:?}",
|
||||||
all.problems
|
all.problems
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+484
-48
@@ -7,10 +7,10 @@ use std::path::PathBuf;
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::thread;
|
use std::thread;
|
||||||
|
|
||||||
use sccache_dash::app::{unix_now, App, Config};
|
use sccache_dash::app::{unix_now, App, Config, Probe, Prober, Task};
|
||||||
use sccache_dash::history::History;
|
use sccache_dash::history::History;
|
||||||
use sccache_dash::stats;
|
use sccache_dash::stats;
|
||||||
use sccache_dash_api::{Range, Status, Totals, View};
|
use sccache_dash_api::{Range, Severity, Status, Totals, View};
|
||||||
|
|
||||||
const LIVE: &str = include_str!("../../../fixtures/live-0.18.0.json");
|
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 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\"}";
|
||||||
@@ -36,6 +36,7 @@ printf '%s\n' "$*" >> "$0.log"
|
|||||||
case "$1" in
|
case "$1" in
|
||||||
--version) echo 'sccache 0.18.0' ;;
|
--version) echo 'sccache 0.18.0' ;;
|
||||||
--zero-stats) cp "$0.zeroed" "$0.out" ;;
|
--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" ;;
|
*) cat "$0.out" ;;
|
||||||
esac
|
esac
|
||||||
"#,
|
"#,
|
||||||
@@ -43,6 +44,8 @@ esac
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).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.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();
|
std::fs::write(dir.path().join("sccache.zeroed"), ZEROED).unwrap();
|
||||||
Fake {
|
Fake {
|
||||||
log: dir.path().join("sccache.log"),
|
log: dir.path().join("sccache.log"),
|
||||||
@@ -66,25 +69,44 @@ esac
|
|||||||
.collect()
|
.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 {
|
fn config(&self) -> Config {
|
||||||
Config {
|
Config {
|
||||||
sccache: self.script.clone().into(),
|
sccache: self.script.clone().into(),
|
||||||
history: self.history.clone(),
|
history: self.history.clone(),
|
||||||
|
start_sccache: true,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A server on a free port next to an empty history, polled once, answering in the background.
|
/// 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.
|
/// The test stands in for the polling task: it holds the history and polls by hand.
|
||||||
fn start(fake: &Fake) -> (Arc<App>, History, SocketAddr) {
|
fn start(fake: &Fake) -> (Arc<App>, Task, SocketAddr) {
|
||||||
let app = Arc::new(App::new(fake.config()));
|
let app = Arc::new(App::with_probe(fake.config(), fake.probe()));
|
||||||
let history = History::memory().unwrap();
|
let mut task = Task::memory();
|
||||||
app.poll_at(&history, NOW);
|
task.poll(&app, NOW);
|
||||||
let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
|
let server = tiny_http::Server::http("127.0.0.1:0").unwrap();
|
||||||
let addr = server.server_addr().to_ip().unwrap();
|
let addr = server.server_addr().to_ip().unwrap();
|
||||||
let answering = Arc::clone(&app);
|
let answering = Arc::clone(&app);
|
||||||
thread::spawn(move || sccache_dash::http::answer(server, answering));
|
thread::spawn(move || sccache_dash::http::answer(server, answering));
|
||||||
(app, history, addr)
|
(app, task, addr)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends one raw request (`{port}` stands for the server's port) and returns the whole response.
|
/// Sends one raw request (`{port}` stands for the server's port) and returns the whole response.
|
||||||
@@ -119,7 +141,7 @@ fn zero(addr: SocketAddr, host: Option<&str>, origin: Option<&str>) -> (u16, Str
|
|||||||
#[test]
|
#[test]
|
||||||
fn zero_is_refused_for_a_foreign_origin_or_host() {
|
fn zero_is_refused_for_a_foreign_origin_or_host() {
|
||||||
let fake = Fake::new();
|
let fake = Fake::new();
|
||||||
let (app, history, addr) = start(&fake);
|
let (app, task, addr) = start(&fake);
|
||||||
|
|
||||||
// A page anywhere else, in any shape: a bare host, another port, or "null".
|
// A page anywhere else, in any shape: a bare host, another port, or "null".
|
||||||
for origin in [
|
for origin in [
|
||||||
@@ -154,7 +176,7 @@ fn zero_is_refused_for_a_foreign_origin_or_host() {
|
|||||||
fake.calls()
|
fake.calls()
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
history.row_count().unwrap(),
|
task.history.row_count().unwrap(),
|
||||||
0,
|
0,
|
||||||
"and nothing was written to the history"
|
"and nothing was written to the history"
|
||||||
);
|
);
|
||||||
@@ -167,7 +189,7 @@ fn zero_is_refused_for_a_foreign_origin_or_host() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
|
fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
|
||||||
let fake = Fake::new();
|
let fake = Fake::new();
|
||||||
let (app, history, addr) = start(&fake);
|
let (app, mut task, addr) = start(&fake);
|
||||||
|
|
||||||
let (code, response) = zero(
|
let (code, response) = zero(
|
||||||
addr,
|
addr,
|
||||||
@@ -186,24 +208,25 @@ fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// What the polling task then does, woken by the request: it reads the counters again.
|
// What the polling task then does, woken by the request: it reads the counters again.
|
||||||
app.poll_at(&history, unix_now());
|
task.poll(&app, unix_now());
|
||||||
let calls = fake.calls();
|
let calls = fake.calls();
|
||||||
assert_eq!(calls.iter().filter(|c| *c == "--zero-stats").count(), 2);
|
assert_eq!(calls.iter().filter(|c| *c == "--zero-stats").count(), 2);
|
||||||
assert_eq!(calls.last().unwrap(), "--show-stats --stats-format json");
|
assert_eq!(calls.last().unwrap(), "--show-stats --stats-format json");
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
history.row_count().unwrap(),
|
task.history.row_count().unwrap(),
|
||||||
1,
|
1,
|
||||||
"the history stays, and the zeroing is one more row"
|
"the history stays, and the zeroing is one more row"
|
||||||
);
|
);
|
||||||
let row = &history.rows(0, i64::MAX).unwrap()[0];
|
assert!(
|
||||||
assert!(row.reset, "the zeroing shows in the history as a reset");
|
task.history.last_reset().unwrap().is_some(),
|
||||||
|
"the zeroing shows in the history as a reset"
|
||||||
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
row.delta,
|
task.history.sums(0, i64::MAX).unwrap(),
|
||||||
stats::Counters::default(),
|
Some(stats::Counters::default()),
|
||||||
"nothing has been compiled since"
|
"nothing has been compiled since"
|
||||||
);
|
);
|
||||||
assert_eq!(history.last_reset().unwrap(), Some(row.t));
|
|
||||||
|
|
||||||
let v = app.view(Range::SinceReset);
|
let v = app.view(Range::SinceReset);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -221,7 +244,7 @@ fn zero_from_the_dashboard_zeroes_sccache_and_keeps_the_history() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn view_export_and_the_page_answer() {
|
fn view_export_and_the_page_answer() {
|
||||||
let fake = Fake::new();
|
let fake = Fake::new();
|
||||||
let (_app, _history, addr) = start(&fake);
|
let (_app, _task, addr) = start(&fake);
|
||||||
|
|
||||||
let response = send(addr, &format!("GET /api/view?range=reset{GET}"));
|
let response = send(addr, &format!("GET /api/view?range=reset{GET}"));
|
||||||
assert!(
|
assert!(
|
||||||
@@ -243,9 +266,7 @@ fn view_export_and_the_page_answer() {
|
|||||||
),
|
),
|
||||||
(Some("0.18.0"), Some("0.18.0"))
|
(Some("0.18.0"), Some("0.18.0"))
|
||||||
);
|
);
|
||||||
assert!(v
|
assert!(v.summary_markdown.starts_with("**sccache, since reset**\n"));
|
||||||
.summary_markdown
|
|
||||||
.starts_with("**sccache, since last reset**\n"));
|
|
||||||
for range in ["1h", "24h", "7d", "30d"] {
|
for range in ["1h", "24h", "7d", "30d"] {
|
||||||
let response = send(addr, &format!("GET /api/view?range={range}{GET}"));
|
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();
|
let v: View = serde_json::from_str(response.split("\r\n\r\n").nth(1).unwrap()).unwrap();
|
||||||
@@ -287,38 +308,54 @@ fn view_export_and_the_page_answer() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() {
|
fn rows_are_saved_when_counters_change_and_at_most_once_a_minute() {
|
||||||
let fake = Fake::new();
|
let fake = Fake::new();
|
||||||
let app = App::new(fake.config());
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
let history = History::memory().unwrap();
|
let mut task = Task::memory();
|
||||||
let rows = || history.row_count().unwrap();
|
|
||||||
|
|
||||||
app.poll_at(&history, NOW);
|
task.poll(&app, NOW);
|
||||||
assert_eq!(rows(), 0, "the first reading is a baseline, not a row");
|
assert_eq!(
|
||||||
app.poll_at(&history, NOW + 10);
|
task.history.row_count().unwrap(),
|
||||||
assert_eq!(rows(), 0, "nothing changed");
|
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"));
|
fake.answers(&LIVE.replace("\"compile_requests\":7351", "\"compile_requests\":7352"));
|
||||||
app.poll_at(&history, NOW + 30);
|
task.poll(&app, NOW + 30);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
rows(),
|
task.history.row_count().unwrap(),
|
||||||
0,
|
0,
|
||||||
"changed, but less than a minute after the baseline"
|
"changed, but less than a minute after the baseline"
|
||||||
);
|
);
|
||||||
app.poll_at(&history, NOW + 60);
|
task.poll(&app, NOW + 60);
|
||||||
assert_eq!(rows(), 1, "a minute on, the change is saved");
|
|
||||||
let row = &history.rows(0, i64::MAX).unwrap()[0];
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
(row.t, row.delta.totals.requests, row.reset),
|
task.history.row_count().unwrap(),
|
||||||
(NOW + 60, 1, false)
|
1,
|
||||||
|
"a minute on, the change is saved"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
task.history
|
||||||
|
.sums(0, i64::MAX)
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.totals
|
||||||
|
.requests,
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
task.history.last_reset().unwrap(),
|
||||||
|
None,
|
||||||
|
"a change is not a reset"
|
||||||
);
|
);
|
||||||
|
|
||||||
app.poll_at(&history, NOW + 700);
|
task.poll(&app, NOW + 700);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
rows(),
|
task.history.row_count().unwrap(),
|
||||||
1,
|
1,
|
||||||
"unchanged: nothing more is saved, however long the quiet lasts"
|
"unchanged: nothing more is saved, however long the quiet lasts"
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
history.build_observations().unwrap().is_empty(),
|
task.history.build_obs_stamp().unwrap() == (0, 0),
|
||||||
"and with no misses there is no build observation"
|
"and with no misses there is no build observation"
|
||||||
);
|
);
|
||||||
assert_eq!(app.lock().views.len(), 5, "every poll makes the five views");
|
assert_eq!(app.lock().views.len(), 5, "every poll makes the five views");
|
||||||
@@ -354,9 +391,11 @@ fn the_history_survives_a_restart_in_its_file() {
|
|||||||
let mut c = b.clone();
|
let mut c = b.clone();
|
||||||
c.totals.requests += 5;
|
c.totals.requests += 5;
|
||||||
history.record(&mut tracker, &c, NOW + 70).unwrap();
|
history.record(&mut tracker, &c, NOW + 70).unwrap();
|
||||||
let rows = history.rows(0, i64::MAX).unwrap();
|
assert_eq!(history.row_count().unwrap(), 1);
|
||||||
assert_eq!(rows.len(), 1);
|
assert_eq!(
|
||||||
assert_eq!((rows[0].t, rows[0].delta.totals.requests), (NOW + 70, 5));
|
history.sums(0, i64::MAX).unwrap().unwrap().totals.requests,
|
||||||
|
5
|
||||||
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
app.view(Range::Day).range,
|
app.view(Range::Day).range,
|
||||||
Some(Range::Day),
|
Some(Range::Day),
|
||||||
@@ -392,13 +431,12 @@ fn old_rows_are_deleted_at_startup() {
|
|||||||
1,
|
1,
|
||||||
"the one row older than 30 days"
|
"the one row older than 30 days"
|
||||||
);
|
);
|
||||||
let left: Vec<i64> = history
|
assert_eq!(history.row_count().unwrap(), 3);
|
||||||
.rows(0, i64::MAX)
|
assert_eq!(
|
||||||
.unwrap()
|
history.first_row().unwrap(),
|
||||||
.iter()
|
Some(NOW - 30 * day + 3600),
|
||||||
.map(|r| r.t)
|
"the oldest row left"
|
||||||
.collect();
|
);
|
||||||
assert_eq!(left, vec![NOW - 30 * day + 3600, NOW - 3600, NOW]);
|
|
||||||
assert_eq!(history.prune(NOW).unwrap(), 0, "nothing more to delete");
|
assert_eq!(history.prune(NOW).unwrap(), 0, "nothing more to delete");
|
||||||
assert!(
|
assert!(
|
||||||
fake.history.with_extension("db-wal").exists()
|
fake.history.with_extension("db-wal").exists()
|
||||||
@@ -406,3 +444,401 @@ fn old_rows_are_deleted_at_startup() {
|
|||||||
"WAL mode is on"
|
"WAL mode is on"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_missing_sccache_server_is_left_alone_unless_starting_was_asked_for() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
fake.down();
|
||||||
|
let app = App::with_probe(
|
||||||
|
Config {
|
||||||
|
start_sccache: false,
|
||||||
|
..fake.config()
|
||||||
|
},
|
||||||
|
fake.probe(),
|
||||||
|
);
|
||||||
|
let mut task = Task::memory();
|
||||||
|
|
||||||
|
task.poll(&app, NOW);
|
||||||
|
task.poll(&app, NOW + 120);
|
||||||
|
let calls = fake.calls();
|
||||||
|
assert!(!calls.iter().any(|c| c == "--start-server"), "{calls:?}");
|
||||||
|
assert!(app
|
||||||
|
.lock()
|
||||||
|
.error
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|e| e.contains("your next build starts it")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_missing_sccache_server_is_started_once_then_read() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
fake.down();
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::memory();
|
||||||
|
|
||||||
|
task.poll(&app, NOW);
|
||||||
|
let calls = fake.calls();
|
||||||
|
assert_eq!(
|
||||||
|
calls.iter().filter(|c| *c == "--start-server").count(),
|
||||||
|
1,
|
||||||
|
"{calls:?}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
calls.last().unwrap(),
|
||||||
|
"--show-stats --stats-format json",
|
||||||
|
"the counters are read again after starting"
|
||||||
|
);
|
||||||
|
let v = app.view(Range::SinceReset);
|
||||||
|
assert_eq!(v.server.status, Status::Idle, "{:?}", v.server.error);
|
||||||
|
assert_eq!(
|
||||||
|
v.totals,
|
||||||
|
stats::parse(LIVE).unwrap().counters.totals,
|
||||||
|
"the started server's counters, not the empty ones"
|
||||||
|
);
|
||||||
|
|
||||||
|
task.poll(&app, NOW + 10);
|
||||||
|
assert_eq!(
|
||||||
|
fake.calls()
|
||||||
|
.iter()
|
||||||
|
.filter(|c| *c == "--start-server")
|
||||||
|
.count(),
|
||||||
|
1,
|
||||||
|
"not started again while it is running"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_server_that_will_not_start_is_reported_and_not_retried_for_a_minute() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
fake.down();
|
||||||
|
std::fs::write(fake.dir.path().join("sccache.no-start"), "").unwrap();
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::memory();
|
||||||
|
|
||||||
|
for at in [NOW, NOW + 10, NOW + 50] {
|
||||||
|
task.poll(&app, at);
|
||||||
|
let v = app.view(Range::Day);
|
||||||
|
assert_eq!(v.server.status, Status::NotRunning, "polled at {at}");
|
||||||
|
assert!(
|
||||||
|
v.server
|
||||||
|
.error
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|e| e.contains("`sccache --start-server` failed")),
|
||||||
|
"{:?}",
|
||||||
|
v.server.error
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
v.problems
|
||||||
|
.iter()
|
||||||
|
.any(|p| p.severity == Severity::Error && p.title == "sccache is not running"),
|
||||||
|
"{:?}",
|
||||||
|
v.problems
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
fake.calls()
|
||||||
|
.iter()
|
||||||
|
.filter(|c| *c == "--start-server")
|
||||||
|
.count(),
|
||||||
|
1,
|
||||||
|
"tried once"
|
||||||
|
);
|
||||||
|
task.poll(&app, NOW + 60);
|
||||||
|
assert_eq!(
|
||||||
|
fake.calls()
|
||||||
|
.iter()
|
||||||
|
.filter(|c| *c == "--start-server")
|
||||||
|
.count(),
|
||||||
|
2,
|
||||||
|
"and again a minute later"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Meanwhile the server came up by itself (a compile started it): no more error. Its counters
|
||||||
|
// differ from the empty ones, so that counts as compiles having arrived.
|
||||||
|
std::fs::write(fake.dir.path().join("sccache.running"), "").unwrap();
|
||||||
|
fake.answers(LIVE);
|
||||||
|
task.poll(&app, NOW + 70);
|
||||||
|
assert_eq!(app.view(Range::Day).server.status, Status::Running);
|
||||||
|
assert_eq!(app.view(Range::Day).server.error, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The real output with `more` more Rust builds in it: that many more requests, misses and compiles.
|
||||||
|
fn with_more_rust_builds(more: u64) -> String {
|
||||||
|
let text = LIVE.replace(
|
||||||
|
"\"compile_requests\":7351",
|
||||||
|
&format!("\"compile_requests\":{}", 7351 + more),
|
||||||
|
);
|
||||||
|
let text = text.replace("\"Rust\":3256", &format!("\"Rust\":{}", 3256 + more));
|
||||||
|
let text = text.replace("\"rust\":3256", &format!("\"rust\":{}", 3256 + more));
|
||||||
|
let text = text.replace(
|
||||||
|
"\"compilations\":3256",
|
||||||
|
&format!("\"compilations\":{}", 3256 + more),
|
||||||
|
);
|
||||||
|
let text = text.replace(
|
||||||
|
"\"cache_writes\":3256",
|
||||||
|
&format!("\"cache_writes\":{}", 3256 + more),
|
||||||
|
);
|
||||||
|
text.replace(
|
||||||
|
"\"compiler_write_duration\":{\"secs\":25343",
|
||||||
|
&format!(
|
||||||
|
"\"compiler_write_duration\":{{\"secs\":{}",
|
||||||
|
25343 + 8 * more
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_bootstrap_is_not_redrawn_on_every_poll_of_a_build_in_flight() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::memory();
|
||||||
|
let rust_builds = |app: &App| {
|
||||||
|
app.view(Range::Day)
|
||||||
|
.build_times
|
||||||
|
.first()
|
||||||
|
.map_or(0, |t| t.compiles)
|
||||||
|
};
|
||||||
|
task.poll(&app, NOW);
|
||||||
|
assert_eq!(rust_builds(&app), 0, "nothing seen yet");
|
||||||
|
|
||||||
|
// A build adds one Rust build between every pair of polls. Each is stored at once. The first
|
||||||
|
// is drawn at the next poll (the empty draw before it started no wait); the rest wait for
|
||||||
|
// the one-minute beat that began with that draw.
|
||||||
|
for step in 1..7u64 {
|
||||||
|
fake.answers(&with_more_rust_builds(step));
|
||||||
|
task.poll(&app, NOW + (step as i64) * 10);
|
||||||
|
assert_eq!(
|
||||||
|
task.history.build_obs_stamp().unwrap().0,
|
||||||
|
step as i64,
|
||||||
|
"observation {step} is stored at once"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
rust_builds(&app),
|
||||||
|
1,
|
||||||
|
"the first draw stands for the minute (step {step})"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
fake.answers(&with_more_rust_builds(7));
|
||||||
|
task.poll(&app, NOW + 70);
|
||||||
|
assert_eq!(
|
||||||
|
rust_builds(&app),
|
||||||
|
7,
|
||||||
|
"a minute after the last draw, everything seen so far is drawn in"
|
||||||
|
);
|
||||||
|
|
||||||
|
fake.answers(&with_more_rust_builds(8));
|
||||||
|
task.poll(&app, NOW + 80);
|
||||||
|
assert_eq!(
|
||||||
|
rust_builds(&app),
|
||||||
|
7,
|
||||||
|
"and it stands again until the next beat"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_full_history_costs_few_rows_on_the_second_poll() {
|
||||||
|
// Thirty days with a row every minute: the most there can ever be. Two languages miss most
|
||||||
|
// minutes, so only one minute in ten gives a build observation.
|
||||||
|
let fake = Fake::new();
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::memory();
|
||||||
|
let day = 86_400;
|
||||||
|
let mut c = stats::Counters::default();
|
||||||
|
let mut readings = Vec::new();
|
||||||
|
for step in 0..43_200i64 {
|
||||||
|
let (rust, cxx) = if step % 10 == 0 { (2, 0) } else { (1, 1) };
|
||||||
|
c.totals.requests += 10;
|
||||||
|
c.totals.executed += 8;
|
||||||
|
c.totals.hits += 6;
|
||||||
|
c.totals.misses += rust + cxx;
|
||||||
|
c.totals.not_cacheable += 2;
|
||||||
|
c.totals.cache_writes += rust + cxx;
|
||||||
|
c.compilations += rust + cxx;
|
||||||
|
c.ns = [
|
||||||
|
c.ns[0] + 6 * 10_000_000,
|
||||||
|
c.ns[1] + (rust + cxx) * 1_000_000_000,
|
||||||
|
c.ns[2] + (rust + cxx) * 8_000_000_000,
|
||||||
|
];
|
||||||
|
c.langs = vec![
|
||||||
|
("Assembler".to_owned(), [2, 0, 0]),
|
||||||
|
("C/C++".to_owned(), [4, cxx, 0]),
|
||||||
|
("Rust".to_owned(), [0, rust, 0]),
|
||||||
|
];
|
||||||
|
readings.push((NOW - 30 * day + step * 60, c.clone()));
|
||||||
|
}
|
||||||
|
task.history.fill(&readings).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
task.history.row_count().unwrap(),
|
||||||
|
43_199,
|
||||||
|
"the first reading is the baseline"
|
||||||
|
);
|
||||||
|
let observations = task.history.build_obs_stamp().unwrap().0;
|
||||||
|
assert_eq!(
|
||||||
|
observations, 4_319,
|
||||||
|
"one for every tenth minute after the baseline"
|
||||||
|
);
|
||||||
|
|
||||||
|
task.poll(&app, NOW);
|
||||||
|
let first = app.lock().views_rows;
|
||||||
|
task.poll(&app, NOW + 10);
|
||||||
|
let second = app.lock().views_rows;
|
||||||
|
eprintln!("rows handed out: first poll {first} (reading {observations} build observations once), second poll {second}");
|
||||||
|
assert!(
|
||||||
|
first >= observations as usize,
|
||||||
|
"the first poll reads every observation once"
|
||||||
|
);
|
||||||
|
assert!(second < 3_000, "the second poll handed out {second} rows");
|
||||||
|
let v = app.view(Range::Day);
|
||||||
|
assert_eq!(v.buckets.len(), 120);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What sccache prints after `k` more rounds of work: every round adds 3 requests, 2 hits and
|
||||||
|
/// 1 Rust miss that took 5 s to compile.
|
||||||
|
fn after_rounds(k: u64) -> String {
|
||||||
|
let mut v: serde_json::Value = serde_json::from_str(LIVE).unwrap();
|
||||||
|
let s = &mut v["stats"];
|
||||||
|
let add = |s: &mut serde_json::Value, key: &str, n: u64| {
|
||||||
|
s[key] = (s[key].as_u64().unwrap() + n).into();
|
||||||
|
};
|
||||||
|
add(s, "compile_requests", 3 * k);
|
||||||
|
add(s, "requests_executed", k);
|
||||||
|
add(s, "cache_writes", k);
|
||||||
|
add(s, "compilations", k);
|
||||||
|
s["cache_hits"]["counts"]["Rust"] = (229 + 2 * k).into();
|
||||||
|
s["cache_misses"]["counts"]["Rust"] = (3256 + k).into();
|
||||||
|
let secs = 25343 + 5 * k;
|
||||||
|
s["compiler_write_duration"]["secs"] = secs.into();
|
||||||
|
v.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Polls once a `step` seconds from `from` to `to`, the counters rising a round each time.
|
||||||
|
fn run_polls(
|
||||||
|
fake: &Fake,
|
||||||
|
app: &App,
|
||||||
|
task: &mut Task,
|
||||||
|
rounds: &mut u64,
|
||||||
|
span: (i64, i64),
|
||||||
|
step: i64,
|
||||||
|
) {
|
||||||
|
let mut t = span.0;
|
||||||
|
while t <= span.1 {
|
||||||
|
fake.answers(&after_rounds(*rounds));
|
||||||
|
task.poll(app, t);
|
||||||
|
*rounds += 1;
|
||||||
|
t += step;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_restart_loses_nothing_and_counts_nothing_twice() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let mut rounds = 0;
|
||||||
|
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::open(&fake.history, NOW).unwrap();
|
||||||
|
// Five minutes of polls, every ten seconds, with work in each; the last 30 s after a row.
|
||||||
|
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 330), 10);
|
||||||
|
let before = app.view(Range::Day);
|
||||||
|
assert!(before.totals.requests > 0, "{:?}", before.totals);
|
||||||
|
assert!(
|
||||||
|
task.history.row_count().unwrap() >= 4,
|
||||||
|
"a row a minute on disk while it runs, not at the end: {}",
|
||||||
|
task.history.row_count().unwrap()
|
||||||
|
);
|
||||||
|
drop(task);
|
||||||
|
drop(app);
|
||||||
|
|
||||||
|
// The restart: a new process opens the same file and polls once, ten seconds later, with
|
||||||
|
// the same counters sccache had (no work in between).
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::open(&fake.history, NOW + 340).unwrap();
|
||||||
|
rounds -= 1;
|
||||||
|
run_polls(
|
||||||
|
&fake,
|
||||||
|
&app,
|
||||||
|
&mut task,
|
||||||
|
&mut rounds,
|
||||||
|
(NOW + 340, NOW + 340),
|
||||||
|
10,
|
||||||
|
);
|
||||||
|
let after = app.view(Range::Day);
|
||||||
|
assert_eq!(
|
||||||
|
(after.totals, after.previous),
|
||||||
|
(before.totals, before.previous),
|
||||||
|
"a view's totals are the same just before and just after a restart"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_restart_counts_the_work_done_while_it_was_down() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let mut rounds = 0;
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::open(&fake.history, NOW).unwrap();
|
||||||
|
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 200), 10);
|
||||||
|
let before = app.view(Range::Day).totals.requests;
|
||||||
|
drop(task);
|
||||||
|
drop(app);
|
||||||
|
|
||||||
|
// sccache went on working for 4 rounds while sccache-dash was stopped.
|
||||||
|
rounds += 3;
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::open(&fake.history, NOW + 260).unwrap();
|
||||||
|
run_polls(
|
||||||
|
&fake,
|
||||||
|
&app,
|
||||||
|
&mut task,
|
||||||
|
&mut rounds,
|
||||||
|
(NOW + 260, NOW + 260),
|
||||||
|
10,
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
app.view(Range::Day).totals.requests,
|
||||||
|
before + 4 * 3,
|
||||||
|
"the difference since the last poll before the stop is counted, once"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn build_times_show_within_a_minute_of_the_observations() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let mut rounds = 0;
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::open(&fake.history, NOW).unwrap();
|
||||||
|
// The first poll draws the (empty) bootstrap; the observations come after it.
|
||||||
|
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 600), 10);
|
||||||
|
let shown = |t: &Task| t.history.build_obs_stamp().unwrap().0;
|
||||||
|
assert!(shown(&task) >= 50, "observations were recorded");
|
||||||
|
let times = app.view(Range::Day).build_times;
|
||||||
|
assert_eq!(times.len(), 1, "Rust has a histogram after ten minutes");
|
||||||
|
|
||||||
|
// Stop polling for work: after one more poll a minute on, the newest are in too.
|
||||||
|
let seen = times[0].compiles;
|
||||||
|
run_polls(
|
||||||
|
&fake,
|
||||||
|
&app,
|
||||||
|
&mut task,
|
||||||
|
&mut rounds,
|
||||||
|
(NOW + 610, NOW + 680),
|
||||||
|
10,
|
||||||
|
);
|
||||||
|
let now = app.view(Range::Day).build_times[0].compiles;
|
||||||
|
assert!(now > seen, "the histogram keeps up: {seen} then {now}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_first_observations_show_at_the_next_poll_not_a_minute_later() {
|
||||||
|
let fake = Fake::new();
|
||||||
|
let mut rounds = 0;
|
||||||
|
let app = App::with_probe(fake.config(), fake.probe());
|
||||||
|
let mut task = Task::open(&fake.history, NOW).unwrap();
|
||||||
|
// The first poll draws nothing: there is nothing to draw, and that must not start the
|
||||||
|
// minute's wait for the first real observations.
|
||||||
|
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 30), 10);
|
||||||
|
assert!(task.history.build_obs_stamp().unwrap().0 >= 3);
|
||||||
|
assert_eq!(
|
||||||
|
app.view(Range::Day).build_times.len(),
|
||||||
|
1,
|
||||||
|
"seconds after the first observation, not a minute"
|
||||||
|
);
|
||||||
|
}
|
||||||
+166
-74
@@ -140,87 +140,135 @@ pub struct Saved {
|
|||||||
/// may not hold (cached compiles may be larger or smaller than the typical
|
/// may not hold (cached compiles may be larger or smaller than the typical
|
||||||
/// miss); nor does it cover errors in `hits` or `hit_read_seconds`, or any
|
/// miss); nor does it cover errors in `hits` or `hit_read_seconds`, or any
|
||||||
/// drift in build times over time.
|
/// drift in build times over time.
|
||||||
|
///
|
||||||
|
/// Several sets of hits over the same observations (one per range, say) should
|
||||||
|
/// go through [`Resampled`] instead: it draws the bootstrap once.
|
||||||
pub fn time_saved(langs: &[LanguageHits], hit_read_seconds: f64) -> Saved {
|
pub fn time_saved(langs: &[LanguageHits], hit_read_seconds: f64) -> Saved {
|
||||||
let hit_read = if hit_read_seconds.is_finite() && hit_read_seconds > 0.0 {
|
let obs: Vec<&[Observation]> = langs.iter().map(|l| l.obs).collect();
|
||||||
hit_read_seconds
|
Resampled::new(&obs).time_saved(langs, hit_read_seconds)
|
||||||
} else {
|
}
|
||||||
0.0
|
|
||||||
};
|
/// The bootstrap drawn once for a set of languages, so that the time saved for
|
||||||
let mut left_out = 0u64;
|
/// several sets of hits can be worked out from the same draws: the build times
|
||||||
// (hits, (compiles, seconds) pairs) for counted languages.
|
/// seen are the same for every set, only the hits differ.
|
||||||
let mut counted: Vec<(f64, Vec<(f64, f64)>)> = Vec::new();
|
#[derive(Debug)]
|
||||||
for l in langs {
|
pub struct Resampled {
|
||||||
let data: Vec<(f64, f64)> = l
|
/// Per replicate, per language: the resampled (compiles, seconds). A language
|
||||||
.obs
|
/// with too little data has zeros there and is left out.
|
||||||
.iter()
|
replicates: Vec<Vec<(f64, f64)>>,
|
||||||
.filter(|o| usable(o))
|
/// Whether each language has enough observations to be counted.
|
||||||
.map(|o| (o.compiles as f64, o.seconds))
|
counted: Vec<bool>,
|
||||||
.collect();
|
}
|
||||||
if data.len() < MIN_OBSERVATIONS {
|
|
||||||
left_out = left_out.saturating_add(l.hits);
|
impl Resampled {
|
||||||
|
/// Resamples every language that has [`MIN_OBSERVATIONS`] usable observations.
|
||||||
|
pub fn new(obs_per_language: &[&[Observation]]) -> Resampled {
|
||||||
|
let data: Vec<Vec<(f64, f64)>> = obs_per_language.iter().map(|obs| points(obs)).collect();
|
||||||
|
let counted: Vec<bool> = data.iter().map(|d| d.len() >= MIN_OBSERVATIONS).collect();
|
||||||
|
let mut rng = Rng(SEED);
|
||||||
|
let mut replicates = Vec::with_capacity(REPLICATES);
|
||||||
|
for _ in 0..REPLICATES {
|
||||||
|
replicates.push(data.iter().map(|d| resample(d, &mut rng)).collect());
|
||||||
|
}
|
||||||
|
Resampled {
|
||||||
|
replicates,
|
||||||
|
counted,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`time_saved`] for one set of hits, from the draws already made. `langs`
|
||||||
|
/// must give each language in the order its observations were given to
|
||||||
|
/// [`new`](Resampled::new); the slices need not be the same ones.
|
||||||
|
pub fn time_saved(&self, langs: &[LanguageHits<'_>], hit_read_seconds: f64) -> Saved {
|
||||||
|
let hit_read = if hit_read_seconds.is_finite() && hit_read_seconds > 0.0 {
|
||||||
|
hit_read_seconds
|
||||||
} else {
|
} else {
|
||||||
counted.push((l.hits as f64, data));
|
0.0
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let saving = |hits: f64, c: f64, s: f64| hits * (s / c - hit_read).max(0.0);
|
|
||||||
let seconds: f64 = counted
|
|
||||||
.iter()
|
|
||||||
.map(|(h, d)| {
|
|
||||||
let (c, s) = sums(d.iter());
|
|
||||||
saving(*h, c, s)
|
|
||||||
})
|
|
||||||
.sum();
|
|
||||||
|
|
||||||
if counted.is_empty() {
|
|
||||||
return Saved {
|
|
||||||
seconds,
|
|
||||||
interval_90: None,
|
|
||||||
hits_left_out: left_out,
|
|
||||||
};
|
};
|
||||||
}
|
let saving = |hits: f64, c: f64, s: f64| hits * (s / c - hit_read).max(0.0);
|
||||||
|
let counted = |i: usize| langs.get(i).is_some_and(|_| self.counted[i]);
|
||||||
let mut rng = Rng(SEED);
|
let mut left_out = 0u64;
|
||||||
let mut totals: Vec<f64> = Vec::with_capacity(REPLICATES);
|
let seconds: f64 = langs
|
||||||
for _ in 0..REPLICATES {
|
.iter()
|
||||||
let mut total = 0.0;
|
.enumerate()
|
||||||
for (h, d) in &counted {
|
.filter(|(i, _)| counted(*i))
|
||||||
if *h == 0.0 {
|
.map(|(_, l)| {
|
||||||
continue;
|
let d = points(l.obs);
|
||||||
|
let (c, s) = sums(d.iter());
|
||||||
|
saving(l.hits as f64, c, s)
|
||||||
|
})
|
||||||
|
.sum();
|
||||||
|
for (i, l) in langs.iter().enumerate() {
|
||||||
|
if !counted(i) {
|
||||||
|
left_out = left_out.saturating_add(l.hits);
|
||||||
}
|
}
|
||||||
let n = d.len() as u64;
|
|
||||||
// Two 32-bit draws per 64-bit output; (r * n) >> 32 is in 0..n.
|
|
||||||
// Two independent accumulator pairs keep the adds from chaining.
|
|
||||||
let pick = |r: u64| d[((r * n) >> 32) as usize];
|
|
||||||
let (mut c, mut s) = (0.0, 0.0);
|
|
||||||
let (mut c2, mut s2) = (0.0, 0.0);
|
|
||||||
for _ in 0..d.len() / 2 {
|
|
||||||
let x = rng.next();
|
|
||||||
let (dc, ds) = pick(x >> 32);
|
|
||||||
let (ec, es) = pick(x & 0xFFFF_FFFF);
|
|
||||||
c += dc;
|
|
||||||
s += ds;
|
|
||||||
c2 += ec;
|
|
||||||
s2 += es;
|
|
||||||
}
|
|
||||||
if d.len() % 2 == 1 {
|
|
||||||
let (dc, ds) = pick(rng.next() >> 32);
|
|
||||||
c += dc;
|
|
||||||
s += ds;
|
|
||||||
}
|
|
||||||
let (c, s) = (c + c2, s + s2);
|
|
||||||
total += saving(*h, c, s);
|
|
||||||
}
|
}
|
||||||
totals.push(total);
|
if langs.is_empty() || !self.counted.iter().take(langs.len()).any(|c| *c) {
|
||||||
|
return Saved {
|
||||||
|
seconds,
|
||||||
|
interval_90: None,
|
||||||
|
hits_left_out: left_out,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let mut totals: Vec<f64> = self
|
||||||
|
.replicates
|
||||||
|
.iter()
|
||||||
|
.map(|replicate| {
|
||||||
|
langs
|
||||||
|
.iter()
|
||||||
|
.zip(replicate)
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(i, _)| counted(*i))
|
||||||
|
.map(|(_, (l, (c, s)))| saving(l.hits as f64, *c, *s))
|
||||||
|
.sum()
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
totals.sort_unstable_by(|a, b| a.total_cmp(b));
|
||||||
|
let lo = totals[REPLICATES / 20].min(seconds);
|
||||||
|
let hi = totals[REPLICATES - REPLICATES / 20 - 1].max(seconds);
|
||||||
|
Saved {
|
||||||
|
seconds,
|
||||||
|
interval_90: Some((lo, hi)),
|
||||||
|
hits_left_out: left_out,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
totals.sort_unstable_by(|a, b| a.total_cmp(b));
|
}
|
||||||
let lo = totals[REPLICATES / 20].min(seconds);
|
|
||||||
let hi = totals[REPLICATES - REPLICATES / 20 - 1].max(seconds);
|
/// The usable observations of a language as (compiles, seconds).
|
||||||
Saved {
|
fn points(obs: &[Observation]) -> Vec<(f64, f64)> {
|
||||||
seconds,
|
obs.iter()
|
||||||
interval_90: Some((lo, hi)),
|
.filter(|o| usable(o))
|
||||||
hits_left_out: left_out,
|
.map(|o| (o.compiles as f64, o.seconds))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One bootstrap replicate of a language: its observations drawn with replacement, summed.
|
||||||
|
/// A language with too little data draws nothing.
|
||||||
|
fn resample(data: &[(f64, f64)], rng: &mut Rng) -> (f64, f64) {
|
||||||
|
if data.len() < MIN_OBSERVATIONS {
|
||||||
|
return (0.0, 0.0);
|
||||||
}
|
}
|
||||||
|
let n = data.len() as u64;
|
||||||
|
// Two 32-bit draws per 64-bit output; (r * n) >> 32 is in 0..n.
|
||||||
|
// Two independent accumulator pairs keep the adds from chaining.
|
||||||
|
let pick = |r: u64| data[((r * n) >> 32) as usize];
|
||||||
|
let (mut c, mut s) = (0.0, 0.0);
|
||||||
|
let (mut c2, mut s2) = (0.0, 0.0);
|
||||||
|
for _ in 0..data.len() / 2 {
|
||||||
|
let x = rng.next();
|
||||||
|
let (dc, ds) = pick(x >> 32);
|
||||||
|
let (ec, es) = pick(x & 0xFFFF_FFFF);
|
||||||
|
c += dc;
|
||||||
|
s += ds;
|
||||||
|
c2 += ec;
|
||||||
|
s2 += es;
|
||||||
|
}
|
||||||
|
if data.len() % 2 == 1 {
|
||||||
|
let (dc, ds) = pick(rng.next() >> 32);
|
||||||
|
c += dc;
|
||||||
|
s += ds;
|
||||||
|
}
|
||||||
|
(c + c2, s + s2)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sums<'a>(it: impl Iterator<Item = &'a (f64, f64)>) -> (f64, f64) {
|
fn sums<'a>(it: impl Iterator<Item = &'a (f64, f64)>) -> (f64, f64) {
|
||||||
@@ -466,3 +514,47 @@ mod tests {
|
|||||||
assert_eq!(s.interval_90, Some((0.0, 0.0)));
|
assert_eq!(s.interval_90, Some((0.0, 0.0)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod resampled {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn o(compiles: u64, seconds: f64) -> Observation {
|
||||||
|
Observation { compiles, seconds }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn several_hit_sets_from_one_draw_each_match_the_one_shot_call() {
|
||||||
|
let rust: Vec<Observation> = (0..40).map(|i| o(1, 4.0 + (i % 7) as f64)).collect();
|
||||||
|
let c: Vec<Observation> = (0..30).map(|i| o(1, 0.2 + 0.01 * (i % 5) as f64)).collect();
|
||||||
|
let tiny: Vec<Observation> = (0..3).map(|_| o(1, 9.0)).collect();
|
||||||
|
let draws = Resampled::new(&[&rust, &c, &tiny]);
|
||||||
|
for (rh, ch, th) in [(120, 40, 5), (0, 40, 5), (120, 0, 0), (1, 1, 1)] {
|
||||||
|
let langs = [
|
||||||
|
LanguageHits {
|
||||||
|
hits: rh,
|
||||||
|
obs: &rust,
|
||||||
|
},
|
||||||
|
LanguageHits { hits: ch, obs: &c },
|
||||||
|
LanguageHits {
|
||||||
|
hits: th,
|
||||||
|
obs: &tiny,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let once = time_saved(&langs, 0.01);
|
||||||
|
let again = draws.time_saved(&langs, 0.01);
|
||||||
|
assert_eq!(once.seconds, again.seconds, "{rh}/{ch}/{th}");
|
||||||
|
assert_eq!(once.hits_left_out, again.hits_left_out, "{rh}/{ch}/{th}");
|
||||||
|
assert_eq!(
|
||||||
|
again.hits_left_out, th,
|
||||||
|
"a language with three observations is left out"
|
||||||
|
);
|
||||||
|
let (lo, hi) = again.interval_90.expect("two languages have enough data");
|
||||||
|
assert!(
|
||||||
|
lo <= again.seconds && again.seconds <= hi,
|
||||||
|
"{rh}/{ch}/{th}: {lo} <= {} <= {hi}",
|
||||||
|
again.seconds
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
[package]
|
||||||
|
name = "sccache-dash-ui"
|
||||||
|
description = "Dashboard page for sccache-dash"
|
||||||
|
version.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
sccache-dash-api = { path = "../api" }
|
||||||
|
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
|
||||||
|
# The page is drawn with eframe in the browser for now. A native window would
|
||||||
|
# open the same `Dashboard`, and needs eframe here with its x11 and wayland features.
|
||||||
|
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||||
|
eframe = { version = "0.37", default-features = false, features = [
|
||||||
|
"default_fonts",
|
||||||
|
"glow",
|
||||||
|
"persistence",
|
||||||
|
] }
|
||||||
|
egui_plot = "0.38"
|
||||||
|
ehttp = "0.7"
|
||||||
|
wasm-bindgen = "0.2"
|
||||||
|
wasm-bindgen-futures = "0.4"
|
||||||
|
js-sys = "0.3"
|
||||||
|
web-sys = { version = "0.3", features = [
|
||||||
|
"Document",
|
||||||
|
"Element",
|
||||||
|
"HtmlAnchorElement",
|
||||||
|
"HtmlCanvasElement",
|
||||||
|
"Window",
|
||||||
|
] }
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
http://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION AND CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,93 @@
|
|||||||
|
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
|
||||||
|
|
||||||
|
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||||
|
This license is copied below, and is also available with a FAQ at:
|
||||||
|
https://scripts.sil.org/OFL
|
||||||
|
|
||||||
|
|
||||||
|
-----------------------------------------------------------
|
||||||
|
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||||
|
-----------------------------------------------------------
|
||||||
|
|
||||||
|
PREAMBLE
|
||||||
|
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||||
|
development of collaborative font projects, to support the font creation
|
||||||
|
efforts of academic and linguistic communities, and to provide a free and
|
||||||
|
open framework in which fonts may be shared and improved in partnership
|
||||||
|
with others.
|
||||||
|
|
||||||
|
The OFL allows the licensed fonts to be used, studied, modified and
|
||||||
|
redistributed freely as long as they are not sold by themselves. The
|
||||||
|
fonts, including any derivative works, can be bundled, embedded,
|
||||||
|
redistributed and/or sold with any software provided that any reserved
|
||||||
|
names are not used by derivative works. The fonts and derivatives,
|
||||||
|
however, cannot be released under any other type of license. The
|
||||||
|
requirement for fonts to remain under this license does not apply
|
||||||
|
to any document created using the fonts or their derivatives.
|
||||||
|
|
||||||
|
DEFINITIONS
|
||||||
|
"Font Software" refers to the set of files released by the Copyright
|
||||||
|
Holder(s) under this license and clearly marked as such. This may
|
||||||
|
include source files, build scripts and documentation.
|
||||||
|
|
||||||
|
"Reserved Font Name" refers to any names specified as such after the
|
||||||
|
copyright statement(s).
|
||||||
|
|
||||||
|
"Original Version" refers to the collection of Font Software components as
|
||||||
|
distributed by the Copyright Holder(s).
|
||||||
|
|
||||||
|
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||||
|
or substituting -- in part or in whole -- any of the components of the
|
||||||
|
Original Version, by changing formats or by porting the Font Software to a
|
||||||
|
new environment.
|
||||||
|
|
||||||
|
"Author" refers to any designer, engineer, programmer, technical
|
||||||
|
writer or other person who contributed to the Font Software.
|
||||||
|
|
||||||
|
PERMISSION & CONDITIONS
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining
|
||||||
|
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||||
|
redistribute, and sell modified and unmodified copies of the Font
|
||||||
|
Software, subject to the following conditions:
|
||||||
|
|
||||||
|
1) Neither the Font Software nor any of its individual components,
|
||||||
|
in Original or Modified Versions, may be sold by itself.
|
||||||
|
|
||||||
|
2) Original or Modified Versions of the Font Software may be bundled,
|
||||||
|
redistributed and/or sold with any software, provided that each copy
|
||||||
|
contains the above copyright notice and this license. These can be
|
||||||
|
included either as stand-alone text files, human-readable headers or
|
||||||
|
in the appropriate machine-readable metadata fields within text or
|
||||||
|
binary files as long as those fields can be easily viewed by the user.
|
||||||
|
|
||||||
|
3) No Modified Version of the Font Software may use the Reserved Font
|
||||||
|
Name(s) unless explicit written permission is granted by the corresponding
|
||||||
|
Copyright Holder. This restriction only applies to the primary font name as
|
||||||
|
presented to the users.
|
||||||
|
|
||||||
|
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||||
|
Software shall not be used to promote, endorse or advertise any
|
||||||
|
Modified Version, except to acknowledge the contribution(s) of the
|
||||||
|
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
5) The Font Software, modified or unmodified, in part or in whole,
|
||||||
|
must be distributed entirely under this license, and must not be
|
||||||
|
distributed under any other license. The requirement for fonts to
|
||||||
|
remain under this license does not apply to any document created
|
||||||
|
using the Font Software.
|
||||||
|
|
||||||
|
TERMINATION
|
||||||
|
This license becomes null and void if any of the above conditions are
|
||||||
|
not met.
|
||||||
|
|
||||||
|
DISCLAIMER
|
||||||
|
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||||
|
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||||
|
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||||
|
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||||
|
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||||
|
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||||
|
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||||
|
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||||
Binary file not shown.
@@ -0,0 +1,39 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||||
|
<meta name="color-scheme" content="dark light" />
|
||||||
|
<title>sccache dash</title>
|
||||||
|
<!-- A gauge in the page's own colours. -->
|
||||||
|
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Crect width=%2232%22 height=%2232%22 rx=%227%22 fill=%22%23161a22%22/%3E%3Cpath d=%22M6 22a10 10 0 0 1 20 0%22 fill=%22none%22 stroke=%22%233a4254%22 stroke-width=%224%22 stroke-linecap=%22round%22/%3E%3Cpath d=%22M6 22a10 10 0 0 1 15-8.66%22 fill=%22none%22 stroke=%22%234cc38a%22 stroke-width=%224%22 stroke-linecap=%22round%22/%3E%3Cpath d=%22M16 22l6-8%22 stroke=%22%23e6e9ef%22 stroke-width=%222.5%22 stroke-linecap=%22round%22/%3E%3Ccircle cx=%2216%22 cy=%2222%22 r=%222.5%22 fill=%22%23e6e9ef%22/%3E%3C/svg%3E" />
|
||||||
|
<link data-trunk rel="rust" data-bin="sccache-dash-ui" />
|
||||||
|
<style>
|
||||||
|
/* The page is one canvas that fills the window and scrolls inside itself. */
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
height: 100%;
|
||||||
|
height: 100dvh;
|
||||||
|
margin: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
/* The page colour of each theme (crates/ui/src/theme.rs), so nothing flashes while the page loads. */
|
||||||
|
background: #0e1116;
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: light) {
|
||||||
|
html,
|
||||||
|
body {
|
||||||
|
background: #f5f6f8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
canvas {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<canvas id="the_canvas_id"></canvas>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,936 @@
|
|||||||
|
//! The dashboard: what it remembers, how it fetches, and the top of the page.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use eframe::egui;
|
||||||
|
use sccache_dash_api::{Range, View};
|
||||||
|
|
||||||
|
use crate::disclosure;
|
||||||
|
use crate::fmt;
|
||||||
|
use crate::theme;
|
||||||
|
use crate::{cards, extras, net, overtime, problems, raw, speed, style, where_went};
|
||||||
|
|
||||||
|
/// Refresh intervals offered, in seconds; zero means off.
|
||||||
|
const REFRESH_CHOICES: [u64; 4] = [0, 5, 10, 30];
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
|
enum ThemeChoice {
|
||||||
|
/// Follow the browser's own light or dark setting.
|
||||||
|
Auto,
|
||||||
|
Light,
|
||||||
|
Dark,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ThemeChoice {
|
||||||
|
const ALL: [Self; 3] = [Self::Auto, Self::Light, Self::Dark];
|
||||||
|
|
||||||
|
fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Auto => "Auto",
|
||||||
|
Self::Light => "Light",
|
||||||
|
Self::Dark => "Dark",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preference(self) -> egui::ThemePreference {
|
||||||
|
match self {
|
||||||
|
Self::Auto => egui::ThemePreference::System,
|
||||||
|
Self::Light => egui::ThemePreference::Light,
|
||||||
|
Self::Dark => egui::ThemePreference::Dark,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a request in flight is for.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Ask {
|
||||||
|
View,
|
||||||
|
Zero,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole page. It draws one `View` at a time and keeps the last one on
|
||||||
|
/// screen until the next arrives.
|
||||||
|
pub struct Dashboard {
|
||||||
|
range: Range,
|
||||||
|
refresh_secs: u64,
|
||||||
|
theme: ThemeChoice,
|
||||||
|
view: Option<View>,
|
||||||
|
pending: Option<(Ask, net::Answer)>,
|
||||||
|
/// Why the last request failed, if it did.
|
||||||
|
error: Option<String>,
|
||||||
|
/// Page time, in seconds, when the last view was asked for.
|
||||||
|
sent_at: Option<f64>,
|
||||||
|
/// Languages unticked in the "Over time" filter.
|
||||||
|
hidden_languages: Vec<String>,
|
||||||
|
/// Whether the "Zero stats" question is open.
|
||||||
|
asking_zero: bool,
|
||||||
|
/// A short message for the controls row, and the page time it goes away.
|
||||||
|
note: Option<(String, f64)>,
|
||||||
|
/// Set when the range, refresh interval or theme changed and should be remembered.
|
||||||
|
settings_changed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dashboard {
|
||||||
|
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
|
||||||
|
let storage = cc.storage;
|
||||||
|
let dashboard = Self {
|
||||||
|
range: remembered(storage, "range").unwrap_or(Range::Day),
|
||||||
|
refresh_secs: remembered(storage, "refresh").unwrap_or(10),
|
||||||
|
theme: remembered(storage, "theme").unwrap_or(ThemeChoice::Auto),
|
||||||
|
view: None,
|
||||||
|
pending: None,
|
||||||
|
error: None,
|
||||||
|
sent_at: None,
|
||||||
|
hidden_languages: Vec::new(),
|
||||||
|
asking_zero: false,
|
||||||
|
note: None,
|
||||||
|
settings_changed: false,
|
||||||
|
};
|
||||||
|
let ctx = &cc.egui_ctx;
|
||||||
|
ctx.set_theme(dashboard.theme.preference());
|
||||||
|
theme::install(ctx);
|
||||||
|
dashboard
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now(ctx: &egui::Context) -> f64 {
|
||||||
|
ctx.input(|input| input.time)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send a request, replacing any request still in flight.
|
||||||
|
fn send(&mut self, ctx: &egui::Context, ask: Ask) {
|
||||||
|
if ask == Ask::View {
|
||||||
|
self.sent_at = Some(Self::now(ctx));
|
||||||
|
}
|
||||||
|
let request = match ask {
|
||||||
|
Ask::View => net::view(self.range),
|
||||||
|
Ask::Zero => net::zero(),
|
||||||
|
};
|
||||||
|
self.pending = Some((ask, net::Answer::send(request, ctx)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pick up the answer to the request in flight, if it has arrived.
|
||||||
|
fn collect(&mut self, ctx: &egui::Context, now: f64) {
|
||||||
|
if self.note.as_ref().is_some_and(|(_, until)| *until <= now) {
|
||||||
|
self.note = None;
|
||||||
|
}
|
||||||
|
let Some(answer) = self
|
||||||
|
.pending
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|(_, answer)| answer.take())
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some((ask, _)) = self.pending.take() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
match ask {
|
||||||
|
Ask::View => match net::view_from(answer) {
|
||||||
|
Ok(view) => {
|
||||||
|
self.view = Some(view);
|
||||||
|
self.error = None;
|
||||||
|
}
|
||||||
|
Err(error) => self.error = Some(error),
|
||||||
|
},
|
||||||
|
Ask::Zero => match net::accepted(answer) {
|
||||||
|
Ok(()) => {
|
||||||
|
self.flash("Stats zeroed", now);
|
||||||
|
self.send(ctx, Ask::View);
|
||||||
|
}
|
||||||
|
Err(error) => self.error = Some(format!("The stats could not be zeroed: {error}")),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep asking for a new view at the chosen interval.
|
||||||
|
fn tick(&mut self, ctx: &egui::Context, now: f64) {
|
||||||
|
if self.pending.is_some() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(sent_at) = self.sent_at else {
|
||||||
|
self.send(ctx, Ask::View);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if self.refresh_secs == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let every = self.refresh_secs as f64;
|
||||||
|
let since = now - sent_at;
|
||||||
|
if since >= every {
|
||||||
|
self.send(ctx, Ask::View);
|
||||||
|
} else {
|
||||||
|
ctx.request_repaint_after(Duration::from_secs_f64((every - since).max(0.05)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flash(&mut self, text: impl Into<String>, now: f64) {
|
||||||
|
self.note = Some((text.into(), now + 4.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl eframe::App for Dashboard {
|
||||||
|
/// Runs before every frame, also while the window is hidden: pick up answers and keep asking.
|
||||||
|
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||||
|
let now = Self::now(ctx);
|
||||||
|
self.collect(ctx, now);
|
||||||
|
self.tick(ctx, now);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||||
|
// The whole window in the page colour first: the toolbar sits outside the
|
||||||
|
// scrolling panel, and the browser's own canvas colour must never show.
|
||||||
|
ui.painter()
|
||||||
|
.rect_filled(ui.max_rect(), 0.0, theme::ctx(ui.ctx()).page);
|
||||||
|
controls(self, ui);
|
||||||
|
if let (Some(view), Some(error)) = (&self.view, &self.error) {
|
||||||
|
lost_contact(
|
||||||
|
ui.ctx(),
|
||||||
|
error,
|
||||||
|
view.generated_at,
|
||||||
|
ui.available_rect_before_wrap().width(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
egui::CentralPanel::default()
|
||||||
|
.frame(
|
||||||
|
egui::Frame::NONE
|
||||||
|
.fill(theme::ctx(ui.ctx()).page)
|
||||||
|
.inner_margin(egui::Margin::symmetric(
|
||||||
|
theme::space::PAGE_MARGIN as i8,
|
||||||
|
theme::space::PAGE_MARGIN as i8,
|
||||||
|
)),
|
||||||
|
)
|
||||||
|
.show(ui, |ui| {
|
||||||
|
egui::ScrollArea::vertical()
|
||||||
|
.auto_shrink([false; 2])
|
||||||
|
.show(ui, |ui| {
|
||||||
|
let Self {
|
||||||
|
range,
|
||||||
|
view,
|
||||||
|
hidden_languages,
|
||||||
|
..
|
||||||
|
} = self;
|
||||||
|
match view {
|
||||||
|
None => waiting(ui, self.error.as_deref(), self.refresh_secs),
|
||||||
|
Some(view) => page(ui, view, *range, hidden_languages),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
if self.asking_zero {
|
||||||
|
zero_question(self, ui.ctx());
|
||||||
|
}
|
||||||
|
if self.settings_changed {
|
||||||
|
if let Some(storage) = frame.storage_mut() {
|
||||||
|
remember(self, storage);
|
||||||
|
}
|
||||||
|
self.settings_changed = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remember the range, refresh interval and theme when the page is closed.
|
||||||
|
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||||
|
remember(self, storage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put the range, refresh interval and theme into the storage eframe keeps between visits.
|
||||||
|
fn remember(dashboard: &Dashboard, storage: &mut dyn eframe::Storage) {
|
||||||
|
eframe::set_value(storage, "range", &dashboard.range);
|
||||||
|
eframe::set_value(storage, "refresh", &dashboard.refresh_secs);
|
||||||
|
eframe::set_value(storage, "theme", &dashboard.theme);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remembered<T: serde::de::DeserializeOwned>(
|
||||||
|
storage: Option<&dyn eframe::Storage>,
|
||||||
|
key: &str,
|
||||||
|
) -> Option<T> {
|
||||||
|
storage.and_then(|storage| eframe::get_value(storage, key))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn theme_labels() -> [&'static str; 3] {
|
||||||
|
ThemeChoice::ALL.map(|theme| theme.name())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wordmark at the left of the top bar.
|
||||||
|
fn wordmark(ui: &mut egui::Ui) {
|
||||||
|
ui.add(egui::Label::new(
|
||||||
|
egui::RichText::new("sccache dash")
|
||||||
|
.font(theme::number_font(15.0))
|
||||||
|
.color(theme::ui(ui).text),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wordmark_width(ui: &egui::Ui) -> f32 {
|
||||||
|
style::text_width(ui, "sccache dash", theme::number_font(15.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// About how wide the row of actions is, from the width of its labels.
|
||||||
|
fn actions_width(ui: &egui::Ui) -> f32 {
|
||||||
|
let medium = theme::medium(theme::px::BODY);
|
||||||
|
let label = |text: &str| style::text_width(ui, text, medium.clone()) + 18.0;
|
||||||
|
let gaps = theme::space::TOOL_GAP;
|
||||||
|
label(&fmt::refresh_label(30)) + 20.0 + label("Refresh")
|
||||||
|
+ theme_labels().iter().map(|text| style::text_width(ui, text, medium.clone()) + 2.0 * theme::space::CONTROL_PAD).sum::<f32>()
|
||||||
|
+ label("Copy summary") + label("Export JSON") + label("Zero stats")
|
||||||
|
+ theme::space::TOOLBAR_NOTE_WIDTH
|
||||||
|
+ gaps * 7.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The slim bar at the top of the page: the wordmark and the range at the left; the
|
||||||
|
/// actions at the right, on their own line where there is no room beside the range.
|
||||||
|
fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) {
|
||||||
|
let ctx = ui.ctx().clone();
|
||||||
|
let now = Dashboard::now(&ctx);
|
||||||
|
let gap = theme::space::TOOL_GAP;
|
||||||
|
let margin = theme::space::PAGE_MARGIN;
|
||||||
|
let vertical = 10.0;
|
||||||
|
ui.add_space(vertical);
|
||||||
|
let width = ui.available_rect_before_wrap().width() - 2.0 * margin;
|
||||||
|
let medium = theme::medium(theme::px::BODY);
|
||||||
|
let range_width: f32 = Range::ALL
|
||||||
|
.iter()
|
||||||
|
.map(|range| style::text_width(ui, range.code(), medium.clone()) + 2.0 * theme::space::CONTROL_PAD)
|
||||||
|
.sum();
|
||||||
|
let left_width = wordmark_width(ui) + 2.0 * theme::space::PANEL_GAP + range_width;
|
||||||
|
let one_line = left_width + gap + actions_width(ui) <= width;
|
||||||
|
let phone = width + 2.0 * theme::space::PAGE_MARGIN < theme::layout::TWO_COLUMNS_FROM;
|
||||||
|
|
||||||
|
let labels: Vec<&str> = Range::ALL.iter().map(|range| range.code()).collect();
|
||||||
|
let chosen = Range::ALL.iter().position(|range| *range == dashboard.range).unwrap_or(0);
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = gap;
|
||||||
|
ui.add_space(margin);
|
||||||
|
wordmark(ui);
|
||||||
|
ui.add_space(theme::space::PANEL_GAP - gap);
|
||||||
|
if let Some(index) = style::segmented(ui, "range", &labels, chosen) {
|
||||||
|
if index != chosen {
|
||||||
|
dashboard.range = Range::ALL[index];
|
||||||
|
dashboard.settings_changed = true;
|
||||||
|
dashboard.send(&ctx, Ask::View);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if one_line {
|
||||||
|
ui.add_space((ui.available_width() - actions_width(ui) - margin).max(0.0));
|
||||||
|
ui.allocate_ui_with_layout(
|
||||||
|
egui::vec2(actions_width(ui), theme::layout::TOOLBAR_HEIGHT),
|
||||||
|
egui::Layout::left_to_right(egui::Align::Center),
|
||||||
|
|ui| actions(dashboard, ui, &ctx, now, gap),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if !one_line {
|
||||||
|
let height = theme::layout::TOOLBAR_HEIGHT;
|
||||||
|
ui.add_space(gap);
|
||||||
|
let room = ui.available_rect_before_wrap().width() - 2.0 * margin;
|
||||||
|
let group_width = if phone { room } else { actions_width(ui).min(room) };
|
||||||
|
// On a phone the actions wrap at the left; on a narrower window they sit
|
||||||
|
// on a second line, at the right.
|
||||||
|
let layout = if phone {
|
||||||
|
egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true)
|
||||||
|
} else {
|
||||||
|
egui::Layout::right_to_left(egui::Align::Center)
|
||||||
|
};
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.add_space(margin);
|
||||||
|
ui.allocate_ui_with_layout(egui::vec2(room, height), layout, |ui| {
|
||||||
|
if !phone {
|
||||||
|
ui.allocate_ui_with_layout(
|
||||||
|
egui::vec2(group_width, height),
|
||||||
|
egui::Layout::left_to_right(egui::Align::Center),
|
||||||
|
|ui| actions(dashboard, ui, &ctx, now, gap),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
ui.spacing_mut().item_spacing = egui::vec2(gap, gap);
|
||||||
|
actions(dashboard, ui, &ctx, now, gap);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
ui.add_space(vertical);
|
||||||
|
let rule = ui.available_rect_before_wrap();
|
||||||
|
ui.painter().hline(
|
||||||
|
rule.x_range(),
|
||||||
|
rule.top() + 0.5,
|
||||||
|
egui::Stroke::new(1.0, theme::ctx(&ctx).border),
|
||||||
|
);
|
||||||
|
ui.add_space(1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Refresh, theme, Copy summary, Export JSON, Zero stats, and the message slot.
|
||||||
|
fn actions(dashboard: &mut Dashboard, ui: &mut egui::Ui, ctx: &egui::Context, now: f64, gap: f32) {
|
||||||
|
ui.spacing_mut().item_spacing.x = gap;
|
||||||
|
let mut refresh_secs = dashboard.refresh_secs;
|
||||||
|
egui::ComboBox::from_id_salt("refresh")
|
||||||
|
.selected_text(fmt::refresh_label(refresh_secs))
|
||||||
|
.show_ui(ui, |ui| {
|
||||||
|
for secs in REFRESH_CHOICES {
|
||||||
|
ui.selectable_value(&mut refresh_secs, secs, fmt::refresh_label(secs));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if refresh_secs != dashboard.refresh_secs {
|
||||||
|
dashboard.refresh_secs = refresh_secs;
|
||||||
|
dashboard.settings_changed = true;
|
||||||
|
}
|
||||||
|
if ui.button("Refresh").clicked() {
|
||||||
|
dashboard.send(ctx, Ask::View);
|
||||||
|
}
|
||||||
|
|
||||||
|
let theme_chosen = ThemeChoice::ALL
|
||||||
|
.iter()
|
||||||
|
.position(|theme| *theme == dashboard.theme)
|
||||||
|
.unwrap_or(0);
|
||||||
|
if let Some(index) = style::segmented(ui, "theme", &theme_labels(), theme_chosen) {
|
||||||
|
let theme = ThemeChoice::ALL[index];
|
||||||
|
dashboard.theme = theme;
|
||||||
|
dashboard.settings_changed = true;
|
||||||
|
ctx.set_theme(theme.preference());
|
||||||
|
}
|
||||||
|
|
||||||
|
let online = dashboard.view.is_some();
|
||||||
|
let copy = ui.add_enabled(online, egui::Button::new("Copy summary"));
|
||||||
|
if copy.clicked() {
|
||||||
|
if let Some(view) = &dashboard.view {
|
||||||
|
ctx.copy_text(view.summary_markdown.clone());
|
||||||
|
}
|
||||||
|
dashboard.flash("Summary copied", now);
|
||||||
|
}
|
||||||
|
let export = ui.add_enabled(online, egui::Button::new("Export JSON"));
|
||||||
|
if export.clicked() {
|
||||||
|
let note = net::download("/api/export").map_or_else(
|
||||||
|
|error| format!("Export failed: {error}"),
|
||||||
|
|()| "Export started".to_owned(),
|
||||||
|
);
|
||||||
|
dashboard.flash(note, now);
|
||||||
|
}
|
||||||
|
let zeroing = dashboard
|
||||||
|
.pending
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(ask, _)| *ask == Ask::Zero);
|
||||||
|
let zero = ui.add_enabled(online && !zeroing, egui::Button::new("Zero stats"));
|
||||||
|
if zero.clicked() {
|
||||||
|
dashboard.asking_zero = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A fixed-size slot, so that messages come and go without moving the controls.
|
||||||
|
ui.allocate_ui_with_layout(
|
||||||
|
egui::vec2(theme::space::TOOLBAR_NOTE_WIDTH, theme::layout::TOOLBAR_HEIGHT),
|
||||||
|
egui::Layout::left_to_right(egui::Align::Center),
|
||||||
|
|ui| {
|
||||||
|
if dashboard
|
||||||
|
.pending
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|(ask, _)| *ask == Ask::View)
|
||||||
|
{
|
||||||
|
ui.spinner();
|
||||||
|
ui.add(egui::Label::new(theme::small(ui, "Updating")).truncate());
|
||||||
|
} else if let Some((note, _)) = &dashboard.note {
|
||||||
|
ui.add(egui::Label::new(theme::small(ui, note.clone())).truncate());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ask before zeroing: it can't be undone.
|
||||||
|
fn zero_question(dashboard: &mut Dashboard, ctx: &egui::Context) {
|
||||||
|
let modal = egui::Modal::new(egui::Id::unique("zero-stats-question")).show(ctx, |ui| {
|
||||||
|
ui.set_max_width(360.0);
|
||||||
|
ui.add(egui::Label::new(theme::strong("Zero sccache's stats?")).wrap());
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
ui.add(egui::Label::new(theme::body(
|
||||||
|
"The counters go back to zero. The saved history stays, so the charts keep their \
|
||||||
|
older data. This can't be undone.",
|
||||||
|
))
|
||||||
|
.wrap());
|
||||||
|
ui.add_space(theme::space::PANEL_GAP);
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
if ui.button("Zero stats").clicked() {
|
||||||
|
Some(true)
|
||||||
|
} else if ui.button("Cancel").clicked() {
|
||||||
|
Some(false)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.inner
|
||||||
|
});
|
||||||
|
let answer = modal.inner;
|
||||||
|
if modal.should_close() || answer == Some(false) {
|
||||||
|
dashboard.asking_zero = false;
|
||||||
|
}
|
||||||
|
if answer == Some(true) {
|
||||||
|
dashboard.asking_zero = false;
|
||||||
|
dashboard.send(ctx, Ask::Zero);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the page says while no view has arrived yet.
|
||||||
|
fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
let retry = if refresh_secs > 0 {
|
||||||
|
format!("Trying again every {refresh_secs} seconds.")
|
||||||
|
} else {
|
||||||
|
"Press Refresh to try again.".to_owned()
|
||||||
|
};
|
||||||
|
let (heading, body, color) = match error {
|
||||||
|
Some(error) => (
|
||||||
|
"Can't reach the server".to_owned(),
|
||||||
|
format!(
|
||||||
|
"{error}.\n\nCheck that sccache-dash is running on this machine. {retry}"
|
||||||
|
),
|
||||||
|
p.bad,
|
||||||
|
),
|
||||||
|
None => (
|
||||||
|
"Waiting for the first figures".to_owned(),
|
||||||
|
"Asking the server for your cache numbers.".to_owned(),
|
||||||
|
p.text,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
// The same height the headline and cards take, so the page doesn't jump when they arrive.
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let height = theme::layout::HEADLINE_HEIGHT + theme::space::PANEL_GAP + theme::layout::STRIP_ROW_HEIGHT * 2.0;
|
||||||
|
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||||
|
let mut place = ui.new_child(
|
||||||
|
egui::UiBuilder::new()
|
||||||
|
.max_rect(rect)
|
||||||
|
.layout(egui::Layout::centered_and_justified(egui::Direction::TopDown)),
|
||||||
|
);
|
||||||
|
place.vertical(|ui| {
|
||||||
|
ui.add(egui::Label::new(theme::strong(heading).color(color)).wrap());
|
||||||
|
ui.add(egui::Label::new(theme::small(ui, body)).wrap());
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A notice that the server can't be reached, shown over the page rather than
|
||||||
|
/// in it, so what is already on screen keeps its place and height.
|
||||||
|
fn lost_contact(ctx: &egui::Context, error: &str, from: i64, page_width: f32) {
|
||||||
|
let p = theme::ctx(ctx);
|
||||||
|
let when = fmt::moment_text(from + fmt::local_offset());
|
||||||
|
egui::Area::new(egui::Id::unique("lost-contact"))
|
||||||
|
.anchor(
|
||||||
|
egui::Align2::RIGHT_TOP,
|
||||||
|
egui::vec2(-theme::space::PAGE_MARGIN, theme::layout::TOOLBAR_HEIGHT + 3.0 * theme::space::PAGE_MARGIN),
|
||||||
|
)
|
||||||
|
.order(egui::Order::Foreground)
|
||||||
|
.show(ctx, |ui| {
|
||||||
|
let width = (page_width - 2.0 * theme::space::PAGE_MARGIN).min(440.0);
|
||||||
|
egui::Frame::NONE
|
||||||
|
.fill(p.panel)
|
||||||
|
.stroke(egui::Stroke::new(1.0, p.bad))
|
||||||
|
.corner_radius(theme::space::PANEL_RADIUS)
|
||||||
|
.inner_margin(theme::space::PANEL_PAD_Y)
|
||||||
|
.show(ui, |ui| {
|
||||||
|
ui.set_max_width(width - 2.0 * theme::space::PANEL_PAD_Y);
|
||||||
|
ui.add(
|
||||||
|
egui::Label::new(
|
||||||
|
theme::strong(format!(
|
||||||
|
"Can't reach the server: {error}. These figures are from {when}."
|
||||||
|
))
|
||||||
|
.color(p.bad),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rectangles of one row of the grid: each entry of `spans` is how many
|
||||||
|
/// columns that panel takes; all are at least `height` tall.
|
||||||
|
fn row(ui: &egui::Ui, height: f32, spans: &[usize]) -> Vec<egui::Rect> {
|
||||||
|
style::cells(ui, height, spans)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close the row: the cursor moves below the tallest of its panels.
|
||||||
|
fn close_row(ui: &mut egui::Ui, taken: &[egui::Rect]) {
|
||||||
|
style::end_row(ui, taken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One panel across the whole page, as tall as what it holds.
|
||||||
|
fn single(ui: &mut egui::Ui, title: &str, body: impl FnOnce(&mut egui::Ui)) {
|
||||||
|
let [rect] = row(ui, 0.0, &[1]).try_into().expect("one panel");
|
||||||
|
let (_, taken) = style::panel(ui, rect, title, body);
|
||||||
|
close_row(ui, &[taken]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How tall a panel is that holds `rows` table rows under its title.
|
||||||
|
fn table_height(fixed: f32, rows: usize) -> f32 {
|
||||||
|
fixed + rows as f32 * theme::space::ROW
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How tall "Speed" is.
|
||||||
|
fn speed_height(view: &View) -> f32 {
|
||||||
|
use theme::layout as l;
|
||||||
|
let with_histograms = view
|
||||||
|
.build_times
|
||||||
|
.iter()
|
||||||
|
.filter(|times| times.compiles > 0 && !times.bins.is_empty())
|
||||||
|
.count();
|
||||||
|
table_height(l::SPEED_FIXED_HEIGHT, 0) + with_histograms as f32 * l::HISTOGRAM_HEIGHT
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole page below the controls: a grid of panels. Two columns of panels
|
||||||
|
/// from the medium width up, one below it; the counter strip is six across,
|
||||||
|
/// three across, or two.
|
||||||
|
fn page(ui: &mut egui::Ui, view: &View, asked: Range, hidden_languages: &mut Vec<String>) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
use theme::layout as l;
|
||||||
|
let gap = theme::space::PANEL_GAP;
|
||||||
|
if let Some(error) = &view.server.error {
|
||||||
|
style::banner(ui, egui::RichText::new(format!("sccache is not working: {error}")), p.bad);
|
||||||
|
ui.add_space(gap);
|
||||||
|
}
|
||||||
|
let columns = theme::columns(ui.available_rect_before_wrap().width());
|
||||||
|
|
||||||
|
headline(ui, view, asked);
|
||||||
|
|
||||||
|
// Six counters in one row on a wide screen; three in the medium layout; two on a phone.
|
||||||
|
let per_row = match columns {
|
||||||
|
3 => 6,
|
||||||
|
2 => 3,
|
||||||
|
_ => 2,
|
||||||
|
};
|
||||||
|
cards::row(ui, view, per_row);
|
||||||
|
|
||||||
|
if columns >= 2 {
|
||||||
|
let half = style::span_width(ui, 2, 1);
|
||||||
|
let languages_h = table_height(l::LANGUAGES_FIXED_HEIGHT, view.languages.len() + 1);
|
||||||
|
let [a, b] = row(ui, l::WHERE_FIXED_HEIGHT.max(languages_h), &[1, 1]).try_into().expect("two panels");
|
||||||
|
let (_, a) = style::panel(ui, a, "Where compiles went", |ui| where_went::section(ui, view));
|
||||||
|
let (_, b) = style::panel(ui, b, "By language", |ui| where_went::languages(ui, view));
|
||||||
|
close_row(ui, &[a, b]);
|
||||||
|
|
||||||
|
overtime::filter(ui, view, hidden_languages);
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
let hidden: &[String] = hidden_languages;
|
||||||
|
let [a, b] = row(ui, l::CHART_PANEL_HEIGHT, &[1, 1]).try_into().expect("two panels");
|
||||||
|
let (_, a) = style::panel(ui, a, "Hit rate over time", |ui| {
|
||||||
|
overtime::hit_rate_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT)
|
||||||
|
});
|
||||||
|
let (_, b) = style::panel(ui, b, "Compiles over time", |ui| {
|
||||||
|
overtime::volume_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT)
|
||||||
|
});
|
||||||
|
close_row(ui, &[a, b]);
|
||||||
|
|
||||||
|
let height = speed_height(view).max(where_went::reasons_height(ui, view, half));
|
||||||
|
let [a, b] = row(ui, height, &[1, 1]).try_into().expect("two panels");
|
||||||
|
let (_, a) = style::panel(ui, a, "Speed", |ui| speed::section(ui, view));
|
||||||
|
let (_, b) = style::panel(ui, b, "Why compiles were not cacheable", |ui| where_went::reasons(ui, view));
|
||||||
|
close_row(ui, &[a, b]);
|
||||||
|
} else {
|
||||||
|
// One column: each panel as tall as what it holds.
|
||||||
|
single(ui, "Where compiles went", |ui| where_went::section(ui, view));
|
||||||
|
single(ui, "By language", |ui| where_went::languages(ui, view));
|
||||||
|
overtime::filter(ui, view, hidden_languages);
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
let hidden: &[String] = hidden_languages;
|
||||||
|
single(ui, "Hit rate over time", |ui| {
|
||||||
|
overtime::hit_rate_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT)
|
||||||
|
});
|
||||||
|
single(ui, "Compiles over time", |ui| {
|
||||||
|
overtime::volume_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT)
|
||||||
|
});
|
||||||
|
single(ui, "Speed", |ui| speed::section(ui, view));
|
||||||
|
single(ui, "Why compiles were not cacheable", |ui| where_went::reasons(ui, view));
|
||||||
|
}
|
||||||
|
|
||||||
|
extras(ui, view);
|
||||||
|
|
||||||
|
let open = ui
|
||||||
|
.ctx()
|
||||||
|
.data_mut(|data| data.get_temp::<bool>(egui::Id::new("raw-counters-open")))
|
||||||
|
.unwrap_or(false);
|
||||||
|
let full = style::span_width(ui, 1, 1);
|
||||||
|
let [rect] = row(ui, raw::height(view, full, open), &[1]).try_into().expect("one panel");
|
||||||
|
let taken = raw::section(ui, view, rect);
|
||||||
|
close_row(ui, &[taken]);
|
||||||
|
ui.add_space(theme::space::PAGE_MARGIN);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The "Extras" panels, side by side where there are several.
|
||||||
|
fn extras(ui: &mut egui::Ui, view: &View) {
|
||||||
|
if view.extras.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let columns = theme::columns(ui.available_rect_before_wrap().width()).min(2);
|
||||||
|
let per_row = columns.min(view.extras.len()).max(1);
|
||||||
|
for line in view.extras.chunks(per_row) {
|
||||||
|
let spans: Vec<usize> = line.iter().map(|_| 1).collect();
|
||||||
|
let height = theme::space::ROW * (line.iter().map(|extra| extra.rows.len()).max().unwrap_or(0) + 1) as f32
|
||||||
|
+ theme::space::PANEL_PAD_Y * 2.0 + theme::space::UNDER_TITLE + 12.0;
|
||||||
|
let cells = style::cells(ui, height, &spans);
|
||||||
|
let mut taken = Vec::with_capacity(cells.len());
|
||||||
|
for (rect, extra) in cells.iter().zip(line) {
|
||||||
|
let title: &str = Box::leak(extra.title.clone().into_boxed_str());
|
||||||
|
let (_, rect) = style::panel(ui, *rect, title, |ui| extras::section(ui, view));
|
||||||
|
taken.push(rect);
|
||||||
|
}
|
||||||
|
close_row(ui, &taken);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One of the three big figures.
|
||||||
|
struct Figure<'a> {
|
||||||
|
value: String,
|
||||||
|
/// The size of the figure's text: a number, or words at the card size.
|
||||||
|
size: f32,
|
||||||
|
color: egui::Color32,
|
||||||
|
caption: String,
|
||||||
|
/// Smaller print under the figure.
|
||||||
|
small: String,
|
||||||
|
/// A second line of smaller print; the block keeps its height when it is empty.
|
||||||
|
small2: String,
|
||||||
|
/// A trend line and the value it is drawn against.
|
||||||
|
trend: Option<(&'a [Option<f64>], f64)>,
|
||||||
|
/// Instead of a trend line and small print: the problems list.
|
||||||
|
problems: Option<&'a View>,
|
||||||
|
hover: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The line the figure's number sits on: every figure's number has this much room, so all
|
||||||
|
/// the captions below start at the same height whatever size the number is drawn at.
|
||||||
|
const VALUE_ROW: f32 = theme::px::HEADLINE * 1.25;
|
||||||
|
|
||||||
|
/// The room the storage line (meter and text) is given under the figures; a phone has a second text line.
|
||||||
|
const STORAGE_LINE: f32 = 30.0;
|
||||||
|
|
||||||
|
impl Figure<'_> {
|
||||||
|
/// Draw in a column `width` wide and always the same height.
|
||||||
|
fn draw(self, ui: &mut egui::Ui, width: f32) {
|
||||||
|
let gap = theme::space::LINE;
|
||||||
|
let block = ui.allocate_ui_with_layout(
|
||||||
|
egui::vec2(width, theme::layout::FIGURE_HEIGHT),
|
||||||
|
egui::Layout::top_down(egui::Align::Min),
|
||||||
|
|ui| {
|
||||||
|
ui.set_width(width);
|
||||||
|
ui.spacing_mut().item_spacing = egui::vec2(gap, gap);
|
||||||
|
// Shrink a long figure to the column instead of cutting it.
|
||||||
|
let natural = style::text_width(ui, &self.value, theme::number_font(self.size));
|
||||||
|
let size = if natural > width { (self.size * width / natural).max(20.0) } else { self.size };
|
||||||
|
ui.allocate_ui_with_layout(
|
||||||
|
egui::vec2(width, VALUE_ROW),
|
||||||
|
egui::Layout::left_to_right(egui::Align::Max),
|
||||||
|
|ui| {
|
||||||
|
let value = egui::Label::new(
|
||||||
|
egui::RichText::new(&self.value)
|
||||||
|
.font(theme::number_font(size))
|
||||||
|
.color(self.color),
|
||||||
|
)
|
||||||
|
.truncate();
|
||||||
|
ui.add(value.sense(egui::Sense::hover())).on_hover_text(&self.value);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
ui.add(egui::Label::new(theme::title(ui, self.caption.clone())).truncate());
|
||||||
|
ui.add_space(gap * 2.0);
|
||||||
|
if let Some(view) = self.problems {
|
||||||
|
let room = ui.available_height();
|
||||||
|
problems::hero_list(ui, view, room);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match self.trend {
|
||||||
|
Some((values, top)) => style::sparkline(ui, theme::drawing::SPARKLINE, values, top, self.color),
|
||||||
|
None => ui.add_space(theme::drawing::SPARKLINE + gap),
|
||||||
|
}
|
||||||
|
ui.add(egui::Label::new(theme::small(ui, self.small.clone())).truncate());
|
||||||
|
ui.add(egui::Label::new(theme::small(ui, self.small2.clone())).truncate());
|
||||||
|
},
|
||||||
|
);
|
||||||
|
if let Some(hover) = self.hover {
|
||||||
|
block.response.on_hover_text(hover);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The big numbers, what they mean, and where the cache lives.
|
||||||
|
fn headline(ui: &mut egui::Ui, view: &View, asked: Range) {
|
||||||
|
let range = view.range.unwrap_or(asked);
|
||||||
|
let totals = &view.totals;
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
|
||||||
|
let rates: Vec<Option<f64>> = view
|
||||||
|
.buckets
|
||||||
|
.iter()
|
||||||
|
.map(|bucket| (!bucket.gap).then(|| overtime::hit_rate(bucket.hits, bucket.misses)).flatten())
|
||||||
|
.collect();
|
||||||
|
let saved: Vec<Option<f64>> = view
|
||||||
|
.buckets
|
||||||
|
.iter()
|
||||||
|
.map(|bucket| (!bucket.gap).then_some(bucket.saved_seconds))
|
||||||
|
.collect();
|
||||||
|
let saved_top = saved.iter().flatten().fold(0.0_f64, |top, seconds| top.max(*seconds));
|
||||||
|
|
||||||
|
let problems = view.problems.len();
|
||||||
|
|
||||||
|
let counts = format!(
|
||||||
|
"{} compiles · {} from cache · {} built",
|
||||||
|
fmt::count(totals.requests),
|
||||||
|
fmt::count(totals.hits),
|
||||||
|
fmt::count(totals.misses)
|
||||||
|
);
|
||||||
|
let title_text = theme::title(ui, range.label()).text().to_owned();
|
||||||
|
let counts_text = counts.clone();
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
// Side by side where there is room; one under another on a phone.
|
||||||
|
let side_by_side = width >= 600.0;
|
||||||
|
let spacing = theme::space::PANEL_GAP;
|
||||||
|
let height = if side_by_side {
|
||||||
|
theme::layout::HEADLINE_HEIGHT
|
||||||
|
} else {
|
||||||
|
theme::layout::HEADLINE_HEIGHT + 2.0 * (theme::layout::FIGURE_HEIGHT + spacing) + STORAGE_LINE / 2.0
|
||||||
|
};
|
||||||
|
let rect = egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, height));
|
||||||
|
let (_, taken) = style::panel_titled(
|
||||||
|
ui,
|
||||||
|
rect,
|
||||||
|
|ui| {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.add(egui::Label::new(theme::title(ui, title_text)).truncate());
|
||||||
|
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||||
|
ui.add(egui::Label::new(theme::small(ui, counts_text)).truncate());
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|ui| {
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let columns = if side_by_side { 3.0 } else { 1.0 };
|
||||||
|
let column = (width - spacing * (columns - 1.0)) / columns;
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
let draw = |ui: &mut egui::Ui, figure: Figure<'_>| figure.draw(ui, column);
|
||||||
|
// Timeouts, cache errors and forced recaches are inside the built count, as sccache counts them.
|
||||||
|
let first = Figure {
|
||||||
|
value: fmt::percent(totals.hit_rate()),
|
||||||
|
size: theme::px::HEADLINE,
|
||||||
|
color: p.hero,
|
||||||
|
caption: "from cache".into(),
|
||||||
|
small: format!("{} of all compiler calls", fmt::percent(totals.hit_rate_of_all())),
|
||||||
|
trend: Some((&rates, 1.0)),
|
||||||
|
problems: None,
|
||||||
|
hover: None,
|
||||||
|
small2: String::new(),
|
||||||
|
};
|
||||||
|
// A saving is never written in milliseconds; and when no language's build time is
|
||||||
|
// known yet, the figure says so instead of showing nothing.
|
||||||
|
let seconds = view.time_saved.seconds;
|
||||||
|
let left_out = view.time_saved.hits_left_out;
|
||||||
|
let left_out_line = if left_out > 0 {
|
||||||
|
format!("{} hits left out of this figure", fmt::count(left_out))
|
||||||
|
} else {
|
||||||
|
"every hit counted".to_owned()
|
||||||
|
};
|
||||||
|
let interval = view
|
||||||
|
.time_saved
|
||||||
|
.interval_90
|
||||||
|
.map(|(low, high)| format!("{} – {} (90% range)", fmt::duration(low), fmt::duration(high)));
|
||||||
|
let (value, size, small, small2) = if seconds >= 1.0 {
|
||||||
|
(format!("~{}", fmt::duration(seconds)), theme::px::HEADLINE, interval.unwrap_or_default(), left_out_line)
|
||||||
|
} else if seconds > 0.0 {
|
||||||
|
("~under 1 s".to_owned(), theme::px::HEADLINE, interval.unwrap_or_default(), left_out_line)
|
||||||
|
} else if left_out > 0 {
|
||||||
|
(
|
||||||
|
"not enough data yet".to_owned(),
|
||||||
|
theme::px::CARD_NUMBER,
|
||||||
|
String::new(),
|
||||||
|
format!(
|
||||||
|
"{} hits not counted: no build time known yet for their language",
|
||||||
|
fmt::count(left_out)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
("nothing saved yet".to_owned(), theme::px::CARD_NUMBER, String::new(), String::new())
|
||||||
|
};
|
||||||
|
let second = Figure {
|
||||||
|
value,
|
||||||
|
size,
|
||||||
|
color: p.hero,
|
||||||
|
caption: "saved (rough)".into(),
|
||||||
|
small,
|
||||||
|
small2,
|
||||||
|
trend: Some((&saved, saved_top)),
|
||||||
|
problems: None,
|
||||||
|
hover: Some(view.time_saved.note.clone()),
|
||||||
|
};
|
||||||
|
let third = Figure {
|
||||||
|
value: fmt::count(problems as u64),
|
||||||
|
size: theme::px::HEADLINE,
|
||||||
|
color: if problems > 0 { p.bad } else { p.text },
|
||||||
|
caption: if problems == 1 { "problem".into() } else { "problems".into() },
|
||||||
|
small: String::new(),
|
||||||
|
small2: String::new(),
|
||||||
|
trend: None,
|
||||||
|
problems: Some(view),
|
||||||
|
hover: None,
|
||||||
|
};
|
||||||
|
let top = ui.cursor().top();
|
||||||
|
let left = ui.cursor().left();
|
||||||
|
if side_by_side {
|
||||||
|
ui.horizontal_top(|ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = spacing;
|
||||||
|
draw(ui, first);
|
||||||
|
draw(ui, second);
|
||||||
|
draw(ui, third);
|
||||||
|
});
|
||||||
|
// A hairline in the middle of each gutter between figures.
|
||||||
|
let y = top..=top + theme::layout::FIGURE_HEIGHT;
|
||||||
|
for index in 1..3 {
|
||||||
|
let x = left + index as f32 * column + (index as f32 - 0.5) * spacing;
|
||||||
|
ui.painter().vline(x.round() + 0.5, y.clone(), egui::Stroke::new(1.0, p.grid));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
draw(ui, first);
|
||||||
|
ui.add_space(spacing);
|
||||||
|
draw(ui, second);
|
||||||
|
ui.add_space(spacing);
|
||||||
|
draw(ui, third);
|
||||||
|
}
|
||||||
|
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
style::rule(ui);
|
||||||
|
ui.add_space(theme::space::ITEM + 2.0);
|
||||||
|
|
||||||
|
let server = &view.server;
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
if let Some(location) = &server.cache_location {
|
||||||
|
// sccache words it `Local disk: "/home/me/.cache/sccache"`; the kind is enough here.
|
||||||
|
let kind = location.split(':').next().unwrap_or(location);
|
||||||
|
let kind = if kind.eq_ignore_ascii_case("LOCAL DISK") {
|
||||||
|
"Local disk".to_owned()
|
||||||
|
} else {
|
||||||
|
kind.to_owned()
|
||||||
|
};
|
||||||
|
parts.push(kind);
|
||||||
|
}
|
||||||
|
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
|
||||||
|
parts.push(format!("{} of {}", fmt::bytes(size), fmt::bytes(max)));
|
||||||
|
}
|
||||||
|
if let Some(version) = server.version.as_deref().or(server.client_version.as_deref()) {
|
||||||
|
parts.push(format!("sccache {version}"));
|
||||||
|
}
|
||||||
|
parts.push(
|
||||||
|
match server.status {
|
||||||
|
sccache_dash_api::Status::Running => "running",
|
||||||
|
sccache_dash_api::Status::Idle => "idle",
|
||||||
|
sccache_dash_api::Status::NotRunning => "not running",
|
||||||
|
}
|
||||||
|
.to_owned(),
|
||||||
|
);
|
||||||
|
let line = parts.join(" · ");
|
||||||
|
// The meter first, then the text under it, in a box of fixed height.
|
||||||
|
let lines = if side_by_side { 1.0 } else { 2.0 };
|
||||||
|
let text_height = STORAGE_LINE / 2.0 * lines;
|
||||||
|
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
|
||||||
|
let full = if max > 0 { size as f64 / max as f64 } else { 0.0 };
|
||||||
|
let color = if full >= theme::state::CACHE_FULL { p.bad } else { p.hero };
|
||||||
|
style::meter(ui, theme::drawing::USAGE_BAR, full, color);
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
}
|
||||||
|
let response = ui
|
||||||
|
.allocate_ui_with_layout(
|
||||||
|
egui::vec2(width, text_height),
|
||||||
|
egui::Layout::top_down(egui::Align::Min),
|
||||||
|
|ui| ui.add(egui::Label::new(theme::small(ui, line)).wrap()),
|
||||||
|
)
|
||||||
|
.inner;
|
||||||
|
if let Some(location) = &server.cache_location {
|
||||||
|
response.on_hover_text(location.clone());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
ui.allocate_rect(taken, egui::Sense::hover());
|
||||||
|
ui.add_space(theme::space::PANEL_GAP);
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
//! The six counters under the headline: one quiet strip, all cells the same size, tops in a line.
|
||||||
|
|
||||||
|
use eframe::egui::{self, Color32, Pos2, Rect, RichText};
|
||||||
|
|
||||||
|
use sccache_dash_api::{Range, View};
|
||||||
|
|
||||||
|
use crate::fmt;
|
||||||
|
use crate::style;
|
||||||
|
use crate::theme;
|
||||||
|
|
||||||
|
/// The cards in `per_row` per row: six in one row on a wide screen, three in
|
||||||
|
/// the two-column layout, two on a phone.
|
||||||
|
pub fn row(ui: &mut egui::Ui, view: &View, per_row: usize) {
|
||||||
|
let totals = &view.totals;
|
||||||
|
let previous = view.previous.as_ref();
|
||||||
|
let range = view.range.unwrap_or(Range::Day);
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
let requests = totals.requests;
|
||||||
|
let cache_errors = totals.errors();
|
||||||
|
let cards = [
|
||||||
|
Card {
|
||||||
|
title: "Cache hits",
|
||||||
|
count: totals.hits,
|
||||||
|
color: None,
|
||||||
|
detail: format!("{} of compiler calls", fmt::share(totals.hits, requests)),
|
||||||
|
previous: previous.map(|previous| previous.hits),
|
||||||
|
good_when_up: true,
|
||||||
|
},
|
||||||
|
Card {
|
||||||
|
title: "Cache misses",
|
||||||
|
count: totals.misses,
|
||||||
|
color: None,
|
||||||
|
detail: format!("{} of compiler calls", fmt::share(totals.misses, requests)),
|
||||||
|
previous: previous.map(|previous| previous.misses),
|
||||||
|
good_when_up: false,
|
||||||
|
},
|
||||||
|
Card {
|
||||||
|
title: "Timeouts",
|
||||||
|
count: totals.timeouts,
|
||||||
|
color: (totals.timeouts > 0).then_some(p.bad),
|
||||||
|
detail: String::new(),
|
||||||
|
previous: previous.map(|previous| previous.timeouts),
|
||||||
|
good_when_up: false,
|
||||||
|
},
|
||||||
|
Card {
|
||||||
|
title: "Cache errors",
|
||||||
|
count: cache_errors,
|
||||||
|
color: (cache_errors > 0).then_some(p.bad),
|
||||||
|
detail: format!(
|
||||||
|
"{} read · {} write · {} other",
|
||||||
|
fmt::count(totals.read_errors),
|
||||||
|
fmt::count(totals.write_errors),
|
||||||
|
fmt::count(totals.other_errors)
|
||||||
|
),
|
||||||
|
previous: previous.map(|previous| previous.errors()),
|
||||||
|
good_when_up: false,
|
||||||
|
},
|
||||||
|
Card {
|
||||||
|
title: "Compile failures",
|
||||||
|
count: totals.compile_fails,
|
||||||
|
color: None,
|
||||||
|
detail: String::new(),
|
||||||
|
previous: previous.map(|previous| previous.compile_fails),
|
||||||
|
good_when_up: false,
|
||||||
|
},
|
||||||
|
Card {
|
||||||
|
title: "Forced recaches",
|
||||||
|
count: totals.forced_recaches,
|
||||||
|
color: None,
|
||||||
|
detail: String::new(),
|
||||||
|
previous: previous.map(|previous| previous.forced_recaches),
|
||||||
|
good_when_up: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
let per_row = per_row.max(1);
|
||||||
|
let left = ui.cursor().left();
|
||||||
|
let mut top = ui.cursor().top();
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let cell_width = width / per_row as f32;
|
||||||
|
let height = theme::layout::STRIP_ROW_HEIGHT;
|
||||||
|
let rule = egui::Stroke::new(1.0, p.border);
|
||||||
|
ui.painter().hline(left..=left + width, top + 0.5, rule);
|
||||||
|
for (line_index, line) in cards.chunks(per_row).enumerate() {
|
||||||
|
if line_index > 0 {
|
||||||
|
ui.painter().hline(left..=left + width, top + 0.5, egui::Stroke::new(1.0, p.grid));
|
||||||
|
}
|
||||||
|
for (index, card) in line.iter().enumerate() {
|
||||||
|
let change = change(card.count, card.previous, range, card.good_when_up, p);
|
||||||
|
style::card(
|
||||||
|
ui,
|
||||||
|
Rect::from_min_size(Pos2::new(left + index as f32 * cell_width, top), egui::vec2(cell_width, height)),
|
||||||
|
index == 0,
|
||||||
|
card.title,
|
||||||
|
&fmt::count(card.count),
|
||||||
|
&card.detail,
|
||||||
|
change,
|
||||||
|
card.color.unwrap_or(p.text),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
top += height;
|
||||||
|
}
|
||||||
|
ui.painter().hline(left..=left + width, top - 0.5, rule);
|
||||||
|
ui.add_space(top - ui.cursor().top());
|
||||||
|
ui.add_space(theme::space::PANEL_GAP);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Card {
|
||||||
|
title: &'static str,
|
||||||
|
count: u64,
|
||||||
|
/// The colour of the count when it is worth a look.
|
||||||
|
color: Option<Color32>,
|
||||||
|
/// The line between the count and the comparison.
|
||||||
|
detail: String,
|
||||||
|
/// The same count in the period before, when the server has one.
|
||||||
|
previous: Option<u64>,
|
||||||
|
/// Whether more of this count is good news.
|
||||||
|
good_when_up: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a count compares with the period before, and the colour that change deserves.
|
||||||
|
fn change(count: u64, previous: Option<u64>, range: Range, good_when_up: bool, p: &theme::Palette) -> RichText {
|
||||||
|
let Some(previous) = previous else {
|
||||||
|
return RichText::new("").font(egui::FontId::proportional(theme::px::SMALL));
|
||||||
|
};
|
||||||
|
if previous == 0 {
|
||||||
|
return small_plain(p, if count == 0 { String::new() } else { "was 0 before".into() });
|
||||||
|
}
|
||||||
|
let change = (count as f64 - previous as f64) / previous as f64 * 100.0;
|
||||||
|
if change.abs() < 0.5 {
|
||||||
|
return small_plain(p, "no change".into());
|
||||||
|
}
|
||||||
|
let better = (change > 0.0) == good_when_up;
|
||||||
|
RichText::new(format!("{change:+.0}% vs {}", fmt::previous_label(range)))
|
||||||
|
.font(egui::FontId::proportional(theme::px::SMALL))
|
||||||
|
.color(if better { p.good } else { p.bad })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn small_plain(p: &theme::Palette, text: String) -> RichText {
|
||||||
|
RichText::new(text)
|
||||||
|
.font(egui::FontId::proportional(theme::px::SMALL))
|
||||||
|
.color(p.muted)
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
//! The arithmetic of a list of lines that open: which start open, how tall the
|
||||||
|
//! list is, and whether stacking panels beside it wastes less room. No drawing
|
||||||
|
//! here, so it is tested natively.
|
||||||
|
|
||||||
|
/// A line that opens to show a text beneath it, laid out for a width.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct Entry {
|
||||||
|
/// The line itself.
|
||||||
|
pub row: f32,
|
||||||
|
pub open: bool,
|
||||||
|
/// The first paragraph's height; used only when open.
|
||||||
|
pub meaning: f32,
|
||||||
|
/// The second paragraph's height, `None` when there is none; used only when open.
|
||||||
|
pub action: Option<f32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a line is open: what was clicked, else open when `fixable`.
|
||||||
|
pub fn is_open(stored: Option<bool>, fixable: bool) -> bool {
|
||||||
|
stored.unwrap_or(fixable)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How tall one line is: `gap` between its parts, `pad` under the open text.
|
||||||
|
pub fn entry_height(entry: &Entry, gap: f32, pad: f32) -> f32 {
|
||||||
|
if !entry.open {
|
||||||
|
return entry.row;
|
||||||
|
}
|
||||||
|
let action = entry.action.map_or(0.0, |height| gap + height);
|
||||||
|
entry.row + gap + entry.meaning + action + pad
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How tall the whole list is: its lines and a hairline `separator` tall between them.
|
||||||
|
pub fn list_height(entries: &[Entry], gap: f32, pad: f32, separator: f32) -> f32 {
|
||||||
|
let lines: f32 = entries.iter().map(|entry| entry_height(entry, gap, pad)).sum();
|
||||||
|
lines + entries.len().saturating_sub(1) as f32 * separator
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether to stack the panels (`stacked` tall in all) beside a panel `beside` tall rather
|
||||||
|
/// than put the one `single` panel there: yes when that leaves less empty room.
|
||||||
|
pub fn stack_beside(single: f32, stacked: f32, beside: f32) -> bool {
|
||||||
|
(stacked - beside).abs() < (single - beside).abs()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn entry(open: bool) -> Entry {
|
||||||
|
Entry { row: 28.0, open, meaning: 45.0, action: Some(30.0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_fixable_lines_start_open() {
|
||||||
|
assert!(is_open(None, true));
|
||||||
|
assert!(!is_open(None, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_click_wins_over_the_default() {
|
||||||
|
assert!(!is_open(Some(false), true));
|
||||||
|
assert!(is_open(Some(true), false));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_closed_line_is_one_row_and_an_open_one_adds_its_text() {
|
||||||
|
assert_eq!(entry_height(&entry(false), 3.0, 8.0), 28.0);
|
||||||
|
assert_eq!(entry_height(&entry(true), 3.0, 8.0), 28.0 + 3.0 + 45.0 + 3.0 + 30.0 + 8.0);
|
||||||
|
let no_action = Entry { action: None, ..entry(true) };
|
||||||
|
assert_eq!(entry_height(&no_action, 3.0, 8.0), 28.0 + 3.0 + 45.0 + 8.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_list_is_its_lines_and_the_hairlines_between() {
|
||||||
|
let list = [entry(true), entry(false), entry(false)];
|
||||||
|
assert_eq!(list_height(&list, 3.0, 8.0, 1.0), 117.0 + 28.0 + 28.0 + 2.0);
|
||||||
|
assert_eq!(list_height(&[], 3.0, 8.0, 1.0), 0.0);
|
||||||
|
assert_eq!(list_height(&[entry(false)], 3.0, 8.0, 1.0), 28.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stacking_is_chosen_only_when_it_fills_the_room_better() {
|
||||||
|
// Everything closed: the lone panel (244) is close to the list (300); three stacked (500) are not.
|
||||||
|
assert!(!stack_beside(244.0, 500.0, 300.0));
|
||||||
|
// Two open: the list (520) is nearer the stack.
|
||||||
|
assert!(stack_beside(244.0, 500.0, 520.0));
|
||||||
|
// A tie keeps the simple layout.
|
||||||
|
assert!(!stack_beside(200.0, 400.0, 300.0));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
//! Extras: the tables sccache only fills in for some setups, one panel each.
|
||||||
|
|
||||||
|
use sccache_dash_api::View;
|
||||||
|
|
||||||
|
use crate::style::{self, Cell};
|
||||||
|
use crate::theme;
|
||||||
|
|
||||||
|
pub fn section(ui: &mut eframe::egui::Ui, view: &View) {
|
||||||
|
for extra in &view.extras {
|
||||||
|
let rows: Vec<Vec<Cell>> = extra
|
||||||
|
.rows
|
||||||
|
.iter()
|
||||||
|
.map(|(label, value)| {
|
||||||
|
vec![
|
||||||
|
Cell::Text(theme::strong(label.clone())),
|
||||||
|
Cell::Text(theme::number(value.clone())),
|
||||||
|
]
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
style::table(ui, &[], &rows);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
//! How numbers, durations and times are written on the page.
|
||||||
|
|
||||||
|
use sccache_dash_api::Range;
|
||||||
|
|
||||||
|
/// How a comparison with the period before is worded, from the range's own
|
||||||
|
/// label: "previous 24 hours".
|
||||||
|
pub fn previous_label(range: Range) -> String {
|
||||||
|
let label = range.label();
|
||||||
|
format!("previous {}", label.strip_prefix("last ").unwrap_or(label))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lowest edge of a row of panels: the largest of their `bottoms`, or
|
||||||
|
/// `empty` when there are none. The bottoms are screen positions, so they are
|
||||||
|
/// negative while the row is scrolled above the top of the window.
|
||||||
|
pub fn lowest(bottoms: impl IntoIterator<Item = f32>, empty: f32) -> f32 {
|
||||||
|
bottoms.into_iter().reduce(f32::max).unwrap_or(empty)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whole-number percentages of `parts` that add up to exactly 100, giving the
|
||||||
|
/// leftovers of rounding to the largest shares. All zero when nothing is counted.
|
||||||
|
pub fn shares(parts: &[u64]) -> Vec<u64> {
|
||||||
|
let total: u64 = parts.iter().sum();
|
||||||
|
if total == 0 {
|
||||||
|
return vec![0; parts.len()];
|
||||||
|
}
|
||||||
|
let exact: Vec<f64> = parts
|
||||||
|
.iter()
|
||||||
|
.map(|part| 100.0 * *part as f64 / total as f64)
|
||||||
|
.collect();
|
||||||
|
let mut whole: Vec<u64> = exact.iter().map(|value| value.floor() as u64).collect();
|
||||||
|
let mut left = 100 - whole.iter().sum::<u64>();
|
||||||
|
let mut by_fraction: Vec<usize> = (0..parts.len()).collect();
|
||||||
|
by_fraction.sort_by(|a, b| exact[*b].fract().total_cmp(&exact[*a].fract()));
|
||||||
|
for index in by_fraction {
|
||||||
|
if left == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
whole[index] += 1;
|
||||||
|
left -= 1;
|
||||||
|
}
|
||||||
|
whole
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the refresh control names an interval: "Every 10 s", or "Off".
|
||||||
|
pub fn refresh_label(secs: u64) -> String {
|
||||||
|
if secs == 0 {
|
||||||
|
"Off".into()
|
||||||
|
} else {
|
||||||
|
format!("Every {secs} s")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A count with thousands separators: 2815 becomes "2,815".
|
||||||
|
pub fn count(n: u64) -> String {
|
||||||
|
let digits = n.to_string();
|
||||||
|
let first = (digits.len() - 1) % 3 + 1;
|
||||||
|
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
|
||||||
|
out.push_str(&digits[..first]);
|
||||||
|
for (index, digit) in digits[first..].chars().enumerate() {
|
||||||
|
if index % 3 == 0 {
|
||||||
|
out.push(',');
|
||||||
|
}
|
||||||
|
out.push(digit);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A ratio as whole percent: 0.456 becomes "46%"; "—" when there is no ratio.
|
||||||
|
pub fn percent(ratio: Option<f64>) -> String {
|
||||||
|
ratio.map_or_else(|| "—".into(), |ratio| format!("{:.0}%", ratio * 100.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `part` of `whole` as whole percent; "—" when `whole` is zero.
|
||||||
|
pub fn share(part: u64, whole: u64) -> String {
|
||||||
|
percent((whole > 0).then(|| part as f64 / whole as f64))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seconds the short way: "0.7 ms", "8.1 s", "3m 05s", "3h 05m", "2d 3h".
|
||||||
|
pub fn duration(seconds: f64) -> String {
|
||||||
|
if !seconds.is_finite() {
|
||||||
|
return "—".into();
|
||||||
|
}
|
||||||
|
let seconds = seconds.max(0.0);
|
||||||
|
if seconds < 1.0 {
|
||||||
|
return format!("{:.1} ms", seconds * 1000.0);
|
||||||
|
}
|
||||||
|
let tenths = (seconds * 10.0).round() as u64;
|
||||||
|
let (whole, tenth) = (tenths / 10, tenths % 10);
|
||||||
|
if whole < 60 {
|
||||||
|
return format!("{whole}.{tenth} s");
|
||||||
|
}
|
||||||
|
let (minutes, second) = (whole / 60, whole % 60);
|
||||||
|
if minutes < 60 {
|
||||||
|
return format!("{minutes}m {second:02}s");
|
||||||
|
}
|
||||||
|
let (hours, minute) = (minutes / 60, minutes % 60);
|
||||||
|
if hours < 24 {
|
||||||
|
return format!("{hours}h {minute:02}m");
|
||||||
|
}
|
||||||
|
let (days, hour) = (hours / 24, hours % 24);
|
||||||
|
format!("{days}d {hour}h")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A multiple in round numbers: 11432.7 becomes "11,000", 7.42 becomes "7.4".
|
||||||
|
pub fn round_number(n: f64) -> String {
|
||||||
|
if !n.is_finite() || n <= 0.0 {
|
||||||
|
return "—".into();
|
||||||
|
}
|
||||||
|
if n < 10.0 {
|
||||||
|
return format!("{n:.1}");
|
||||||
|
}
|
||||||
|
let round_to = if n >= 1000.0 {
|
||||||
|
100.0
|
||||||
|
} else if n >= 100.0 {
|
||||||
|
10.0
|
||||||
|
} else {
|
||||||
|
1.0
|
||||||
|
};
|
||||||
|
count((n / round_to).round() as u64 * round_to as u64)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A size in bytes the way file managers show it: "10.0 GB".
|
||||||
|
pub fn bytes(n: u64) -> String {
|
||||||
|
const K: f64 = 1024.0;
|
||||||
|
let (value, unit) = match n as f64 {
|
||||||
|
value if value < K => return format!("{n} B"),
|
||||||
|
value if value < K * K => (value / K, "KB"),
|
||||||
|
value if value < K * K * K => (value / (K * K), "MB"),
|
||||||
|
value if value < K * K * K * K => (value / (K * K * K), "GB"),
|
||||||
|
value => (value / (K * K * K * K), "TB"),
|
||||||
|
};
|
||||||
|
format!("{value:.1} {unit}")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seconds to add to a Unix time to get the clock time of this computer.
|
||||||
|
/// The browser knows its time zone; a native window would need to find it another way.
|
||||||
|
pub fn local_offset() -> i64 {
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
{
|
||||||
|
// `get_timezone_offset` is minutes to add to local time to get UTC.
|
||||||
|
-(js_sys::Date::new_0().get_timezone_offset() as i64) * 60
|
||||||
|
}
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
{
|
||||||
|
0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A moment as month, day and clock time.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Moment {
|
||||||
|
pub month: u32,
|
||||||
|
pub day: u32,
|
||||||
|
pub hour: u32,
|
||||||
|
pub minute: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The moment `unix` seconds after 1 January 1970.
|
||||||
|
pub fn moment(unix: i64) -> Moment {
|
||||||
|
let days = unix.div_euclid(86_400);
|
||||||
|
let secs_of_day = unix.rem_euclid(86_400);
|
||||||
|
// Howard Hinnant's civil-from-days.
|
||||||
|
let z = days + 719_468;
|
||||||
|
let day_of_era = z.rem_euclid(146_097);
|
||||||
|
let year_of_era =
|
||||||
|
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
||||||
|
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
||||||
|
let mp = (5 * day_of_year + 2) / 153;
|
||||||
|
let day = day_of_year - (153 * mp + 2) / 5 + 1;
|
||||||
|
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||||
|
Moment {
|
||||||
|
month: month as u32,
|
||||||
|
day: day as u32,
|
||||||
|
hour: (secs_of_day / 3600) as u32,
|
||||||
|
minute: (secs_of_day % 3600 / 60) as u32,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Moment {
|
||||||
|
/// "14:05"
|
||||||
|
pub fn clock(self) -> String {
|
||||||
|
format!("{:02}:{:02}", self.hour, self.minute)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Nov 12"
|
||||||
|
pub fn date(self) -> String {
|
||||||
|
const MONTHS: [&str; 12] = [
|
||||||
|
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
|
||||||
|
];
|
||||||
|
let month = MONTHS[(self.month.clamp(1, 12) - 1) as usize];
|
||||||
|
format!("{month} {}", self.day)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Nov 12, 14:05" for a moment given in Unix seconds.
|
||||||
|
pub fn moment_text(unix: i64) -> String {
|
||||||
|
let moment = moment(unix);
|
||||||
|
format!("{}, {}", moment.date(), moment.clock())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spacing of the ticks on a time axis that long, in seconds: whole minutes,
|
||||||
|
/// hours or days, giving about four to eight ticks.
|
||||||
|
pub fn tick_step(span_secs: f64) -> i64 {
|
||||||
|
const STEPS: [i64; 14] = [
|
||||||
|
60, 120, 300, 600, 900, 1800, 3600, 7200, 10_800, 21_600, 43_200, 86_400, 172_800,
|
||||||
|
604_800,
|
||||||
|
];
|
||||||
|
STEPS
|
||||||
|
.into_iter()
|
||||||
|
.find(|step| span_secs / *step as f64 <= 7.5)
|
||||||
|
.unwrap_or(604_800)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The label for one tick of a time axis: the clock time, or the date for
|
||||||
|
/// ticks that fall on midnight or are a day or more apart.
|
||||||
|
pub fn tick_label(unix: i64, step: i64) -> String {
|
||||||
|
let moment = moment(unix);
|
||||||
|
if step >= 86_400 || unix.rem_euclid(86_400) == 0 {
|
||||||
|
moment.date()
|
||||||
|
} else {
|
||||||
|
moment.clock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What is hidden after the "All languages" box changes: ticked shows every
|
||||||
|
/// language, cleared hides them all.
|
||||||
|
pub fn hidden_after_all<'a>(ticked: bool, languages: impl Iterator<Item = &'a str>) -> Vec<String> {
|
||||||
|
if ticked {
|
||||||
|
Vec::new()
|
||||||
|
} else {
|
||||||
|
languages.map(str::to_owned).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_row_scrolled_above_the_window_still_ends_at_its_own_bottom() {
|
||||||
|
// Rows closed by their lowest panel: the same answer wherever the page is scrolled.
|
||||||
|
assert_eq!(lowest([260.0, 300.0, 280.0], 0.0), 300.0);
|
||||||
|
assert_eq!(lowest([-340.0, -300.0, -320.0], 0.0), -300.0);
|
||||||
|
assert_eq!(lowest([-17250.0, -17210.5], 0.0), -17210.5);
|
||||||
|
assert_eq!(lowest([], 42.0), 42.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn counts_have_thousands_separators() {
|
||||||
|
assert_eq!(count(0), "0");
|
||||||
|
assert_eq!(count(325), "325");
|
||||||
|
assert_eq!(count(2815), "2,815");
|
||||||
|
assert_eq!(count(123_456), "123,456");
|
||||||
|
assert_eq!(count(1_234_567_890), "1,234,567,890");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn durations_are_short_and_round_cleanly() {
|
||||||
|
assert_eq!(duration(0.0007), "0.7 ms");
|
||||||
|
assert_eq!(duration(0.0), "0.0 ms");
|
||||||
|
assert_eq!(duration(8.14), "8.1 s");
|
||||||
|
assert_eq!(duration(59.96), "1m 00s");
|
||||||
|
assert_eq!(duration(185.0), "3m 05s");
|
||||||
|
assert_eq!(duration(11_100.0), "3h 05m");
|
||||||
|
assert_eq!(duration(183_600.0), "2d 3h");
|
||||||
|
assert_eq!(duration(f64::NAN), "—");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn moments_match_the_calendar() {
|
||||||
|
assert_eq!(
|
||||||
|
moment(0),
|
||||||
|
Moment {
|
||||||
|
month: 1,
|
||||||
|
day: 1,
|
||||||
|
hour: 0,
|
||||||
|
minute: 0
|
||||||
|
}
|
||||||
|
);
|
||||||
|
// 1,700,000,000 is 14 November 2023, 22:13:20 UTC.
|
||||||
|
assert_eq!(moment_text(1_700_000_000), "Nov 14, 22:13");
|
||||||
|
// Day 95 after the epoch is 6 April 1970.
|
||||||
|
assert_eq!(moment_text(95 * 86_400 + 12 * 3600), "Apr 6, 12:00");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_are_round_and_ticked() {
|
||||||
|
assert_eq!(round_number(11_432.7), "11,400");
|
||||||
|
assert_eq!(round_number(7.42), "7.4");
|
||||||
|
assert_eq!(bytes(10 * 1024 * 1024 * 1024), "10.0 GB");
|
||||||
|
assert_eq!(tick_step(3660.0), 600);
|
||||||
|
assert_eq!(tick_step(86_640.0), 21_600);
|
||||||
|
assert_eq!(tick_label(43_200, 600), "12:00");
|
||||||
|
assert_eq!(tick_label(86_400, 600), "Jan 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shares_add_up_to_one_hundred() {
|
||||||
|
assert_eq!(shares(&[50, 33, 17]), [50, 33, 17]);
|
||||||
|
assert_eq!(shares(&[1, 1, 1]), [34, 33, 33]);
|
||||||
|
assert_eq!(shares(&[7351, 0, 0, 0, 0]), [100, 0, 0, 0, 0]);
|
||||||
|
assert_eq!(shares(&[0, 0]), [0, 0]);
|
||||||
|
let parts = [3254, 3256, 829, 14, 13];
|
||||||
|
assert_eq!(shares(&parts).iter().sum::<u64>(), 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn all_languages_box_turns_them_back_on() {
|
||||||
|
let names = ["Rust", "C/C++"];
|
||||||
|
assert_eq!(hidden_after_all(true, names.into_iter()), Vec::<String>::new());
|
||||||
|
assert_eq!(hidden_after_all(false, names.into_iter()), vec!["Rust", "C/C++"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
//! The sccache-dash dashboard page. `trunk` compiles this to WebAssembly and
|
||||||
|
//! the sccache-dash server serves it at http://127.0.0.1:8226.
|
||||||
|
|
||||||
|
pub mod disclosure;
|
||||||
|
pub mod fmt;
|
||||||
|
|
||||||
|
// Drawing needs eframe, which is only built for the browser so far; the rest
|
||||||
|
// (and the tests) build anywhere.
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod app;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod cards;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod extras;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod net;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod overtime;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod problems;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod raw;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod speed;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod style;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod theme;
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod where_went;
|
||||||
|
|
||||||
|
/// The canvas in `index.html` the page is drawn on.
|
||||||
|
pub const CANVAS_ID: &str = "the_canvas_id";
|
||||||
|
|
||||||
|
/// Open the dashboard page in the browser.
|
||||||
|
pub fn open() {
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
web::open();
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
eprintln!(
|
||||||
|
"sccache-dash-ui is a web page: build it with `trunk build` in crates/ui. \
|
||||||
|
There is no native window yet."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
mod web {
|
||||||
|
use super::{app::Dashboard, CANVAS_ID};
|
||||||
|
|
||||||
|
pub fn open() {
|
||||||
|
use wasm_bindgen::JsCast;
|
||||||
|
|
||||||
|
let canvas = web_sys::window()
|
||||||
|
.and_then(|window| window.document())
|
||||||
|
.and_then(|document| document.get_element_by_id(CANVAS_ID))
|
||||||
|
.and_then(|element| element.dyn_into::<web_sys::HtmlCanvasElement>().ok())
|
||||||
|
.unwrap_or_else(|| panic!("index.html has no canvas named #{CANVAS_ID}"));
|
||||||
|
|
||||||
|
wasm_bindgen_futures::spawn_local(async move {
|
||||||
|
let options = eframe::WebOptions::default();
|
||||||
|
eframe::WebRunner::new()
|
||||||
|
.start(canvas, options, Box::new(|cc| Ok(Box::new(Dashboard::new(cc)))))
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|error| panic!("eframe failed to start: {error:?}"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use sccache_dash_api::{Range, View};
|
||||||
|
|
||||||
|
/// A view with something in every part of the page.
|
||||||
|
const SAMPLE: &str = r#"{
|
||||||
|
"range": "24h",
|
||||||
|
"generated_at": 1764300000,
|
||||||
|
"server": {
|
||||||
|
"status": "Running",
|
||||||
|
"version": "0.18.0",
|
||||||
|
"client_version": "0.18.0",
|
||||||
|
"cache_location": "Local disk: \"/home/me/.cache/sccache\"",
|
||||||
|
"cache_size": 10726353131,
|
||||||
|
"max_cache_size": 10737418240,
|
||||||
|
"error": null
|
||||||
|
},
|
||||||
|
"totals": {
|
||||||
|
"requests": 5610, "executed": 5610, "hits": 2815, "misses": 2795,
|
||||||
|
"not_cacheable": 0, "unsupported_compiler": 0, "not_compile": 0,
|
||||||
|
"timeouts": 3, "read_errors": 2, "write_errors": 1, "other_errors": 0,
|
||||||
|
"compile_fails": 12, "forced_recaches": 4, "cache_writes": 2795
|
||||||
|
},
|
||||||
|
"previous": {
|
||||||
|
"requests": 5000, "executed": 5000, "hits": 2000, "misses": 3000,
|
||||||
|
"not_cacheable": 0, "unsupported_compiler": 0, "not_compile": 0,
|
||||||
|
"timeouts": 0, "read_errors": 0, "write_errors": 0, "other_errors": 0,
|
||||||
|
"compile_fails": 9, "forced_recaches": 0, "cache_writes": 3000
|
||||||
|
},
|
||||||
|
"timing": { "avg_hit_read_ms": 0.72, "avg_cache_write_ms": 310.0, "avg_compile_ms": 8050.0 },
|
||||||
|
"time_saved": {
|
||||||
|
"seconds": 11100.0, "interval_90": [9700.0, 12600.0], "hits_left_out": 7,
|
||||||
|
"note": "Low on purpose."
|
||||||
|
},
|
||||||
|
"build_times": [
|
||||||
|
{ "language": "Rust", "compiles": 3256, "mean_ms": 7780.0, "median_ms": 7100.0,
|
||||||
|
"p90_ms": 21200.0,
|
||||||
|
"bins": [
|
||||||
|
{ "from_ms": 1000.0, "to_ms": 1778.28, "compiles": 120 },
|
||||||
|
{ "from_ms": 1778.28, "to_ms": 3162.28, "compiles": 980 }
|
||||||
|
] },
|
||||||
|
{ "language": "CUDA", "compiles": 0, "mean_ms": 0.0, "median_ms": 0.0,
|
||||||
|
"p90_ms": 0.0, "bins": [] }
|
||||||
|
],
|
||||||
|
"languages": [
|
||||||
|
{ "name": "Rust", "hits": 229, "misses": 3256, "errors": 0 },
|
||||||
|
{ "name": "C/C++", "hits": 2082, "misses": 0, "errors": 0 }
|
||||||
|
],
|
||||||
|
"not_cached": [{"reason": "crate-type", "count": 621, "name": "Programs and libraries that get linked", "meaning": "m", "action": "a", "fixable": false}, {"reason": "incremental", "count": 105, "name": "n", "meaning": "m", "action": "a", "fixable": true}],
|
||||||
|
"buckets": [
|
||||||
|
{ "start": 1764290000, "hits": 10, "misses": 5, "other": 1, "errors": 0, "saved_seconds": 60.0,
|
||||||
|
"languages": [["Rust", 10, 5]], "reset": false, "gap": false },
|
||||||
|
{ "start": 1764290600, "hits": 0, "misses": 0, "other": 0, "errors": 0, "saved_seconds": 0.0,
|
||||||
|
"languages": [], "reset": false, "gap": true },
|
||||||
|
{ "start": 1764291200, "hits": 4, "misses": 4, "other": 0, "errors": 0, "saved_seconds": 30.0,
|
||||||
|
"languages": [["C/C++", 4, 4]], "reset": true, "gap": false }
|
||||||
|
],
|
||||||
|
"problems": [
|
||||||
|
{ "severity": "Warning", "title": "Rust hit rate 8%", "detail": "Most Rust compiles miss." }
|
||||||
|
],
|
||||||
|
"extras": [ { "title": "Multi-level cache", "rows": [["Levels", "2"]] } ],
|
||||||
|
"raw": { "stats": { "compile_requests": 5610 }, "version": "0.18.0" },
|
||||||
|
"summary_markdown": "**Cache:** 50%"
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_view_deserialises() {
|
||||||
|
let view: View = serde_json::from_str(SAMPLE).expect("the sample is a View");
|
||||||
|
assert_eq!(view.range, Some(Range::Day));
|
||||||
|
assert_eq!(view.totals.hit_rate(), Some(2815.0 / 5610.0));
|
||||||
|
assert_eq!(view.server.version.as_deref(), Some("0.18.0"));
|
||||||
|
assert_eq!(view.time_saved.interval_90, Some((9700.0, 12600.0)));
|
||||||
|
assert_eq!(view.build_times[0].bins[1].compiles, 980);
|
||||||
|
assert_eq!(view.build_times[1].compiles, 0);
|
||||||
|
assert_eq!((view.not_cached[0].reason.as_str(), view.not_cached[0].count), ("crate-type", 621));
|
||||||
|
assert!(view.not_cached[1].fixable);
|
||||||
|
assert_eq!(view.buckets[1].gap, true);
|
||||||
|
assert_eq!(view.extras[0].rows[0].1, "2");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_empty_view_deserialises() {
|
||||||
|
// Every field is present, as the server always sends them; several are empty.
|
||||||
|
let view: View = serde_json::from_str(
|
||||||
|
r#"{"range": null, "generated_at": 0, "server": {"status": "NotRunning"},
|
||||||
|
"totals": {
|
||||||
|
"requests": 0, "executed": 0, "hits": 0, "misses": 0, "not_cacheable": 0,
|
||||||
|
"unsupported_compiler": 0, "not_compile": 0, "timeouts": 0, "read_errors": 0,
|
||||||
|
"write_errors": 0, "other_errors": 0, "compile_fails": 0, "forced_recaches": 0,
|
||||||
|
"cache_writes": 0
|
||||||
|
},
|
||||||
|
"previous": null,
|
||||||
|
"timing": {
|
||||||
|
"avg_hit_read_ms": null, "avg_cache_write_ms": null, "avg_compile_ms": null
|
||||||
|
},
|
||||||
|
"time_saved": {"seconds": 0.0, "hits_left_out": 0, "note": ""},
|
||||||
|
"languages": [], "not_cached": [], "buckets": [], "problems": [], "extras": [],
|
||||||
|
"raw": null, "summary_markdown": ""}"#,
|
||||||
|
)
|
||||||
|
.expect("an empty view is still a View");
|
||||||
|
assert_eq!(view.totals.hit_rate(), None);
|
||||||
|
assert_eq!(view.time_saved.interval_90, None);
|
||||||
|
assert!(view.build_times.is_empty());
|
||||||
|
assert!(view.raw.is_null());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
//! Entry point of the WebAssembly module; the page itself lives in the library.
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
sccache_dash_ui::open();
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
//! Talking to the server. One request is in flight at a time.
|
||||||
|
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
use eframe::egui;
|
||||||
|
use sccache_dash_api::{Range, View};
|
||||||
|
|
||||||
|
/// A request sent to the server; its answer is picked up on a later frame.
|
||||||
|
pub struct Answer {
|
||||||
|
slot: Arc<Mutex<Option<Result<ehttp::Response, String>>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Answer {
|
||||||
|
pub fn send(request: ehttp::Request, ctx: &egui::Context) -> Self {
|
||||||
|
let slot = Arc::new(Mutex::new(None));
|
||||||
|
let sink = Arc::clone(&slot);
|
||||||
|
let ctx = ctx.clone();
|
||||||
|
ehttp::fetch(request, move |result| {
|
||||||
|
if let Ok(mut sink) = sink.lock() {
|
||||||
|
*sink = Some(result);
|
||||||
|
}
|
||||||
|
ctx.request_repaint();
|
||||||
|
});
|
||||||
|
Self { slot }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The answer, once it has arrived.
|
||||||
|
pub fn take(&self) -> Option<Result<ehttp::Response, String>> {
|
||||||
|
self.slot.lock().ok().and_then(|mut slot| slot.take())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ask for the view of a range.
|
||||||
|
pub fn view(range: Range) -> ehttp::Request {
|
||||||
|
ehttp::Request::get(format!("/api/view?range={}", range.code()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ask the server to zero sccache's counters.
|
||||||
|
pub fn zero() -> ehttp::Request {
|
||||||
|
ehttp::Request::post("/api/zero", Vec::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The view inside a server answer.
|
||||||
|
pub fn view_from(answer: Result<ehttp::Response, String>) -> Result<View, String> {
|
||||||
|
let response = answer?;
|
||||||
|
if !response.ok {
|
||||||
|
return Err(format!(
|
||||||
|
"the server answered {} {}{}",
|
||||||
|
response.status,
|
||||||
|
response.status_text,
|
||||||
|
body_hint(response.text())
|
||||||
|
));
|
||||||
|
}
|
||||||
|
serde_json::from_slice(&response.bytes)
|
||||||
|
.map_err(|error| format!("the server's answer could not be read ({error})"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a request that changes something was accepted.
|
||||||
|
pub fn accepted(answer: Result<ehttp::Response, String>) -> Result<(), String> {
|
||||||
|
let response = answer?;
|
||||||
|
if response.ok {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(format!(
|
||||||
|
"the server answered {} {}{}",
|
||||||
|
response.status,
|
||||||
|
response.status_text,
|
||||||
|
body_hint(response.text())
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body_hint(body: Option<&str>) -> String {
|
||||||
|
let body = body.map_or("", |body| body.trim());
|
||||||
|
if body.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
let shown: String = body.chars().take(200).collect();
|
||||||
|
format!(": {shown}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Have the browser download a file the server serves.
|
||||||
|
pub fn download(url: &str) -> Result<(), String> {
|
||||||
|
#[cfg(target_arch = "wasm32")]
|
||||||
|
{
|
||||||
|
use wasm_bindgen::JsCast;
|
||||||
|
|
||||||
|
let document = web_sys::window()
|
||||||
|
.and_then(|window| window.document())
|
||||||
|
.ok_or("the browser has no document")?;
|
||||||
|
let element = document
|
||||||
|
.create_element("a")
|
||||||
|
.map_err(|error| error.as_string().unwrap_or_default())?;
|
||||||
|
let link = element
|
||||||
|
.dyn_into::<web_sys::HtmlAnchorElement>()
|
||||||
|
.map_err(|_| "the browser could not make a download link".to_owned())?;
|
||||||
|
link.set_href(url);
|
||||||
|
link.set_attribute("download", "")
|
||||||
|
.map_err(|error| error.as_string().unwrap_or_default())?;
|
||||||
|
link.click();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(target_arch = "wasm32"))]
|
||||||
|
{
|
||||||
|
let _ = url;
|
||||||
|
Err("saving files is only wired up for the browser".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,397 @@
|
|||||||
|
//! Over time: hit rate and compile volume per bucket, with a language filter.
|
||||||
|
//! Both charts always show the whole selected range; time nothing was recorded
|
||||||
|
//! in is tinted and labelled once.
|
||||||
|
|
||||||
|
use eframe::egui::{self, Stroke, Ui};
|
||||||
|
use egui_plot::{
|
||||||
|
Bar, BarChart, CoordinatesFormatter, Corner, GridInput, GridMark, Line, LineStyle, Plot,
|
||||||
|
PlotBounds, PlotPoint, PlotPoints, PlotResponse, PlotUi, Span, VLine,
|
||||||
|
};
|
||||||
|
use sccache_dash_api::{Bucket, Range, View};
|
||||||
|
|
||||||
|
use crate::fmt;
|
||||||
|
use crate::style;
|
||||||
|
use crate::theme;
|
||||||
|
|
||||||
|
/// Hits out of the cacheable compiles; `None` when there were none.
|
||||||
|
pub fn hit_rate(hits: u64, misses: u64) -> Option<f64> {
|
||||||
|
(hits + misses > 0).then(|| hits as f64 / (hits + misses) as f64)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn axes_of(view: &View, dark: bool) -> Axes {
|
||||||
|
let step = bucket_step(&view.buckets, view.range);
|
||||||
|
Axes {
|
||||||
|
window: range_window(view, step),
|
||||||
|
step,
|
||||||
|
tz: fmt::local_offset() as f64,
|
||||||
|
dark,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of the "Hit rate over time" panel.
|
||||||
|
pub fn hit_rate_panel(ui: &mut Ui, view: &View, hidden: &[String], chart_height: f32) {
|
||||||
|
let axes = axes_of(view, theme::ui(ui).dark);
|
||||||
|
hit_rate_chart(ui, view, hidden, axes, chart_height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The body of the "Compiles over time" panel.
|
||||||
|
pub fn volume_panel(ui: &mut Ui, view: &View, hidden: &[String], chart_height: f32) {
|
||||||
|
let axes = axes_of(view, theme::ui(ui).dark);
|
||||||
|
volume_chart(ui, view, hidden, axes, chart_height);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The title of one part of a panel, in the style of a panel title.
|
||||||
|
pub fn part_title(ui: &mut Ui, text: &str) {
|
||||||
|
ui.add(egui::Label::new(theme::title(ui, text)).truncate());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checkboxes that narrow both charts to some languages.
|
||||||
|
pub fn filter(ui: &mut Ui, view: &View, hidden: &mut Vec<String>) {
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = theme::space::PANEL_GAP;
|
||||||
|
let mut all = hidden.is_empty();
|
||||||
|
if ui.checkbox(&mut all, "All languages").changed() {
|
||||||
|
*hidden = fmt::hidden_after_all(all, view.languages.iter().map(|l| l.name.as_str()));
|
||||||
|
}
|
||||||
|
for language in &view.languages {
|
||||||
|
let mut ticked = !hidden.iter().any(|name| name == &language.name);
|
||||||
|
if ui.checkbox(&mut ticked, language.name.as_str()).changed() {
|
||||||
|
if ticked {
|
||||||
|
hidden.retain(|name| name != &language.name);
|
||||||
|
} else {
|
||||||
|
hidden.push(language.name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if !hidden.is_empty() {
|
||||||
|
ui.add(
|
||||||
|
egui::Label::new(
|
||||||
|
theme::small(
|
||||||
|
ui,
|
||||||
|
"Only the chosen languages are counted. The other outcomes can't be split by \
|
||||||
|
language, so they're left out.",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many seconds each bucket covers.
|
||||||
|
fn bucket_step(buckets: &[Bucket], range: Option<Range>) -> f64 {
|
||||||
|
let length = match range {
|
||||||
|
Some(Range::Hour) => 3_600.0,
|
||||||
|
Some(Range::Day) => 86_400.0,
|
||||||
|
Some(Range::Week) => 604_800.0,
|
||||||
|
Some(Range::Month) => 2_592_000.0,
|
||||||
|
_ => 7_200.0,
|
||||||
|
};
|
||||||
|
match buckets.len() {
|
||||||
|
0 | 1 => length / 120.0,
|
||||||
|
count => (buckets[count - 1].start - buckets[0].start) as f64 / (count - 1) as f64,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole selected range as Unix seconds (start, end): a fixed-length range
|
||||||
|
/// runs back from now by its length, whatever the buckets cover; "since reset"
|
||||||
|
/// runs from the first bucket to the last one's end.
|
||||||
|
fn range_window(view: &View, step: f64) -> (f64, f64) {
|
||||||
|
let now = view.generated_at as f64;
|
||||||
|
let (first, last) = match (view.buckets.first(), view.buckets.last()) {
|
||||||
|
(Some(first), Some(last)) => (first.start as f64, last.start as f64 + step),
|
||||||
|
_ => (now - step, now),
|
||||||
|
};
|
||||||
|
match view.range {
|
||||||
|
Some(Range::Hour) => (now - 3_600.0, now),
|
||||||
|
Some(Range::Day) => (now - 86_400.0, now),
|
||||||
|
Some(Range::Week) => (now - 604_800.0, now),
|
||||||
|
Some(Range::Month) => (now - 2_592_000.0, now),
|
||||||
|
_ => (first, last.max(first + step)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stretches of the window no recorded bucket covers.
|
||||||
|
fn unrecorded(buckets: &[Bucket], window: (f64, f64), step: f64) -> Vec<(f64, f64)> {
|
||||||
|
let mut stretches = Vec::new();
|
||||||
|
let mut cursor = window.0;
|
||||||
|
for bucket in buckets.iter().filter(|bucket| !bucket.gap) {
|
||||||
|
let (from, to) = (bucket.start as f64, bucket.start as f64 + step);
|
||||||
|
if from > cursor {
|
||||||
|
stretches.push((cursor, from));
|
||||||
|
}
|
||||||
|
cursor = cursor.max(to);
|
||||||
|
}
|
||||||
|
if cursor < window.1 {
|
||||||
|
stretches.push((cursor, window.1));
|
||||||
|
}
|
||||||
|
stretches
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What both charts share.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
struct Axes {
|
||||||
|
/// Start and end of the range in Unix seconds.
|
||||||
|
window: (f64, f64),
|
||||||
|
/// Seconds per bucket.
|
||||||
|
step: f64,
|
||||||
|
/// Seconds to add to a Unix time to get local clock time.
|
||||||
|
tz: f64,
|
||||||
|
dark: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A chart with a time axis over the whole range: clock times as ticks and a
|
||||||
|
/// readout of where the pointer is. It can't be zoomed or dragged, so the wheel
|
||||||
|
/// and a finger keep scrolling the page; that also means it can fit its data
|
||||||
|
/// afresh every frame, so new buckets are never cut off. A little air either
|
||||||
|
/// side keeps the first and last time label inside the plot.
|
||||||
|
fn time_plot<'a>(
|
||||||
|
name: &'static str,
|
||||||
|
axes: Axes,
|
||||||
|
height: f32,
|
||||||
|
readout: impl Fn(&PlotPoint) -> String + 'a,
|
||||||
|
) -> Plot<'a> {
|
||||||
|
let (first, last) = (axes.window.0 + axes.tz, axes.window.1 + axes.tz);
|
||||||
|
let span = last - first;
|
||||||
|
let air = span * theme::drawing::CHART_SIDE_AIR;
|
||||||
|
let tick = fmt::tick_step(span);
|
||||||
|
let label_font = egui::FontId::proportional(theme::px::SMALL);
|
||||||
|
let label_color = theme::of(axes.dark).muted;
|
||||||
|
let (from, to) = (first, last);
|
||||||
|
Plot::new(name)
|
||||||
|
.height(height)
|
||||||
|
.show_background(false)
|
||||||
|
.grid_color(theme::of(axes.dark).grid)
|
||||||
|
.allow_scroll(false)
|
||||||
|
.allow_drag(false)
|
||||||
|
.allow_zoom(false)
|
||||||
|
.allow_boxed_zoom(false)
|
||||||
|
.custom_x_axes(vec![egui_plot::AxisHints::new_x()
|
||||||
|
.tick_label_font(label_font.clone())
|
||||||
|
.tick_label_color(label_color)])
|
||||||
|
.custom_y_axes(vec![egui_plot::AxisHints::new_y()
|
||||||
|
.tick_label_font(label_font)
|
||||||
|
.tick_label_color(label_color)])
|
||||||
|
// The range and a little air either side, so the edge labels are not cut off.
|
||||||
|
.default_x_bounds(first - air, last + air)
|
||||||
|
.x_grid_spacer(move |input: GridInput| {
|
||||||
|
ticks(input.bounds.0, input.bounds.1, tick)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|mark| mark.value >= from && mark.value <= to)
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.x_axis_formatter(move |mark: GridMark, _range| {
|
||||||
|
fmt::tick_label(mark.value.round() as i64, tick)
|
||||||
|
})
|
||||||
|
.coordinates_formatter(
|
||||||
|
Corner::LeftTop,
|
||||||
|
CoordinatesFormatter::new(move |point: &PlotPoint, _bounds: &PlotBounds| readout(point)),
|
||||||
|
)
|
||||||
|
.reset()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ticks(from: f64, to: f64, tick: i64) -> Vec<GridMark> {
|
||||||
|
let tick = tick.max(1);
|
||||||
|
let first = from.ceil() as i64;
|
||||||
|
let mut value = first - first.rem_euclid(tick);
|
||||||
|
let mut marks = Vec::new();
|
||||||
|
while value as f64 <= to {
|
||||||
|
marks.push(GridMark {
|
||||||
|
value: value as f64,
|
||||||
|
step_size: tick as f64,
|
||||||
|
});
|
||||||
|
value += tick;
|
||||||
|
}
|
||||||
|
marks
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resets as dashed lines, and everything unrecorded as one tinted band per stretch.
|
||||||
|
fn marks(plot: &mut PlotUi<'_>, buckets: &[Bucket], axes: Axes) {
|
||||||
|
let p = theme::of(axes.dark);
|
||||||
|
for bucket in buckets {
|
||||||
|
if bucket.reset {
|
||||||
|
plot.vline(
|
||||||
|
VLine::new("Reset", bucket.start as f64 + axes.tz)
|
||||||
|
.stroke(Stroke::new(1.5, p.warn))
|
||||||
|
.style(LineStyle::Dashed { length: 12.0 }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (from, to) in unrecorded(buckets, axes.window, axes.step) {
|
||||||
|
plot.span(
|
||||||
|
Span::new("Not recorded", (from + axes.tz)..=(to + axes.tz))
|
||||||
|
.fill(p.unrecorded)
|
||||||
|
.border_width(0.0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether there is anything to mark: a reset, or time nothing was recorded in.
|
||||||
|
fn marked(buckets: &[Bucket], axes: Axes) -> (bool, bool) {
|
||||||
|
let any_reset = buckets.iter().any(|bucket| bucket.reset);
|
||||||
|
let any_gap = !unrecorded(buckets, axes.window, axes.step).is_empty();
|
||||||
|
(any_reset, any_gap)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn overlay(ui: &mut Ui, chart: &PlotResponse<()>, text: &str) {
|
||||||
|
ui.painter().text(
|
||||||
|
chart.response.rect.center(),
|
||||||
|
egui::Align2::CENTER_CENTER,
|
||||||
|
text,
|
||||||
|
egui::FontId::proportional(theme::px::SMALL),
|
||||||
|
theme::ui(ui).muted,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hits and misses of a bucket, for the languages that are ticked.
|
||||||
|
fn split(bucket: &Bucket, hidden: &[String]) -> (u64, u64) {
|
||||||
|
if hidden.is_empty() {
|
||||||
|
(bucket.hits, bucket.misses)
|
||||||
|
} else {
|
||||||
|
bucket
|
||||||
|
.languages
|
||||||
|
.iter()
|
||||||
|
.filter(|(name, _, _)| !hidden.contains(name))
|
||||||
|
.fold((0, 0), |(hits, misses), (_, hits_here, misses_here)| {
|
||||||
|
(hits + hits_here, misses + misses_here)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hit_rate_chart(ui: &mut Ui, view: &View, hidden: &[String], axes: Axes, height: f32) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
// One line per stretch of buckets that have a hit rate.
|
||||||
|
let mut runs: Vec<Vec<PlotPoint>> = Vec::new();
|
||||||
|
let mut run: Vec<PlotPoint> = Vec::new();
|
||||||
|
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
|
||||||
|
let (hits, misses) = split(bucket, hidden);
|
||||||
|
match hit_rate(hits, misses) {
|
||||||
|
Some(rate) => run.push(PlotPoint::new(
|
||||||
|
bucket.start as f64 + axes.tz,
|
||||||
|
rate * 100.0,
|
||||||
|
)),
|
||||||
|
None if !run.is_empty() => runs.push(std::mem::take(&mut run)),
|
||||||
|
None => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !run.is_empty() {
|
||||||
|
runs.push(run);
|
||||||
|
}
|
||||||
|
|
||||||
|
let plot = time_plot(
|
||||||
|
"hit-rate-chart",
|
||||||
|
axes,
|
||||||
|
height,
|
||||||
|
|point| format!("{} · {:.0}%", fmt::moment_text(point.x.round() as i64), point.y),
|
||||||
|
)
|
||||||
|
.default_y_bounds(0.0, 100.0)
|
||||||
|
// A mark every quarter, so the axis reads 0%, 25%, 50%, 75%, 100%.
|
||||||
|
.y_grid_spacer(|_: GridInput| {
|
||||||
|
(0..=4)
|
||||||
|
.map(|quarter| GridMark {
|
||||||
|
value: quarter as f64 * 25.0,
|
||||||
|
step_size: 25.0,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.y_axis_formatter(|mark: GridMark, _| format!("{:.0}%", mark.value));
|
||||||
|
let chart = plot.show(ui, |plot| {
|
||||||
|
marks(plot, &view.buckets, axes);
|
||||||
|
for points in &runs {
|
||||||
|
plot.line(
|
||||||
|
Line::new("Hit rate", PlotPoints::Owned(points.clone()))
|
||||||
|
.color(p.from_cache)
|
||||||
|
.width(2.0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if runs.is_empty() {
|
||||||
|
overlay(ui, &chart, "No cacheable compiles in this range");
|
||||||
|
}
|
||||||
|
let (any_reset, any_gap) = marked(&view.buckets, axes);
|
||||||
|
let mut entries = vec![(style::Mark::Line(p.from_cache), "Hit rate".to_owned())];
|
||||||
|
if any_reset {
|
||||||
|
entries.push((style::Mark::Dashed(p.warn), "Reset".to_owned()));
|
||||||
|
}
|
||||||
|
if any_gap {
|
||||||
|
entries.push((style::Mark::Band, "Not recorded".to_owned()));
|
||||||
|
}
|
||||||
|
style::legend(ui, entries);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn volume_chart(ui: &mut Ui, view: &View, hidden: &[String], axes: Axes, height: f32) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
// The tallest stack of one bucket, with a little air above it.
|
||||||
|
let top = view
|
||||||
|
.buckets
|
||||||
|
.iter()
|
||||||
|
.filter(|bucket| !bucket.gap)
|
||||||
|
.fold(4.0_f64, |top, bucket| {
|
||||||
|
let (hits, misses) = split(bucket, hidden);
|
||||||
|
let other = if hidden.is_empty() { bucket.other } else { 0 };
|
||||||
|
top.max((hits + misses + other) as f64 * 1.1)
|
||||||
|
});
|
||||||
|
let plot = time_plot(
|
||||||
|
"volume-chart",
|
||||||
|
axes,
|
||||||
|
height,
|
||||||
|
|point| fmt::moment_text(point.x.round() as i64),
|
||||||
|
)
|
||||||
|
.default_y_bounds(0.0, top)
|
||||||
|
.y_axis_formatter(|mark: GridMark, _| fmt::count(mark.value.max(0.0).round() as u64));
|
||||||
|
|
||||||
|
let width = axes.step * 0.8;
|
||||||
|
let (mut from_cache, mut built, mut other) = (vec![], vec![], vec![]);
|
||||||
|
let mut any = false;
|
||||||
|
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
|
||||||
|
let x = bucket.start as f64 + axes.tz;
|
||||||
|
let (hits, misses) = split(bucket, hidden);
|
||||||
|
for (bars, count) in [
|
||||||
|
(&mut from_cache, hits),
|
||||||
|
(&mut built, misses),
|
||||||
|
(&mut other, bucket.other),
|
||||||
|
] {
|
||||||
|
if count > 0 {
|
||||||
|
bars.push(Bar::new(x, count as f64));
|
||||||
|
any = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let chart = plot.show(ui, |plot| {
|
||||||
|
marks(plot, &view.buckets, axes);
|
||||||
|
let from_cache = BarChart::new("From cache", from_cache)
|
||||||
|
.width(width)
|
||||||
|
.color(p.from_cache);
|
||||||
|
let built = BarChart::new("Built", built)
|
||||||
|
.width(width)
|
||||||
|
.color(p.built);
|
||||||
|
let other = BarChart::new("Not cacheable and other", other)
|
||||||
|
.width(width)
|
||||||
|
.color(p.not_cacheable);
|
||||||
|
let built = built.stack_on(&[&from_cache]);
|
||||||
|
let other = other.stack_on(&[&built]);
|
||||||
|
plot.bar_chart(from_cache);
|
||||||
|
plot.bar_chart(built);
|
||||||
|
if hidden.is_empty() {
|
||||||
|
plot.bar_chart(other);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
if !any {
|
||||||
|
overlay(ui, &chart, "Nothing recorded in this range");
|
||||||
|
}
|
||||||
|
let (any_reset, any_gap) = marked(&view.buckets, axes);
|
||||||
|
let mut entries = vec![
|
||||||
|
(style::Mark::Fill(p.from_cache), "From cache".to_owned()),
|
||||||
|
(style::Mark::Fill(p.built), "Built".to_owned()),
|
||||||
|
];
|
||||||
|
if hidden.is_empty() {
|
||||||
|
entries.push((style::Mark::Fill(p.not_cacheable), "Not cacheable and other".to_owned()));
|
||||||
|
}
|
||||||
|
if any_reset {
|
||||||
|
entries.push((style::Mark::Dashed(p.warn), "Reset".to_owned()));
|
||||||
|
}
|
||||||
|
if any_gap {
|
||||||
|
entries.push((style::Mark::Band, "Not recorded".to_owned()));
|
||||||
|
}
|
||||||
|
style::legend(ui, entries);
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
//! Problems: what is wrong, most serious first, as the list under the hero's problem
|
||||||
|
//! count. Each problem is a line (a square for how serious, its title, a chevron); clicking
|
||||||
|
//! it shows the full explanation under it, as the reasons list does. The list scrolls inside
|
||||||
|
//! a fixed height, so a longer list or an open explanation never moves the page.
|
||||||
|
|
||||||
|
use eframe::egui::{self, Sense, Ui};
|
||||||
|
use sccache_dash_api::{Severity, View};
|
||||||
|
|
||||||
|
use crate::theme;
|
||||||
|
use crate::where_went::chevron;
|
||||||
|
|
||||||
|
const ROW: f32 = 22.0;
|
||||||
|
const GAP: f32 = 8.0;
|
||||||
|
const CHEVRON: f32 = 8.0;
|
||||||
|
|
||||||
|
fn open_id(title: &str) -> egui::Id {
|
||||||
|
egui::Id::new(("problem-open", title))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The problems of `view` in a list `height` tall.
|
||||||
|
pub fn hero_list(ui: &mut Ui, view: &View, height: f32) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
if view.problems.is_empty() {
|
||||||
|
ui.add(egui::Label::new(theme::small(ui, "Nothing needs attention.")).truncate());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
egui::ScrollArea::vertical()
|
||||||
|
.id_salt("hero-problems")
|
||||||
|
.max_height(height)
|
||||||
|
.auto_shrink([false, false])
|
||||||
|
.show(ui, |ui| {
|
||||||
|
ui.spacing_mut().item_spacing.y = 0.0;
|
||||||
|
let width = ui.available_width();
|
||||||
|
let indent = theme::drawing::SEVERITY_DOT + GAP;
|
||||||
|
for problem in &view.problems {
|
||||||
|
let id = open_id(&problem.title);
|
||||||
|
let open = ui.ctx().data(|data| data.get_temp::<bool>(id)).unwrap_or(false);
|
||||||
|
let (row, response) = ui.allocate_exact_size(egui::vec2(width, ROW), Sense::click());
|
||||||
|
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||||
|
response.widget_info(|| {
|
||||||
|
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, problem.title.as_str())
|
||||||
|
});
|
||||||
|
if response.clicked() {
|
||||||
|
ui.ctx().data_mut(|data| data.insert_temp(id, !open));
|
||||||
|
ui.ctx().request_repaint();
|
||||||
|
}
|
||||||
|
if response.hovered() {
|
||||||
|
ui.painter().rect_filled(row, theme::space::CONTROL_RADIUS, p.hover);
|
||||||
|
}
|
||||||
|
let color = match problem.severity {
|
||||||
|
Severity::Error => p.bad,
|
||||||
|
Severity::Warning => p.warn,
|
||||||
|
};
|
||||||
|
let side = theme::drawing::SEVERITY_DOT;
|
||||||
|
ui.painter().rect_filled(
|
||||||
|
egui::Rect::from_center_size(egui::pos2(row.left() + side / 2.0, row.center().y), egui::vec2(side, side)),
|
||||||
|
0.0,
|
||||||
|
color,
|
||||||
|
);
|
||||||
|
let chevron_x = row.right() - CHEVRON;
|
||||||
|
chevron(ui.painter(), egui::pos2(chevron_x + CHEVRON / 2.0, row.center().y), open, p.muted);
|
||||||
|
let title = crate::style::galley(ui, theme::body(problem.title.clone()), false, f32::INFINITY);
|
||||||
|
let room = (chevron_x - GAP - row.left() - indent).max(10.0);
|
||||||
|
let place = egui::Rect::from_min_size(egui::pos2(row.left() + indent, row.top()), egui::vec2(room, ROW));
|
||||||
|
ui.painter().with_clip_rect(place).galley(
|
||||||
|
egui::pos2(place.left(), row.center().y - title.size().y / 2.0),
|
||||||
|
title,
|
||||||
|
p.text,
|
||||||
|
);
|
||||||
|
if open {
|
||||||
|
let detail = crate::style::galley(ui, theme::small(ui, problem.detail.clone()), true, width - indent);
|
||||||
|
let (place, _) = ui.allocate_exact_size(egui::vec2(width, detail.size().y + 6.0), Sense::hover());
|
||||||
|
ui.painter().galley(egui::pos2(place.left() + indent, place.top()), detail, p.muted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
//! Raw counters: the sccache stats exactly as the server read them, as compact
|
||||||
|
//! key/value lines that flow in columns. The panel opens and closes; it starts
|
||||||
|
//! closed, as one line.
|
||||||
|
|
||||||
|
use std::cell::Cell;
|
||||||
|
|
||||||
|
use eframe::egui::{self, Pos2, Rect, Sense, Ui};
|
||||||
|
use sccache_dash_api::View;
|
||||||
|
|
||||||
|
use crate::style;
|
||||||
|
use crate::theme;
|
||||||
|
|
||||||
|
/// Every leaf of the JSON as its dotted path and its value as text.
|
||||||
|
fn leaves(value: &serde_json::Value, path: String, out: &mut Vec<(String, String)>) {
|
||||||
|
match value {
|
||||||
|
serde_json::Value::Object(fields) => {
|
||||||
|
for (name, value) in fields {
|
||||||
|
let path = if path.is_empty() { name.clone() } else { format!("{path}.{name}") };
|
||||||
|
leaves(value, path, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
serde_json::Value::Array(items) => {
|
||||||
|
for (index, value) in items.iter().enumerate() {
|
||||||
|
leaves(value, format!("{path}[{index}]"), out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
leaf => out.push((
|
||||||
|
path,
|
||||||
|
match leaf {
|
||||||
|
serde_json::Value::String(text) => text.clone(),
|
||||||
|
serde_json::Value::Null => "null".to_owned(),
|
||||||
|
number => number.to_string(),
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many columns of key/value lines fit in a panel's `inner` width.
|
||||||
|
fn columns(inner: f32) -> usize {
|
||||||
|
let gap = theme::space::PANEL_GAP + 4.0;
|
||||||
|
(((inner + gap) / (theme::layout::RAW_LINE_WIDTH + gap)) as usize).clamp(1, 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How tall the panel is when it is `width` wide: its title and, when open,
|
||||||
|
/// its lines.
|
||||||
|
pub fn height(view: &View, width: f32, open: bool) -> f32 {
|
||||||
|
let title = theme::space::ROW + theme::space::UNDER_TITLE + 2.0 * theme::space::PANEL_PAD_Y;
|
||||||
|
if !open {
|
||||||
|
return title - theme::space::UNDER_TITLE + theme::space::LINE;
|
||||||
|
}
|
||||||
|
let mut lines = 0;
|
||||||
|
if !view.raw.is_null() {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
leaves(&view.raw, String::new(), &mut out);
|
||||||
|
lines = out.len();
|
||||||
|
}
|
||||||
|
let inner = width - 2.0 * theme::space::PANEL_PADDING;
|
||||||
|
title + lines.div_ceil(columns(inner)) as f32 * theme::space::ROW
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The panel at `rect`; its title opens and closes it. Returns the rect it took.
|
||||||
|
pub fn section(ui: &mut Ui, view: &View, rect: Rect) -> Rect {
|
||||||
|
let id = egui::Id::new("raw-counters-open");
|
||||||
|
let open = Cell::new(ui.ctx().data_mut(|data| data.get_temp::<bool>(id)).unwrap_or(false));
|
||||||
|
let (_, taken) = style::panel_titled(
|
||||||
|
ui,
|
||||||
|
rect,
|
||||||
|
|ui| {
|
||||||
|
let mut now = open.get();
|
||||||
|
style::toggling_title(ui, "Raw counters", &mut now);
|
||||||
|
open.set(now);
|
||||||
|
},
|
||||||
|
|ui| {
|
||||||
|
let open = open.get();
|
||||||
|
ui.ctx().data_mut(|data| data.insert_temp(id, open));
|
||||||
|
if !open {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match &view.raw {
|
||||||
|
serde_json::Value::Null => {
|
||||||
|
ui.label(theme::body("sccache's raw counters could not be read."));
|
||||||
|
}
|
||||||
|
value => {
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
leaves(value, String::new(), &mut lines);
|
||||||
|
flow(ui, &lines);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
taken
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Key/value lines in as many columns of the raw line width as fit, filled
|
||||||
|
/// left to right and then down: each line in its own cell, the key in small
|
||||||
|
/// print and the value in mono right after it.
|
||||||
|
fn flow(ui: &mut Ui, lines: &[(String, String)]) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let gap = theme::space::PANEL_GAP + 4.0;
|
||||||
|
let columns = columns(width);
|
||||||
|
let cell = (width - gap * (columns - 1) as f32) / columns as f32;
|
||||||
|
let font = egui::FontId::proportional(theme::px::SMALL);
|
||||||
|
let mono = theme::number_font(theme::px::SMALL);
|
||||||
|
for line in lines.chunks(columns) {
|
||||||
|
// One exact row of cells: a row is laid out, never wrapped, so every column is used.
|
||||||
|
ui.allocate_ui_with_layout(
|
||||||
|
egui::vec2(width, theme::space::ROW),
|
||||||
|
egui::Layout::left_to_right(egui::Align::Center),
|
||||||
|
|ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = gap;
|
||||||
|
for (key, value) in line {
|
||||||
|
let (rect, response) =
|
||||||
|
ui.allocate_exact_size(egui::vec2(cell, theme::space::ROW), Sense::hover());
|
||||||
|
let painter = ui.painter();
|
||||||
|
let clip = rect.intersect(ui.clip_rect());
|
||||||
|
let value_galley = painter.layout_no_wrap(value.clone(), mono.clone(), p.text);
|
||||||
|
let value_width = value_galley.size().x;
|
||||||
|
// The value follows its key by the key/value gap, not pushed to the cell's edge;
|
||||||
|
// where the two do not fit, the key ends in "…" and all of it shows on hover.
|
||||||
|
let key_room = (rect.width() - theme::space::KEY_VALUE_GAP - value_width).max(0.0);
|
||||||
|
let key_galley = painter.layout_no_wrap(key.clone(), font.clone(), p.muted);
|
||||||
|
let key_width = key_galley.size().x;
|
||||||
|
let cut = key_width > key_room;
|
||||||
|
let key_galley = if cut {
|
||||||
|
let mut chars = key.chars().count();
|
||||||
|
loop {
|
||||||
|
chars -= 1;
|
||||||
|
let shorter: String = key.chars().take(chars).collect::<String>() + "…";
|
||||||
|
let galley = painter.layout_no_wrap(shorter, font.clone(), p.muted);
|
||||||
|
if galley.size().x <= key_room || chars <= 1 {
|
||||||
|
break galley;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
key_galley
|
||||||
|
};
|
||||||
|
let key_width = key_galley.size().x;
|
||||||
|
painter.with_clip_rect(clip).galley(
|
||||||
|
Pos2::new(rect.left(), rect.center().y - key_galley.size().y / 2.0),
|
||||||
|
key_galley,
|
||||||
|
p.muted,
|
||||||
|
);
|
||||||
|
let value_left = rect.left() + key_width + theme::space::KEY_VALUE_GAP;
|
||||||
|
painter.with_clip_rect(clip).galley(
|
||||||
|
Pos2::new(value_left, rect.center().y - value_galley.size().y / 2.0),
|
||||||
|
value_galley,
|
||||||
|
p.text,
|
||||||
|
);
|
||||||
|
if cut || value_left + value_width > rect.right() {
|
||||||
|
response.on_hover_text(format!("{key} {value}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,210 @@
|
|||||||
|
//! Speed: how long a cache fetch, a cache write and a build take on average,
|
||||||
|
//! and how build times spread for each language.
|
||||||
|
|
||||||
|
use eframe::egui::{self, Pos2, Rect, Sense, Ui};
|
||||||
|
use sccache_dash_api::{BuildTimes, View};
|
||||||
|
|
||||||
|
use crate::fmt;
|
||||||
|
use crate::style;
|
||||||
|
use crate::theme;
|
||||||
|
|
||||||
|
/// The slowest build time the axis reaches, as log10 of milliseconds (1,000 s).
|
||||||
|
const AXIS_TOP: f64 = 6.0;
|
||||||
|
/// The width of the label and of the value beside each speed bar.
|
||||||
|
const LABEL_WIDTH: f32 = 128.0;
|
||||||
|
const VALUE_WIDTH: f32 = 60.0;
|
||||||
|
|
||||||
|
pub fn section(ui: &mut Ui, view: &View) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
let timing = view.timing;
|
||||||
|
let rows = [
|
||||||
|
("Cache fetch (a hit)", timing.avg_hit_read_ms, p.from_cache),
|
||||||
|
("Cache write", timing.avg_cache_write_ms, p.muted),
|
||||||
|
("Compile one crate", timing.avg_compile_ms, p.built),
|
||||||
|
];
|
||||||
|
for (label, ms, color) in rows {
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
|
||||||
|
let (label_rect, _) =
|
||||||
|
ui.allocate_exact_size(egui::vec2(LABEL_WIDTH, theme::space::ROW), Sense::hover());
|
||||||
|
let label = style::galley(ui, theme::body(label), false, f32::INFINITY);
|
||||||
|
ui.painter().with_clip_rect(label_rect).galley(
|
||||||
|
Pos2::new(label_rect.left(), label_rect.center().y - label.size().y / 2.0),
|
||||||
|
label,
|
||||||
|
p.text,
|
||||||
|
);
|
||||||
|
let text = ms.map_or("—".into(), |ms| fmt::duration(ms / 1000.0));
|
||||||
|
let value = style::galley(ui, theme::number(text), false, f32::INFINITY);
|
||||||
|
let value_rect = ui
|
||||||
|
.allocate_exact_size(egui::vec2(VALUE_WIDTH, theme::space::ROW), Sense::hover())
|
||||||
|
.0;
|
||||||
|
ui.painter().with_clip_rect(value_rect).galley(
|
||||||
|
Pos2::new(value_rect.right() - value.size().x, value_rect.center().y - value.size().y / 2.0),
|
||||||
|
value,
|
||||||
|
p.text,
|
||||||
|
);
|
||||||
|
let bar_rect = ui
|
||||||
|
.allocate_exact_size(
|
||||||
|
egui::vec2(ui.available_rect_before_wrap().width(), theme::space::ROW),
|
||||||
|
Sense::hover(),
|
||||||
|
)
|
||||||
|
.0;
|
||||||
|
let bar = Rect::from_center_size(
|
||||||
|
bar_rect.center(),
|
||||||
|
egui::vec2(bar_rect.width(), theme::drawing::SPEED_BAR),
|
||||||
|
);
|
||||||
|
style::fill_bar(ui, bar, ms.map_or(0.0, style::log_fraction), color);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let hit = timing.avg_hit_read_ms;
|
||||||
|
let write = timing.avg_cache_write_ms;
|
||||||
|
let build = timing.avg_compile_ms;
|
||||||
|
let sentence = if let Some(times) = faster(build, hit) {
|
||||||
|
format!("A cache hit is about {times}x faster than compiling the crate.")
|
||||||
|
} else if let Some(times) = faster(build, write) {
|
||||||
|
format!("Writing to the cache is about {times}x faster than compiling the crate.")
|
||||||
|
} else {
|
||||||
|
"There are no timings to compare in this range.".to_owned()
|
||||||
|
};
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
ui.add(egui::Label::new(theme::strong(sentence).color(p.hero)).wrap());
|
||||||
|
ui.add(
|
||||||
|
egui::Label::new(
|
||||||
|
theme::small(
|
||||||
|
ui,
|
||||||
|
"The bars use a log scale, so a fraction of a millisecond and several seconds are \
|
||||||
|
both visible.",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
build_times(ui, view);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `faster` is about how many times shorter than `slower`, when both are known and positive.
|
||||||
|
fn faster(slower: Option<f64>, faster: Option<f64>) -> Option<String> {
|
||||||
|
let (slower, faster) = (slower?, faster?);
|
||||||
|
(slower > 0.0 && faster > 0.0).then(|| fmt::round_number(slower / faster))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "How long one crate takes to compile": one histogram per language, all on the
|
||||||
|
/// same log scale of build time, with the mean, median and p90 marked.
|
||||||
|
fn build_times(ui: &mut Ui, view: &View) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
let languages: Vec<&BuildTimes> = view
|
||||||
|
.build_times
|
||||||
|
.iter()
|
||||||
|
.filter(|times| times.compiles > 0 && !times.bins.is_empty())
|
||||||
|
.collect();
|
||||||
|
if languages.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ui.add_space(theme::space::BETWEEN_PARTS);
|
||||||
|
crate::overtime::part_title(ui, "How long one crate takes to compile");
|
||||||
|
|
||||||
|
// One shared axis, from a quarter step before the fastest bin to a quarter step after the slowest.
|
||||||
|
let (mut low, mut high) = (f64::MAX, 0.0_f64);
|
||||||
|
for times in &languages {
|
||||||
|
for bin in ×.bins {
|
||||||
|
low = low.min(bin.from_ms);
|
||||||
|
high = high.max(bin.to_ms);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let low = (low.max(1.0).log10() - 0.25).max(0.0);
|
||||||
|
let high = (high.log10() + 0.25).min(AXIS_TOP);
|
||||||
|
|
||||||
|
for times in languages {
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
ui.horizontal(|ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
|
||||||
|
ui.add(egui::Label::new(theme::strong(times.language.clone())).truncate());
|
||||||
|
ui.add(egui::Label::new(theme::small(ui, format!("{} compiles", fmt::count(times.compiles)))).truncate());
|
||||||
|
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
|
||||||
|
for (name, value, color) in [
|
||||||
|
("p90", times.p90_ms, p.p90),
|
||||||
|
("median", times.median_ms, p.median),
|
||||||
|
("mean", times.mean_ms, p.mean),
|
||||||
|
] {
|
||||||
|
ui.label(theme::small(ui, format!("{name} {}", ms(value))).color(color));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
histogram(ui, times, low, high, p);
|
||||||
|
axis(ui, low, high);
|
||||||
|
}
|
||||||
|
ui.add(
|
||||||
|
egui::Label::new(
|
||||||
|
theme::small(
|
||||||
|
ui,
|
||||||
|
"Each point is the average of the builds that finished within one 10-second reading.",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ms(value: f64) -> String {
|
||||||
|
fmt::duration(value / 1000.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bins as bars, build time along the bottom on a log scale, with a line
|
||||||
|
/// for the mean, median and p90.
|
||||||
|
fn histogram(ui: &mut Ui, times: &BuildTimes, low: f64, high: f64, p: &theme::Palette) {
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let (rect, response) = ui.allocate_exact_size(
|
||||||
|
egui::vec2(width, theme::drawing::BUILD_HISTOGRAM),
|
||||||
|
Sense::hover(),
|
||||||
|
);
|
||||||
|
let painter = ui.painter();
|
||||||
|
painter.hline(rect.x_range(), rect.bottom() - 0.5, egui::Stroke::new(1.0, p.grid));
|
||||||
|
let at = |value: f64| {
|
||||||
|
let position = ((value.max(1.0).log10() - low) / (high - low)).clamp(0.0, 1.0);
|
||||||
|
rect.left() + rect.width() * position as f32
|
||||||
|
};
|
||||||
|
let top = times.bins.iter().map(|bin| bin.compiles).max().unwrap_or(0);
|
||||||
|
for bin in ×.bins {
|
||||||
|
if bin.compiles == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let height = theme::drawing::BUILD_HISTOGRAM * bin.compiles as f32 / top.max(1) as f32;
|
||||||
|
let bar = Rect::from_min_max(
|
||||||
|
Pos2::new(at(bin.from_ms), rect.bottom() - height),
|
||||||
|
Pos2::new((at(bin.to_ms) - 1.0).max(at(bin.from_ms) + 1.0), rect.bottom()),
|
||||||
|
);
|
||||||
|
painter.rect_filled(bar, 1.0, p.built);
|
||||||
|
}
|
||||||
|
for (value, color) in [times.mean_ms, times.median_ms, times.p90_ms].into_iter().zip([p.mean, p.median, p.p90]) {
|
||||||
|
let x = at(value);
|
||||||
|
painter.rect_filled(
|
||||||
|
Rect::from_min_max(Pos2::new(x, rect.top()), Pos2::new(x + 2.0, rect.bottom())),
|
||||||
|
0.0,
|
||||||
|
color,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
response.on_hover_text(format!(
|
||||||
|
"{} builds: mean {}, median {}, p90 {}",
|
||||||
|
fmt::count(times.compiles),
|
||||||
|
ms(times.mean_ms),
|
||||||
|
ms(times.median_ms),
|
||||||
|
ms(times.p90_ms)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The times along the bottom of a histogram: one mark every tenfold step.
|
||||||
|
fn axis(ui: &mut Ui, low: f64, high: f64) {
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, theme::drawing::BUILD_AXIS), Sense::hover());
|
||||||
|
let font = egui::FontId::proportional(theme::px::SMALL);
|
||||||
|
for step in 0..=AXIS_TOP as i64 {
|
||||||
|
let value = step as f64;
|
||||||
|
if value < low || value > high {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let x = rect.left() + rect.width() * ((value - low) / (high - low)) as f32;
|
||||||
|
let text = ms(10.0_f64.powf(value));
|
||||||
|
let galley = ui.painter().layout_no_wrap(text, font.clone(), p.muted);
|
||||||
|
let x = x.clamp(rect.left(), rect.right() - galley.size().x);
|
||||||
|
ui.painter().galley(Pos2::new(x, rect.center().y - galley.size().y / 2.0), galley, p.muted);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,630 @@
|
|||||||
|
//! Drawings shared by the panels: the grid, panels, cards, tables, bars and
|
||||||
|
//! chart keys. Every colour and size comes from [`crate::theme`].
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use eframe::egui::{self, Align, Align2, Color32, Galley, Layout, Pos2, Rect, RichText, Sense, Shape, Stroke, StrokeKind, Ui};
|
||||||
|
use egui::TextWrapMode;
|
||||||
|
|
||||||
|
use crate::theme::{self, px, space};
|
||||||
|
|
||||||
|
/// The palette of the theme being drawn.
|
||||||
|
pub fn p(ui: &Ui) -> &'static theme::Palette {
|
||||||
|
theme::ui(ui)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The width of `text` in `font`.
|
||||||
|
pub fn text_width(ui: &Ui, text: &str, font: egui::FontId) -> f32 {
|
||||||
|
ui.painter()
|
||||||
|
.layout_no_wrap(text.to_owned(), font, theme::ui(ui).text)
|
||||||
|
.size()
|
||||||
|
.x
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lay `text` out: on one line, or wrapped at `width` when `wrap` is set.
|
||||||
|
pub fn galley(ui: &Ui, text: RichText, wrap: bool, width: f32) -> Arc<Galley> {
|
||||||
|
egui::WidgetText::from(text).into_galley(
|
||||||
|
ui,
|
||||||
|
Some(if wrap { TextWrapMode::Wrap } else { TextWrapMode::Extend }),
|
||||||
|
width,
|
||||||
|
egui::FontSelection::Default,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A colour made see-through.
|
||||||
|
pub fn tint(color: Color32, share: f32) -> Color32 {
|
||||||
|
theme::tint(color, share)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- The grid ----
|
||||||
|
|
||||||
|
/// How wide a panel is that spans `span` of the `columns` columns of a row.
|
||||||
|
pub fn span_width(ui: &Ui, columns: usize, span: usize) -> f32 {
|
||||||
|
let all = ui.available_rect_before_wrap().width();
|
||||||
|
span_of(all, columns, span)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same, from the row's width instead of a `Ui`.
|
||||||
|
pub fn span_of(row_width: f32, columns: usize, span: usize) -> f32 {
|
||||||
|
let gaps = space::PANEL_GAP;
|
||||||
|
let one = (row_width - gaps * (columns as f32 - 1.0)) / columns as f32;
|
||||||
|
one * span as f32 + gaps * (span as f32 - 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the panels of a row go: one rectangle per entry of `spans` (each the
|
||||||
|
/// number of columns the panel spans), all `height` tall, starting at the
|
||||||
|
/// cursor. Nothing is allocated yet; [`end_row`] does that.
|
||||||
|
pub fn cells(ui: &Ui, height: f32, spans: &[usize]) -> Vec<Rect> {
|
||||||
|
let columns: usize = spans.iter().sum();
|
||||||
|
let top_left = ui.cursor().min;
|
||||||
|
let mut left = top_left.x;
|
||||||
|
spans
|
||||||
|
.iter()
|
||||||
|
.map(|span| {
|
||||||
|
let width = span_width(ui, columns, *span);
|
||||||
|
let rect = Rect::from_min_size(Pos2::new(left, top_left.y), egui::vec2(width, height));
|
||||||
|
left += width + space::PANEL_GAP;
|
||||||
|
rect
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close a row of panels drawn at `rects`: the cursor moves below the tallest.
|
||||||
|
pub fn end_row(ui: &mut Ui, rects: &[Rect]) {
|
||||||
|
let bottom = crate::fmt::lowest(rects.iter().map(|rect| rect.bottom()), ui.cursor().top());
|
||||||
|
let left = rects.first().map_or(ui.cursor().left(), |rect| rect.left());
|
||||||
|
ui.allocate_rect(
|
||||||
|
Rect::from_min_max(Pos2::new(left, ui.cursor().top()), Pos2::new(ui.cursor().right(), bottom)),
|
||||||
|
Sense::hover(),
|
||||||
|
);
|
||||||
|
ui.add_space(space::PANEL_GAP);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A hairline across the panel at the cursor.
|
||||||
|
pub fn rule(ui: &mut Ui) {
|
||||||
|
let (rect, _) = ui.allocate_exact_size(
|
||||||
|
egui::vec2(ui.available_rect_before_wrap().width(), 1.0),
|
||||||
|
Sense::hover(),
|
||||||
|
);
|
||||||
|
ui.painter()
|
||||||
|
.hline(rect.x_range(), rect.top() + 0.5, Stroke::new(1.0, p(ui).border));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Panels and cards ----
|
||||||
|
|
||||||
|
/// A panel with a title, at `rect`: no fill and no box, a hairline across its top.
|
||||||
|
/// It comes out at least as tall as `rect`; the rect it took is returned second.
|
||||||
|
pub fn panel<R>(ui: &mut Ui, rect: Rect, title: &str, body: impl FnOnce(&mut Ui) -> R) -> (R, Rect) {
|
||||||
|
let text = theme::title(ui, title).text().to_owned();
|
||||||
|
panel_titled(
|
||||||
|
ui,
|
||||||
|
rect,
|
||||||
|
|ui| {
|
||||||
|
ui.add(egui::Label::new(theme::title(ui, text)).truncate());
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`panel`] with the title drawn by `title`: one line, `UNDER_TITLE` under it.
|
||||||
|
pub fn panel_titled<R>(
|
||||||
|
ui: &mut Ui,
|
||||||
|
rect: Rect,
|
||||||
|
title: impl FnOnce(&mut Ui),
|
||||||
|
body: impl FnOnce(&mut Ui) -> R,
|
||||||
|
) -> (R, Rect) {
|
||||||
|
let p = p(ui);
|
||||||
|
let pad = egui::vec2(space::PANEL_PADDING, space::PANEL_PAD_Y);
|
||||||
|
let mut inner = ui.new_child(
|
||||||
|
egui::UiBuilder::new()
|
||||||
|
.max_rect(rect.shrink2(pad))
|
||||||
|
.layout(Layout::top_down(Align::Min)),
|
||||||
|
);
|
||||||
|
inner.set_width((rect.width() - 2.0 * pad.x).max(0.0));
|
||||||
|
inner.set_min_height((rect.height() - 2.0 * pad.y).max(0.0));
|
||||||
|
inner.spacing_mut().item_spacing = egui::vec2(space::ITEM, space::LINE);
|
||||||
|
title(&mut inner);
|
||||||
|
inner.add_space(space::UNDER_TITLE);
|
||||||
|
let value = body(&mut inner);
|
||||||
|
let taken = inner.min_rect().expand2(pad);
|
||||||
|
ui.painter().hline(taken.x_range(), taken.top() + 0.5, Stroke::new(1.0, p.border));
|
||||||
|
(value, taken)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A message that must be noticed: the bad colour as a tint and a border, on
|
||||||
|
/// the panel colour.
|
||||||
|
pub fn banner(ui: &mut Ui, text: RichText, color: Color32) {
|
||||||
|
let p = p(ui);
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 40.0), Sense::hover());
|
||||||
|
ui.painter().rect(
|
||||||
|
rect,
|
||||||
|
space::CONTROL_RADIUS,
|
||||||
|
tint(color, 0.14),
|
||||||
|
Stroke::new(1.0, tint(color, 0.5)),
|
||||||
|
StrokeKind::Inside,
|
||||||
|
);
|
||||||
|
let galley = galley(
|
||||||
|
ui,
|
||||||
|
text.strong().font(theme::semibold(px::BODY)),
|
||||||
|
true,
|
||||||
|
width - 2.0 * space::PANEL_PADDING,
|
||||||
|
);
|
||||||
|
ui.painter().galley(
|
||||||
|
Pos2::new(rect.left() + space::PANEL_PADDING, rect.center().y - galley.size().y / 2.0),
|
||||||
|
galley,
|
||||||
|
p.text,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The title of a panel that opens and closes when clicked. `open` is read and
|
||||||
|
/// written through `toggle`; returns whether it is open after the click.
|
||||||
|
pub fn toggling_title(ui: &mut Ui, title: &str, open: &mut bool) -> bool {
|
||||||
|
let p = p(ui);
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let (rect, response) = ui.allocate_exact_size(egui::vec2(width, space::ROW), Sense::click());
|
||||||
|
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title));
|
||||||
|
if response.clicked() {
|
||||||
|
*open = !*open;
|
||||||
|
}
|
||||||
|
let painter = ui.painter();
|
||||||
|
let color = if response.hovered() { p.text } else { p.muted };
|
||||||
|
let galley = galley(ui, theme::title(ui, title).color(color), false, f32::INFINITY);
|
||||||
|
painter.galley(
|
||||||
|
Pos2::new(rect.left(), rect.center().y - galley.size().y / 2.0),
|
||||||
|
galley,
|
||||||
|
color,
|
||||||
|
);
|
||||||
|
// A small chevron at the right: down when open, right when closed.
|
||||||
|
let at = Pos2::new(rect.right() - 4.0, rect.center().y);
|
||||||
|
let stroke = Stroke::new(1.5, p.muted);
|
||||||
|
let points = if *open {
|
||||||
|
vec![
|
||||||
|
Pos2::new(at.x - 4.0, at.y - 2.0),
|
||||||
|
at,
|
||||||
|
Pos2::new(at.x + 4.0, at.y - 2.0),
|
||||||
|
]
|
||||||
|
} else {
|
||||||
|
vec![
|
||||||
|
Pos2::new(at.x - 2.0, at.y - 4.0),
|
||||||
|
at,
|
||||||
|
Pos2::new(at.x - 2.0, at.y + 4.0),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
painter.add(Shape::line(points, stroke));
|
||||||
|
*open
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One cell of the counter strip: a small upper-case label, the number in mono, one line of
|
||||||
|
/// small print and the change against the period before. Exactly `rect`; a hairline stands at
|
||||||
|
/// its left unless it is the first of its row.
|
||||||
|
pub fn card(ui: &mut Ui, rect: Rect, first: bool, label: &str, number: &str, detail: &str, change: RichText, color: Color32) {
|
||||||
|
let p = p(ui);
|
||||||
|
ui.allocate_rect(rect, Sense::hover());
|
||||||
|
let inset = if first { 0.0 } else { 16.0 };
|
||||||
|
if !first {
|
||||||
|
ui.painter().vline(rect.left() + 0.5, rect.y_range().shrink(10.0), Stroke::new(1.0, p.grid));
|
||||||
|
}
|
||||||
|
let inner_rect = Rect::from_min_max(
|
||||||
|
Pos2::new(rect.left() + inset, rect.top() + 10.0),
|
||||||
|
Pos2::new(rect.right() - 8.0, rect.bottom() - 6.0),
|
||||||
|
);
|
||||||
|
let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(inner_rect).layout(Layout::top_down(Align::Min)));
|
||||||
|
inner.set_width(inner_rect.width());
|
||||||
|
inner.spacing_mut().item_spacing = egui::vec2(space::ITEM, 1.0);
|
||||||
|
inner.add(egui::Label::new(theme::title(ui, label)).truncate());
|
||||||
|
inner.add(
|
||||||
|
egui::Label::new(
|
||||||
|
RichText::new(number)
|
||||||
|
.font(theme::number_font(px::CARD_NUMBER))
|
||||||
|
.color(color),
|
||||||
|
)
|
||||||
|
.truncate(),
|
||||||
|
);
|
||||||
|
let detail_label = inner.add(egui::Label::new(theme::small(ui, detail)).truncate());
|
||||||
|
if !detail.is_empty() {
|
||||||
|
detail_label.on_hover_text(detail);
|
||||||
|
}
|
||||||
|
inner.add(egui::Label::new(change).truncate());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Controls ----
|
||||||
|
|
||||||
|
/// One segmented control: `labels` side by side in one pill, the `chosen` one
|
||||||
|
/// marked with the accent. Returns the segment that was clicked.
|
||||||
|
pub fn segmented(ui: &mut Ui, id_salt: &'static str, labels: &[&str], chosen: usize) -> Option<usize> {
|
||||||
|
let p = p(ui);
|
||||||
|
let font = theme::medium(px::BODY);
|
||||||
|
let widths: Vec<f32> = labels
|
||||||
|
.iter()
|
||||||
|
.map(|label| text_width(ui, label, font.clone()) + 2.0 * space::CONTROL_PAD)
|
||||||
|
.collect();
|
||||||
|
let total: f32 = widths.iter().sum();
|
||||||
|
let (rect, _) = ui.allocate_exact_size(egui::vec2(total, space::CONTROL_HEIGHT), Sense::hover());
|
||||||
|
let painter = ui.painter();
|
||||||
|
painter.rect(
|
||||||
|
rect,
|
||||||
|
space::CONTROL_RADIUS,
|
||||||
|
p.track,
|
||||||
|
Stroke::new(1.0, p.border),
|
||||||
|
StrokeKind::Inside,
|
||||||
|
);
|
||||||
|
let mut left = rect.left();
|
||||||
|
let mut clicked = None;
|
||||||
|
for (index, (label, width)) in labels.iter().zip(&widths).enumerate() {
|
||||||
|
let segment = Rect::from_min_max(Pos2::new(left, rect.top()), Pos2::new(left + width, rect.bottom()));
|
||||||
|
let response = ui
|
||||||
|
.interact(segment, ui.scope_id().with(id_salt).with(index), Sense::click())
|
||||||
|
.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||||
|
let selected = index == chosen;
|
||||||
|
let fill = if selected {
|
||||||
|
p.accent
|
||||||
|
} else if response.hovered() {
|
||||||
|
p.hover
|
||||||
|
} else {
|
||||||
|
Color32::TRANSPARENT
|
||||||
|
};
|
||||||
|
if selected || response.hovered() {
|
||||||
|
painter.rect_filled(segment.shrink2(egui::vec2(1.0, 1.0)), space::CONTROL_RADIUS - 2.0, fill);
|
||||||
|
}
|
||||||
|
if index > 0 && !selected && index - 1 != chosen {
|
||||||
|
painter.vline(segment.left() + 0.5, segment.y_range().shrink(7.0), Stroke::new(1.0, p.border));
|
||||||
|
}
|
||||||
|
let color = if selected {
|
||||||
|
p.on_accent
|
||||||
|
} else if response.hovered() {
|
||||||
|
p.text
|
||||||
|
} else {
|
||||||
|
p.muted
|
||||||
|
};
|
||||||
|
painter.text(segment.center(), Align2::CENTER_CENTER, *label, font.clone(), color);
|
||||||
|
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, selected, *label));
|
||||||
|
if response.clicked() {
|
||||||
|
clicked = Some(index);
|
||||||
|
}
|
||||||
|
left += width;
|
||||||
|
}
|
||||||
|
clicked
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Tables ----
|
||||||
|
|
||||||
|
/// What one cell of a [`table`] holds.
|
||||||
|
pub enum Cell {
|
||||||
|
Text(RichText),
|
||||||
|
/// A colour square, then text: the entry of a legend.
|
||||||
|
Marked(Color32, RichText),
|
||||||
|
/// A hit-rate bar for `hits` out of `hits + misses`; its column is fixed width.
|
||||||
|
Bar(u64, u64),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A table that lives inside its panel: columns as wide as what they hold, the
|
||||||
|
/// first column taking the slack; numbers in mono, right-aligned when the head
|
||||||
|
/// is; rows 24 px, a hairline between them; the head in the panel-title style.
|
||||||
|
/// A cell whose text does not fit is cut, and shows all of it on hover.
|
||||||
|
pub fn table(ui: &mut Ui, head: &[&str], rows: &[Vec<Cell>]) {
|
||||||
|
let p = p(ui);
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let columns = head.len().max(rows.first().map_or(0, |row| row.len()));
|
||||||
|
let pad = space::CELL_PAD;
|
||||||
|
let title_font = theme::title_font();
|
||||||
|
let mut natural: Vec<f32> = head
|
||||||
|
.iter()
|
||||||
|
.map(|text| {
|
||||||
|
text_width(ui, &text.to_uppercase(), title_font.clone()) + 2.0 * pad
|
||||||
|
+ text.chars().count() as f32 * space::TITLE_SPACING
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
natural.resize(columns, 0.0);
|
||||||
|
let mut galleys: Vec<Vec<(Option<Arc<Galley>>, String)>> = Vec::with_capacity(rows.len());
|
||||||
|
for row in rows {
|
||||||
|
let mut line = Vec::with_capacity(columns);
|
||||||
|
for (column, cell) in row.iter().enumerate() {
|
||||||
|
match cell {
|
||||||
|
Cell::Marked(_, text) | Cell::Text(text) => {
|
||||||
|
let galley = galley(ui, text.clone(), false, f32::INFINITY);
|
||||||
|
let mark = if matches!(cell, Cell::Marked(..)) {
|
||||||
|
theme::drawing::LEGEND_SWATCH + 6.0
|
||||||
|
} else {
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
natural[column] = natural[column].max(galley.size().x + 2.0 * pad + mark);
|
||||||
|
line.push((Some(galley), text.text().to_owned()));
|
||||||
|
}
|
||||||
|
Cell::Bar(..) => {
|
||||||
|
natural[column] = natural[column].max(theme::drawing::HIT_BAR + 2.0 * pad);
|
||||||
|
line.push((None, String::new()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
galleys.push(line);
|
||||||
|
}
|
||||||
|
// The label column takes the slack, and gives first when the table is too
|
||||||
|
// wide (after a bar column, which can shrink to a stub).
|
||||||
|
// The table reaches `pad` past both edges, so the first column's text and the last
|
||||||
|
// column's numbers line up with the panel's own edges.
|
||||||
|
let width_cells = width + 2.0 * pad;
|
||||||
|
let whole: f32 = natural.iter().sum();
|
||||||
|
let slack = width_cells - whole;
|
||||||
|
if slack >= 0.0 {
|
||||||
|
natural[0] += slack;
|
||||||
|
} else {
|
||||||
|
let bar = rows.first().and_then(|row| {
|
||||||
|
row.iter().position(|cell| matches!(cell, Cell::Bar(..)))
|
||||||
|
});
|
||||||
|
let mut missing = -slack;
|
||||||
|
if let Some(bar) = bar {
|
||||||
|
let give = missing.min((natural[bar] - 28.0).max(0.0));
|
||||||
|
natural[bar] -= give;
|
||||||
|
missing -= give;
|
||||||
|
}
|
||||||
|
let give = missing.min((natural[0] - 2.0 * pad - space::LABEL_MIN).max(0.0));
|
||||||
|
natural[0] -= give;
|
||||||
|
missing -= give;
|
||||||
|
if missing > 0.0 && whole > 0.0 {
|
||||||
|
for size in &mut natural {
|
||||||
|
*size -= missing * *size / whole;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let lefts: Vec<f32> = natural
|
||||||
|
.iter()
|
||||||
|
.scan(ui.cursor().left() - pad, |left, size| {
|
||||||
|
let at = *left;
|
||||||
|
*left += size;
|
||||||
|
Some(at)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let height = space::ROW * (rows.len() + usize::from(!head.is_empty())) as f32;
|
||||||
|
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
|
||||||
|
let painter = ui.painter().with_clip_rect(rect);
|
||||||
|
let cell_rect = |column: usize, top: f32| {
|
||||||
|
Rect::from_min_max(
|
||||||
|
Pos2::new(lefts[column], top),
|
||||||
|
Pos2::new(lefts[column] + natural[column], top + space::ROW),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let put = |ui: &mut Ui, place: Rect, galley: &Arc<Galley>, text: &str, right: bool, id: egui::Id| {
|
||||||
|
let fits = galley.size().x + 2.0 * pad <= place.width() + 0.5;
|
||||||
|
let x = if right { place.right() - pad - galley.size().x } else { place.left() + pad };
|
||||||
|
let pos = Pos2::new(x, place.center().y - galley.size().y / 2.0);
|
||||||
|
let clip = place.intersect(ui.clip_rect());
|
||||||
|
ui.painter().with_clip_rect(clip).galley(pos, galley.clone(), p.text);
|
||||||
|
if !fits {
|
||||||
|
ui.interact(place, id, Sense::hover()).on_hover_text(text.to_owned());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut top = rect.top();
|
||||||
|
if !head.is_empty() {
|
||||||
|
for (column, text) in head.iter().enumerate() {
|
||||||
|
let place = cell_rect(column, top);
|
||||||
|
if text.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let galley = ui.painter().layout_no_wrap(text.to_uppercase(), title_font.clone(), p.muted);
|
||||||
|
put(ui, place, &galley, text, column > 0, ui.scope_id().with(("head", column)));
|
||||||
|
}
|
||||||
|
painter.hline(rect.x_range(), top.round() + space::ROW + 0.5, Stroke::new(1.0, p.border));
|
||||||
|
top += space::ROW;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The rows start under the head, or at the top when there is none.
|
||||||
|
let first = top;
|
||||||
|
for (index, (row, line)) in rows.iter().zip(&galleys).enumerate() {
|
||||||
|
top = first + index as f32 * space::ROW;
|
||||||
|
if index + 1 < rows.len() {
|
||||||
|
painter.hline(rect.x_range(), top.round() + space::ROW + 0.5, Stroke::new(1.0, p.grid));
|
||||||
|
}
|
||||||
|
for (column, cell) in row.iter().enumerate() {
|
||||||
|
let place = cell_rect(column, top);
|
||||||
|
match cell {
|
||||||
|
Cell::Text(_) => {
|
||||||
|
let (galley, text) = &line[column];
|
||||||
|
if let Some(galley) = galley {
|
||||||
|
put(ui, place, galley, text, column > 0, ui.scope_id().with(("cell", index, column)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Cell::Marked(color, _) => {
|
||||||
|
let side = theme::drawing::LEGEND_SWATCH;
|
||||||
|
let square = Rect::from_center_size(
|
||||||
|
Pos2::new(place.left() + pad + side / 2.0, place.center().y),
|
||||||
|
egui::vec2(side, side),
|
||||||
|
);
|
||||||
|
ui.painter().rect_filled(square, 0.0, *color);
|
||||||
|
let (galley, text) = &line[column];
|
||||||
|
if let Some(galley) = galley {
|
||||||
|
let text_place = Rect::from_min_max(
|
||||||
|
Pos2::new(place.left() + pad + side + 6.0, place.top()),
|
||||||
|
place.max,
|
||||||
|
);
|
||||||
|
put(ui, text_place, galley, text, false, ui.scope_id().with(("cell", index, column)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Cell::Bar(hits, misses) => {
|
||||||
|
// As wide as its column, which shrinks before the text does.
|
||||||
|
let bar = Rect::from_min_size(
|
||||||
|
Pos2::new(place.left() + pad, place.center().y - theme::drawing::HIT_BAR_HEIGHT / 2.0),
|
||||||
|
egui::vec2((place.width() - 2.0 * pad).max(0.0), theme::drawing::HIT_BAR_HEIGHT),
|
||||||
|
);
|
||||||
|
hit_bar(ui, bar, *hits, *misses);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// A bar filled from the left to `fraction` of its width (0 to 1), always `height` tall.
|
||||||
|
pub fn meter(ui: &mut Ui, height: f32, fraction: f64, fill: Color32) {
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
|
||||||
|
fill_bar(ui, rect, fraction, fill);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The same, in a rectangle already chosen.
|
||||||
|
pub fn fill_bar(ui: &mut Ui, rect: Rect, fraction: f64, fill: Color32) {
|
||||||
|
let p = p(ui);
|
||||||
|
let painter = ui.painter();
|
||||||
|
painter.rect_filled(rect, 0.0, p.track);
|
||||||
|
let width = rect.width() * fraction.clamp(0.0, 1.0) as f32;
|
||||||
|
if width > 0.5 {
|
||||||
|
painter.rect_filled(
|
||||||
|
Rect::from_min_max(rect.min, Pos2::new(rect.left() + width, rect.bottom())),
|
||||||
|
0.0,
|
||||||
|
fill,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One bar split into coloured parts. The parts fill the whole width when
|
||||||
|
/// their counts add up to `total`; a part with no count gets no width. What
|
||||||
|
/// each part holds shows on hover.
|
||||||
|
pub fn stacked_bar(ui: &mut Ui, parts: &[(&'static str, u64, Color32)], total: u64) {
|
||||||
|
let p = p(ui);
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let (rect, response) = ui.allocate_exact_size(
|
||||||
|
egui::vec2(width, theme::drawing::STACKED_BAR),
|
||||||
|
Sense::hover(),
|
||||||
|
);
|
||||||
|
let painter = ui.painter();
|
||||||
|
painter.rect_filled(rect, 0.0, p.track);
|
||||||
|
let mut x = rect.left();
|
||||||
|
let mut tip = String::new();
|
||||||
|
for (name, part, color) in parts {
|
||||||
|
let width = if total > 0 { rect.width() * *part as f64 as f32 / total as f32 } else { 0.0 };
|
||||||
|
if width > 0.0 {
|
||||||
|
let part_rect = Rect::from_min_max(Pos2::new(x, rect.top()), Pos2::new(x + width, rect.bottom()));
|
||||||
|
painter.rect_filled(part_rect, 0.0, *color);
|
||||||
|
x += width;
|
||||||
|
tip.push_str(&format!(
|
||||||
|
"{name}: {} ({})\n",
|
||||||
|
crate::fmt::count(*part),
|
||||||
|
crate::fmt::share(*part, total)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !tip.is_empty() {
|
||||||
|
response.on_hover_text(tip.trim_end());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A short bar showing hits (in the "from cache" colour) against misses.
|
||||||
|
pub fn hit_bar(ui: &mut Ui, rect: Rect, hits: u64, misses: u64) {
|
||||||
|
let p = p(ui);
|
||||||
|
let painter = ui.painter();
|
||||||
|
painter.rect_filled(rect, 0.0, p.track);
|
||||||
|
let total = hits + misses;
|
||||||
|
if total > 0 {
|
||||||
|
let hit_width = rect.width() * hits as f32 / total as f32;
|
||||||
|
painter.rect_filled(
|
||||||
|
Rect::from_min_max(rect.min, Pos2::new(rect.left() + hit_width, rect.bottom())),
|
||||||
|
0.0,
|
||||||
|
p.from_cache,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A trend line one point per bucket, drawn in a strip `height` tall. `None`
|
||||||
|
/// points break the line, so a gap never looks like a zero. `top` is the value
|
||||||
|
/// drawn at the top of the strip.
|
||||||
|
pub fn sparkline(ui: &mut Ui, height: f32, values: &[Option<f64>], top: f64, color: Color32) {
|
||||||
|
let p = p(ui);
|
||||||
|
let width = ui.available_rect_before_wrap().width();
|
||||||
|
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
|
||||||
|
let painter = ui.painter();
|
||||||
|
painter.hline(rect.x_range(), rect.bottom() - 0.5, Stroke::new(1.0, p.grid));
|
||||||
|
if values.is_empty() || top <= 0.0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let at = |index: usize, value: f64| {
|
||||||
|
Pos2::new(
|
||||||
|
rect.left() + rect.width() * ((index as f32 + 0.5) / values.len() as f32),
|
||||||
|
rect.bottom() - (rect.height() * (value / top) as f32).min(rect.height()),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let mut run: Vec<Pos2> = Vec::new();
|
||||||
|
let flush = |run: &mut Vec<Pos2>, painter: &egui::Painter| match run.len() {
|
||||||
|
0 => {}
|
||||||
|
1 => {
|
||||||
|
painter.circle_filled(run[0], 2.0, color);
|
||||||
|
run.clear();
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
painter.add(Shape::line(std::mem::take(run), Stroke::new(1.5, color)));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (index, value) in values.iter().enumerate() {
|
||||||
|
match value {
|
||||||
|
Some(value) => run.push(at(index, *value)),
|
||||||
|
None => flush(&mut run, painter),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush(&mut run, painter);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a value between a tenth of a millisecond and 100 seconds sits on a
|
||||||
|
/// scale that lets 0.7 ms and 8 s both be seen.
|
||||||
|
pub fn log_fraction(ms: f64) -> f64 {
|
||||||
|
const LOW: f64 = -1.0;
|
||||||
|
const HIGH: f64 = 5.0;
|
||||||
|
if !ms.is_finite() || ms <= 0.0 {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
let position = (ms.log10() - LOW) / (HIGH - LOW);
|
||||||
|
position.clamp(0.02, 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Chart keys ----
|
||||||
|
|
||||||
|
/// What an entry of a chart's key stands for.
|
||||||
|
pub enum Mark {
|
||||||
|
/// A bar.
|
||||||
|
Fill(Color32),
|
||||||
|
/// A line.
|
||||||
|
Line(Color32),
|
||||||
|
/// A dashed line: a reset.
|
||||||
|
Dashed(Color32),
|
||||||
|
/// Time nothing was recorded in.
|
||||||
|
Band,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The swatch for one entry of a chart's key.
|
||||||
|
pub fn key(ui: &mut Ui, mark: Mark) {
|
||||||
|
let p = p(ui);
|
||||||
|
let (rect, _) = ui.allocate_exact_size(
|
||||||
|
egui::vec2(theme::drawing::KEY_SWATCH, theme::drawing::KEY_SWATCH),
|
||||||
|
Sense::hover(),
|
||||||
|
);
|
||||||
|
let painter = ui.painter();
|
||||||
|
let left = Pos2::new(rect.left(), rect.center().y);
|
||||||
|
let right = Pos2::new(rect.right(), rect.center().y);
|
||||||
|
match mark {
|
||||||
|
Mark::Fill(color) => {
|
||||||
|
painter.rect_filled(rect.shrink(3.0), 2.0, color);
|
||||||
|
}
|
||||||
|
Mark::Line(color) => {
|
||||||
|
painter.add(Shape::line(vec![left, right], Stroke::new(2.0, color)));
|
||||||
|
}
|
||||||
|
Mark::Dashed(color) => {
|
||||||
|
painter.add(Shape::dashed_line(&[left, right], Stroke::new(1.5, color), 4.0, 3.0));
|
||||||
|
}
|
||||||
|
Mark::Band => {
|
||||||
|
painter.rect_filled(rect.shrink(3.0), 2.0, p.unrecorded);
|
||||||
|
painter.rect_stroke(rect.shrink(3.0), 2.0, Stroke::new(1.0, p.border), StrokeKind::Inside);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key to a chart, drawn under it so it never sits on the data.
|
||||||
|
pub fn legend(ui: &mut Ui, entries: Vec<(Mark, String)>) {
|
||||||
|
ui.horizontal_wrapped(|ui| {
|
||||||
|
ui.spacing_mut().item_spacing.x = 14.0;
|
||||||
|
for (mark, text) in entries {
|
||||||
|
key(ui, mark);
|
||||||
|
let response = ui.add(egui::Label::new(theme::small(ui, text.clone())).truncate());
|
||||||
|
response.on_hover_text(text);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,444 @@
|
|||||||
|
//! Every colour, size, spacing and font of the page, in one place. A change of
|
||||||
|
//! taste is an edit in this file and nowhere else.
|
||||||
|
//!
|
||||||
|
//! The type is Inter and JetBrains Mono (both under the SIL Open Font License;
|
||||||
|
//! the licence files sit beside the font files in `assets/`).
|
||||||
|
|
||||||
|
use eframe::egui::{self, Color32, FontFamily, FontId, RichText, TextStyle};
|
||||||
|
|
||||||
|
pub static INTER_REGULAR_TTF: &[u8] = include_bytes!("../assets/Inter-Regular.ttf");
|
||||||
|
pub static INTER_MEDIUM_TTF: &[u8] = include_bytes!("../assets/Inter-Medium.ttf");
|
||||||
|
pub static INTER_SEMIBOLD_TTF: &[u8] = include_bytes!("../assets/Inter-SemiBold.ttf");
|
||||||
|
pub static MONO_REGULAR_TTF: &[u8] = include_bytes!("../assets/JetBrainsMono-Regular.ttf");
|
||||||
|
pub static MONO_MEDIUM_TTF: &[u8] = include_bytes!("../assets/JetBrainsMono-Medium.ttf");
|
||||||
|
|
||||||
|
const fn rgb(hex: u32) -> Color32 {
|
||||||
|
Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The colours of one theme. State colours (`good`, `warn`, `bad`) are used
|
||||||
|
/// only for state; the series colours only for the five outcomes of a compile.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Palette {
|
||||||
|
pub dark: bool,
|
||||||
|
pub page: Color32,
|
||||||
|
pub panel: Color32,
|
||||||
|
pub border: Color32,
|
||||||
|
pub text: Color32,
|
||||||
|
pub muted: Color32,
|
||||||
|
/// Hairlines inside a panel: between table rows and across a chart.
|
||||||
|
pub grid: Color32,
|
||||||
|
/// The recessed track of a bar, and of a control.
|
||||||
|
pub track: Color32,
|
||||||
|
/// A control under the pointer.
|
||||||
|
pub hover: Color32,
|
||||||
|
pub good: Color32,
|
||||||
|
pub warn: Color32,
|
||||||
|
pub bad: Color32,
|
||||||
|
pub from_cache: Color32,
|
||||||
|
pub built: Color32,
|
||||||
|
pub not_cacheable: Color32,
|
||||||
|
pub unsupported: Color32,
|
||||||
|
pub not_compile: Color32,
|
||||||
|
/// Selected controls.
|
||||||
|
pub accent: Color32,
|
||||||
|
/// Text on the accent: what a selected control says.
|
||||||
|
pub on_accent: Color32,
|
||||||
|
/// Amber as text and lines: the hero figures and key lines (darker in the light theme to pass contrast).
|
||||||
|
pub hero: Color32,
|
||||||
|
/// The tint over time nothing was recorded in.
|
||||||
|
pub unrecorded: Color32,
|
||||||
|
/// The line of the mean, the median and the p90 on a build-time histogram.
|
||||||
|
pub mean: Color32,
|
||||||
|
pub median: Color32,
|
||||||
|
pub p90: Color32,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const DARK: Palette = Palette {
|
||||||
|
dark: true,
|
||||||
|
page: rgb(0x0f0f10),
|
||||||
|
panel: rgb(0x161617),
|
||||||
|
border: rgb(0x2a2a2c),
|
||||||
|
text: rgb(0xe8e6e1),
|
||||||
|
muted: rgb(0x8f8d87),
|
||||||
|
grid: rgb(0x1f1f21),
|
||||||
|
track: rgb(0x1b1b1d),
|
||||||
|
hover: rgb(0x1f1f21),
|
||||||
|
good: rgb(0x3ecf8e),
|
||||||
|
warn: rgb(0xffb000),
|
||||||
|
bad: rgb(0xff5f56),
|
||||||
|
from_cache: rgb(0x3ecf8e),
|
||||||
|
built: rgb(0x5b8def),
|
||||||
|
not_cacheable: rgb(0x8a8a8f),
|
||||||
|
unsupported: rgb(0x5f5f64),
|
||||||
|
not_compile: rgb(0x424246),
|
||||||
|
accent: rgb(0xffb000),
|
||||||
|
on_accent: rgb(0x0f0f10),
|
||||||
|
hero: rgb(0xffb000),
|
||||||
|
unrecorded: Color32::from_rgba_premultiplied(14, 14, 14, 14),
|
||||||
|
mean: rgb(0xe8e6e1),
|
||||||
|
median: rgb(0xffb000),
|
||||||
|
p90: rgb(0x8a8a8f),
|
||||||
|
};
|
||||||
|
|
||||||
|
pub const LIGHT: Palette = Palette {
|
||||||
|
dark: false,
|
||||||
|
page: rgb(0xf6f3ec),
|
||||||
|
panel: rgb(0xfffdf8),
|
||||||
|
border: rgb(0xd5cfc1),
|
||||||
|
text: rgb(0x1d1b17),
|
||||||
|
muted: rgb(0x6a655b),
|
||||||
|
grid: rgb(0xe6e1d6),
|
||||||
|
track: rgb(0xebe6da),
|
||||||
|
hover: rgb(0xe9e4d8),
|
||||||
|
good: rgb(0x1a8f5a),
|
||||||
|
warn: rgb(0xb87400),
|
||||||
|
bad: rgb(0xc62f26),
|
||||||
|
from_cache: rgb(0x1f9d63),
|
||||||
|
built: rgb(0x2f63d0),
|
||||||
|
not_cacheable: rgb(0x7a766c),
|
||||||
|
unsupported: rgb(0xa39f94),
|
||||||
|
not_compile: rgb(0xc2beb2),
|
||||||
|
accent: rgb(0xffb000),
|
||||||
|
on_accent: rgb(0x1d1b17),
|
||||||
|
hero: rgb(0x8a5600),
|
||||||
|
unrecorded: Color32::from_rgba_premultiplied(0, 0, 0, 16),
|
||||||
|
mean: rgb(0x1d1b17),
|
||||||
|
median: rgb(0x8a5600),
|
||||||
|
p90: rgb(0x7a766c),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The palette of the theme being drawn.
|
||||||
|
pub fn of(dark: bool) -> &'static Palette {
|
||||||
|
if dark {
|
||||||
|
&DARK
|
||||||
|
} else {
|
||||||
|
&LIGHT
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The palette of the theme `ctx` is drawing in.
|
||||||
|
pub fn ctx(ctx: &egui::Context) -> &'static Palette {
|
||||||
|
of(ctx.theme() == egui::Theme::Dark)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The palette of the theme `ui` is drawing in.
|
||||||
|
pub fn ui(ui: &egui::Ui) -> &'static Palette {
|
||||||
|
ctx(ui.ctx())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A colour made see-through: `color` over the panel at `share` of its strength.
|
||||||
|
pub fn tint(color: Color32, share: f32) -> Color32 {
|
||||||
|
let alpha = (share.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||||
|
Color32::from_rgba_premultiplied(color.r(), color.g(), color.b(), alpha)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Font sizes in pixels. There are no others.
|
||||||
|
pub mod px {
|
||||||
|
/// Panel titles, table heads and small labels: upper case, letter-spaced.
|
||||||
|
pub const TITLE: f32 = 11.0;
|
||||||
|
/// Text, and the controls.
|
||||||
|
pub const BODY: f32 = 13.0;
|
||||||
|
/// Small print.
|
||||||
|
pub const SMALL: f32 = 11.0;
|
||||||
|
/// The number on a stat card.
|
||||||
|
pub const CARD_NUMBER: f32 = 22.0;
|
||||||
|
/// The three figures of the headline panel.
|
||||||
|
pub const HEADLINE: f32 = 56.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Space in pixels.
|
||||||
|
pub mod space {
|
||||||
|
pub const PAGE_MARGIN: f32 = 16.0;
|
||||||
|
/// Between panels, and between cards.
|
||||||
|
pub const PANEL_GAP: f32 = 24.0;
|
||||||
|
/// Between the controls of the top bar.
|
||||||
|
pub const TOOL_GAP: f32 = 8.0;
|
||||||
|
/// Panels have no side padding: their content lines up with the hairline above it.
|
||||||
|
pub const PANEL_PADDING: f32 = 0.0;
|
||||||
|
/// Room between a panel's top hairline and its title, and under its content.
|
||||||
|
pub const PANEL_PAD_Y: f32 = 12.0;
|
||||||
|
pub const PANEL_RADIUS: f32 = 0.0;
|
||||||
|
pub const CONTROL_RADIUS: f32 = 2.0;
|
||||||
|
/// Between items that follow each other in a panel.
|
||||||
|
pub const ITEM: f32 = 8.0;
|
||||||
|
/// Between lines of one paragraph.
|
||||||
|
pub const LINE: f32 = 3.0;
|
||||||
|
/// One table row.
|
||||||
|
pub const ROW: f32 = 24.0;
|
||||||
|
/// Space either side of the text in a table cell.
|
||||||
|
pub const CELL_PAD: f32 = 8.0;
|
||||||
|
/// The narrowest the label column of a table gets before its text is cut.
|
||||||
|
pub const LABEL_MIN: f32 = 72.0;
|
||||||
|
pub const CONTROL_HEIGHT: f32 = 24.0;
|
||||||
|
pub const CONTROL_PAD: f32 = 9.0;
|
||||||
|
pub const TITLE_SPACING: f32 = 0.8;
|
||||||
|
pub const TOOLBAR_NOTE_WIDTH: f32 = 150.0;
|
||||||
|
/// Between a raw counter's key and its value.
|
||||||
|
pub const KEY_VALUE_GAP: f32 = 16.0;
|
||||||
|
/// Room under a title before the panel's content.
|
||||||
|
pub const UNDER_TITLE: f32 = 8.0;
|
||||||
|
/// Room between titled parts of one panel.
|
||||||
|
pub const BETWEEN_PARTS: f32 = 14.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the page is laid out, in pixels of window width.
|
||||||
|
pub mod layout {
|
||||||
|
/// From this width the page has three columns of panels.
|
||||||
|
pub const THREE_COLUMNS_FROM: f32 = 1100.0;
|
||||||
|
/// From this width it has two; below it, one.
|
||||||
|
pub const TWO_COLUMNS_FROM: f32 = 700.0;
|
||||||
|
/// How many columns of key/value lines the raw counters run in, per page column.
|
||||||
|
pub const RAW_LINE_WIDTH: f32 = 400.0;
|
||||||
|
|
||||||
|
pub const TOOLBAR_HEIGHT: f32 = 24.0;
|
||||||
|
/// The hero band on a wide page: caption row, one row of figures and the storage line.
|
||||||
|
pub const HEADLINE_HEIGHT: f32 = 296.0;
|
||||||
|
/// A hero figure: the number, its caption, the trend line and two lines of small print.
|
||||||
|
pub const FIGURE_HEIGHT: f32 = 176.0;
|
||||||
|
/// One row of the counter strip.
|
||||||
|
pub const STRIP_ROW_HEIGHT: f32 = 92.0;
|
||||||
|
/// "Where compiles went": its bar, legend and the "of the built" line.
|
||||||
|
pub const WHERE_FIXED_HEIGHT: f32 = 212.0;
|
||||||
|
/// "Why compiles were not cacheable" needs this much beside its reasons: padding, title and the room under it.
|
||||||
|
pub const REASONS_FIXED_HEIGHT: f32 = 56.0;
|
||||||
|
/// From this panel width the "By language" table has room for its hit-rate bars.
|
||||||
|
pub const LANGUAGE_BARS_FROM: f32 = 380.0;
|
||||||
|
/// "By language" needs this much beside its rows.
|
||||||
|
pub const LANGUAGES_FIXED_HEIGHT: f32 = 50.0;
|
||||||
|
/// "Speed" needs this much beside its histograms.
|
||||||
|
pub const SPEED_FIXED_HEIGHT: f32 = 240.0;
|
||||||
|
/// "Speed" needs this much per language with a histogram.
|
||||||
|
pub const HISTOGRAM_HEIGHT: f32 = 85.0;
|
||||||
|
/// A panel of one time chart: padding, title, plot and legend.
|
||||||
|
pub const CHART_PANEL_HEIGHT: f32 = 306.0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drawings inside panels, in pixels.
|
||||||
|
pub mod drawing {
|
||||||
|
pub const CHART_HEIGHT: f32 = 240.0;
|
||||||
|
/// The trend line under a headline figure.
|
||||||
|
pub const SPARKLINE: f32 = 36.0;
|
||||||
|
pub const BUILD_HISTOGRAM: f32 = 44.0;
|
||||||
|
pub const BUILD_AXIS: f32 = 14.0;
|
||||||
|
pub const STACKED_BAR: f32 = 22.0;
|
||||||
|
pub const SPEED_BAR: f32 = 10.0;
|
||||||
|
pub const USAGE_BAR: f32 = 4.0;
|
||||||
|
pub const HIT_BAR: f32 = 72.0;
|
||||||
|
pub const HIT_BAR_HEIGHT: f32 = 6.0;
|
||||||
|
pub const LEGEND_SWATCH: f32 = 10.0;
|
||||||
|
pub const KEY_SWATCH: f32 = 14.0;
|
||||||
|
pub const SEVERITY_DOT: f32 = 8.0;
|
||||||
|
/// Share of the range's length left empty either side of a chart, so the
|
||||||
|
/// first and last time label sit inside the plot.
|
||||||
|
pub const CHART_SIDE_AIR: f64 = 0.035;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A hit rate is good from this share of compiles, and worth a look from the next.
|
||||||
|
pub mod state {
|
||||||
|
pub const HIT_RATE_GOOD: f64 = 0.7;
|
||||||
|
pub const HIT_RATE_WARN: f64 = 0.4;
|
||||||
|
/// A cache this full is shown in the bad colour.
|
||||||
|
pub const CACHE_FULL: f64 = 0.95;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The font families, by name.
|
||||||
|
pub const REGULAR: &str = "inter-regular";
|
||||||
|
pub const MEDIUM: &str = "inter-medium";
|
||||||
|
pub const SEMIBOLD: &str = "inter-semibold";
|
||||||
|
pub const MONO: &str = "jetbrains-mono";
|
||||||
|
pub const MONO_MEDIUM: &str = "jetbrains-mono-medium";
|
||||||
|
|
||||||
|
// The text styles beyond egui's own, by name.
|
||||||
|
pub const TITLE_STYLE: &str = "title";
|
||||||
|
pub const CARD_STYLE: &str = "card-number";
|
||||||
|
pub const HEADLINE_STYLE: &str = "headline-number";
|
||||||
|
|
||||||
|
pub fn medium_family() -> FontFamily {
|
||||||
|
FontFamily::Name(MEDIUM.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn semibold_family() -> FontFamily {
|
||||||
|
FontFamily::Name(SEMIBOLD.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn mono_medium_family() -> FontFamily {
|
||||||
|
FontFamily::Name(MONO_MEDIUM.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text of `size` in Inter Medium.
|
||||||
|
pub fn medium(size: f32) -> FontId {
|
||||||
|
FontId::new(size, medium_family())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text of `size` in Inter SemiBold.
|
||||||
|
pub fn semibold(size: f32) -> FontId {
|
||||||
|
FontId::new(size, semibold_family())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A number of `size`: JetBrains Mono Medium.
|
||||||
|
pub fn number_font(size: f32) -> FontId {
|
||||||
|
FontId::new(size, mono_medium_family())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The font of panel titles and table heads.
|
||||||
|
pub fn title_font() -> FontId {
|
||||||
|
semibold(px::TITLE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn families() -> egui::FontDefinitions {
|
||||||
|
use std::sync::Arc;
|
||||||
|
let mut fonts = egui::FontDefinitions::default();
|
||||||
|
for (name, data) in [
|
||||||
|
(REGULAR, INTER_REGULAR_TTF),
|
||||||
|
(MEDIUM, INTER_MEDIUM_TTF),
|
||||||
|
(SEMIBOLD, INTER_SEMIBOLD_TTF),
|
||||||
|
(MONO, MONO_REGULAR_TTF),
|
||||||
|
(MONO_MEDIUM, MONO_MEDIUM_TTF),
|
||||||
|
] {
|
||||||
|
fonts
|
||||||
|
.font_data
|
||||||
|
.insert(name.to_owned(), Arc::new(egui::FontData::from_static(data)));
|
||||||
|
}
|
||||||
|
fonts
|
||||||
|
.families
|
||||||
|
.entry(FontFamily::Proportional)
|
||||||
|
.or_default()
|
||||||
|
.insert(0, REGULAR.to_owned());
|
||||||
|
fonts
|
||||||
|
.families
|
||||||
|
.entry(FontFamily::Monospace)
|
||||||
|
.or_default()
|
||||||
|
.insert(0, MONO.to_owned());
|
||||||
|
fonts
|
||||||
|
.families
|
||||||
|
.insert(medium_family(), vec![MEDIUM.to_owned()]);
|
||||||
|
fonts
|
||||||
|
.families
|
||||||
|
.insert(semibold_family(), vec![SEMIBOLD.to_owned()]);
|
||||||
|
fonts
|
||||||
|
.families
|
||||||
|
.insert(mono_medium_family(), vec![MONO_MEDIUM.to_owned()]);
|
||||||
|
fonts
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text_styles() -> std::collections::BTreeMap<TextStyle, FontId> {
|
||||||
|
[
|
||||||
|
(TextStyle::Small, FontId::proportional(px::SMALL)),
|
||||||
|
(TextStyle::Body, FontId::proportional(px::BODY)),
|
||||||
|
(TextStyle::Button, medium(px::BODY)),
|
||||||
|
(TextStyle::Heading, semibold(px::BODY)),
|
||||||
|
(TextStyle::Monospace, FontId::monospace(px::BODY)),
|
||||||
|
(TextStyle::Name(TITLE_STYLE.into()), title_font()),
|
||||||
|
(
|
||||||
|
TextStyle::Name(CARD_STYLE.into()),
|
||||||
|
number_font(px::CARD_NUMBER),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
TextStyle::Name(HEADLINE_STYLE.into()),
|
||||||
|
number_font(px::HEADLINE),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visuals(p: &Palette) -> egui::Visuals {
|
||||||
|
use egui::style::WidgetVisuals;
|
||||||
|
use egui::{CornerRadius, Stroke};
|
||||||
|
let mut visuals = if p.dark {
|
||||||
|
egui::Visuals::dark()
|
||||||
|
} else {
|
||||||
|
egui::Visuals::light()
|
||||||
|
};
|
||||||
|
visuals.override_text_color = Some(p.text);
|
||||||
|
visuals.panel_fill = p.page;
|
||||||
|
visuals.window_fill = p.panel;
|
||||||
|
visuals.window_stroke = Stroke::new(1.0, p.border);
|
||||||
|
visuals.extreme_bg_color = p.track;
|
||||||
|
visuals.faint_bg_color = p.hover;
|
||||||
|
visuals.selection.bg_fill = tint(p.accent, 0.35);
|
||||||
|
visuals.selection.stroke = Stroke::new(1.0, p.accent);
|
||||||
|
visuals.hyperlink_color = p.accent;
|
||||||
|
visuals.warn_fg_color = p.warn;
|
||||||
|
visuals.error_fg_color = p.bad;
|
||||||
|
|
||||||
|
let control = |fill, stroke, text: Color32| WidgetVisuals {
|
||||||
|
corner_radius: CornerRadius::same(space::CONTROL_RADIUS as u8),
|
||||||
|
bg_fill: fill,
|
||||||
|
weak_bg_fill: fill,
|
||||||
|
bg_stroke: Stroke::new(1.0, stroke),
|
||||||
|
fg_stroke: Stroke::new(1.0, text),
|
||||||
|
expansion: 0.0,
|
||||||
|
};
|
||||||
|
visuals.widgets.noninteractive = control(p.track, p.border, p.muted);
|
||||||
|
visuals.widgets.inactive = control(Color32::TRANSPARENT, p.border, p.text);
|
||||||
|
visuals.widgets.hovered = control(p.hover, p.muted, p.text);
|
||||||
|
visuals.widgets.active = control(tint(p.accent, 0.25), p.accent, p.text);
|
||||||
|
visuals.widgets.open = control(p.hover, p.muted, p.text);
|
||||||
|
visuals
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put the fonts, text styles, spacing and both themes' colours on the page.
|
||||||
|
pub fn install(ctx: &egui::Context) {
|
||||||
|
ctx.set_fonts(families());
|
||||||
|
ctx.all_styles_mut(|style| {
|
||||||
|
style.text_styles = text_styles();
|
||||||
|
style.spacing.item_spacing = egui::vec2(space::ITEM, space::LINE);
|
||||||
|
style.spacing.button_padding = egui::vec2(8.0, 2.0);
|
||||||
|
style.spacing.interact_size.y = space::CONTROL_HEIGHT;
|
||||||
|
style.spacing.indent = 12.0;
|
||||||
|
style.visuals = visuals(of(style.visuals.dark_mode));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A panel title: 11 px, upper case, letter-spaced, muted.
|
||||||
|
pub fn title(scope: &egui::Ui, text: impl AsRef<str>) -> RichText {
|
||||||
|
RichText::new(text.as_ref().to_uppercase())
|
||||||
|
.font(title_font())
|
||||||
|
.color(ui(scope).muted)
|
||||||
|
.extra_letter_spacing(space::TITLE_SPACING)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Small print in the muted colour.
|
||||||
|
pub fn small(scope: &egui::Ui, text: impl Into<String>) -> RichText {
|
||||||
|
RichText::new(text.into())
|
||||||
|
.font(FontId::proportional(px::SMALL))
|
||||||
|
.color(ui(scope).muted)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text in the body size.
|
||||||
|
pub fn body(text: impl Into<String>) -> RichText {
|
||||||
|
RichText::new(text.into()).font(FontId::proportional(px::BODY))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text in the body size, a little heavier.
|
||||||
|
pub fn strong(text: impl Into<String>) -> RichText {
|
||||||
|
RichText::new(text.into()).font(semibold(px::BODY))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A number in the body size, in the mono font.
|
||||||
|
pub fn number(text: impl Into<String>) -> RichText {
|
||||||
|
RichText::new(text.into()).font(number_font(px::BODY))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The colour of a hit rate: good, worth a look, or bad.
|
||||||
|
pub fn hit_rate_color(rate: Option<f64>, p: &Palette) -> Color32 {
|
||||||
|
match rate {
|
||||||
|
Some(rate) if rate >= state::HIT_RATE_GOOD => p.good,
|
||||||
|
Some(rate) if rate >= state::HIT_RATE_WARN => p.warn,
|
||||||
|
Some(_) => p.bad,
|
||||||
|
None => p.muted,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many columns of panels the page has at `width`.
|
||||||
|
pub fn columns(width: f32) -> usize {
|
||||||
|
if width >= layout::THREE_COLUMNS_FROM {
|
||||||
|
3
|
||||||
|
} else if width >= layout::TWO_COLUMNS_FROM {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,258 @@
|
|||||||
|
//! Where compiles went: one bar split by outcome, with a legend of counts and
|
||||||
|
//! shares; what happened inside the built share; and why some could not be
|
||||||
|
//! cached. How each language fared is its own panel ([`languages`]).
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use eframe::egui::{self, Color32, Sense, Stroke, Ui};
|
||||||
|
use eframe::epaint::text::Galley;
|
||||||
|
use sccache_dash_api::{NotCached, View};
|
||||||
|
|
||||||
|
use crate::disclosure;
|
||||||
|
use crate::fmt;
|
||||||
|
use crate::style::{self, Cell};
|
||||||
|
use crate::theme;
|
||||||
|
|
||||||
|
pub fn section(ui: &mut Ui, view: &View) {
|
||||||
|
let totals = &view.totals;
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
// Five shares of every compiler call; timeouts, cache errors and forced
|
||||||
|
// recaches are inside the built share, as sccache counts them.
|
||||||
|
let parts: [(&'static str, u64, Color32); 5] = [
|
||||||
|
("From cache", totals.hits, p.from_cache),
|
||||||
|
("Built", totals.misses, p.built),
|
||||||
|
("Not cacheable", totals.not_cacheable, p.not_cacheable),
|
||||||
|
("Unsupported compiler", totals.unsupported_compiler, p.unsupported),
|
||||||
|
("Not a compile", totals.not_compile, p.not_compile),
|
||||||
|
];
|
||||||
|
let all: u64 = parts.iter().map(|(_, count, _)| count).sum();
|
||||||
|
let percents = fmt::shares(&parts.iter().map(|(_, count, _)| *count).collect::<Vec<_>>());
|
||||||
|
|
||||||
|
style::stacked_bar(ui, &parts, all);
|
||||||
|
ui.add_space(6.0);
|
||||||
|
let legend: Vec<Vec<Cell>> = parts
|
||||||
|
.iter()
|
||||||
|
.zip(&percents)
|
||||||
|
.map(|((name, count, color), percent)| {
|
||||||
|
vec![
|
||||||
|
Cell::Marked(*color, theme::body(*name)),
|
||||||
|
Cell::Text(theme::number(fmt::count(*count))),
|
||||||
|
Cell::Text(theme::number(format!("{percent}%"))),
|
||||||
|
]
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
style::table(ui, &[], &legend);
|
||||||
|
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
ui.add(egui::Label::new(
|
||||||
|
theme::small(
|
||||||
|
ui,
|
||||||
|
format!(
|
||||||
|
"Of the built: {} timeouts, {} cache errors, {} forced recaches, {} failed to compile",
|
||||||
|
fmt::count(totals.timeouts),
|
||||||
|
fmt::count(totals.errors()),
|
||||||
|
fmt::count(totals.forced_recaches),
|
||||||
|
fmt::count(totals.compile_fails)
|
||||||
|
),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One reason laid out for a width: its line, and the two small paragraphs when it is open.
|
||||||
|
struct Block {
|
||||||
|
name: Arc<Galley>,
|
||||||
|
count: Arc<Galley>,
|
||||||
|
share: Arc<Galley>,
|
||||||
|
/// `None` while the reason is closed.
|
||||||
|
meaning: Option<Arc<Galley>>,
|
||||||
|
/// `None` when closed, or when sccache gives nothing to do.
|
||||||
|
action: Option<Arc<Galley>>,
|
||||||
|
/// The line: at least a control tall, taller when the name wraps.
|
||||||
|
row: f32,
|
||||||
|
open: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Block {
|
||||||
|
fn entry(&self) -> disclosure::Entry {
|
||||||
|
disclosure::Entry {
|
||||||
|
row: self.row,
|
||||||
|
open: self.open,
|
||||||
|
meaning: self.meaning.as_ref().map_or(0.0, |g| g.size().y),
|
||||||
|
action: self.action.as_ref().map(|g| g.size().y),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How far the name is from the numbers, and from the dot.
|
||||||
|
const NAME_GAP: f32 = 8.0;
|
||||||
|
/// The side of the chevron's triangle box.
|
||||||
|
const CHEVRON: f32 = 8.0;
|
||||||
|
/// The hairline between two lines.
|
||||||
|
const SEPARATOR: f32 = 1.0;
|
||||||
|
|
||||||
|
/// Where a reason remembers whether it is open.
|
||||||
|
fn open_id(reason: &str) -> egui::Id {
|
||||||
|
egui::Id::new(("reason-open", reason))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_open(ctx: &egui::Context, reason: &NotCached) -> bool {
|
||||||
|
let stored = ctx.data(|data| data.get_temp::<bool>(open_id(&reason.reason)));
|
||||||
|
disclosure::is_open(stored, reason.fixable)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lay every reason out in `width`; counts and shares line up in columns, the name takes the rest.
|
||||||
|
fn blocks(ui: &Ui, view: &View, width: f32) -> Vec<Block> {
|
||||||
|
let number = |text: String| style::galley(ui, theme::number(text), false, f32::INFINITY);
|
||||||
|
let numbers: Vec<(Arc<Galley>, Arc<Galley>)> = view
|
||||||
|
.not_cached
|
||||||
|
.iter()
|
||||||
|
.map(|r| (number(fmt::count(r.count)), number(fmt::share(r.count, view.totals.not_cacheable))))
|
||||||
|
.collect();
|
||||||
|
let widest = |pick: fn(&(Arc<Galley>, Arc<Galley>)) -> &Arc<Galley>| {
|
||||||
|
numbers.iter().map(|n| pick(n).size().x).fold(0.0, f32::max)
|
||||||
|
};
|
||||||
|
let (count_width, share_width) = (widest(|n| &n.0), widest(|n| &n.1));
|
||||||
|
let indent = theme::drawing::SEVERITY_DOT + NAME_GAP;
|
||||||
|
let name_width = (width - indent - count_width - share_width - CHEVRON - 3.0 * NAME_GAP).max(40.0);
|
||||||
|
view.not_cached
|
||||||
|
.iter()
|
||||||
|
.zip(numbers)
|
||||||
|
.map(|(r, (count, share))| {
|
||||||
|
let name = style::galley(ui, theme::body(r.name.clone()), true, name_width);
|
||||||
|
let open = is_open(ui.ctx(), r);
|
||||||
|
let small = |text: &str| style::galley(ui, theme::small(ui, text), true, width - indent);
|
||||||
|
Block {
|
||||||
|
row: theme::space::CONTROL_HEIGHT.max(name.size().y + 2.0 * theme::space::ITEM),
|
||||||
|
name,
|
||||||
|
count,
|
||||||
|
share,
|
||||||
|
meaning: open.then(|| small(&r.meaning)),
|
||||||
|
action: (open && !r.action.is_empty()).then(|| small(&r.action)),
|
||||||
|
open,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A triangle in the muted colour: pointing right when closed, down when open.
|
||||||
|
pub(crate) fn chevron(painter: &egui::Painter, center: egui::Pos2, open: bool, color: Color32) {
|
||||||
|
let h = CHEVRON / 2.0;
|
||||||
|
let points = if open {
|
||||||
|
vec![center + egui::vec2(-h, -h / 2.0), center + egui::vec2(h, -h / 2.0), center + egui::vec2(0.0, h / 2.0 + 1.0)]
|
||||||
|
} else {
|
||||||
|
vec![center + egui::vec2(-h / 2.0, -h), center + egui::vec2(-h / 2.0, h), center + egui::vec2(h / 2.0 + 1.0, 0.0)]
|
||||||
|
};
|
||||||
|
painter.add(egui::Shape::convex_polygon(points, color, Stroke::NONE));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "Why compiles were not cacheable": one line per reason, each with a dot (the warning
|
||||||
|
/// colour when a setting would fix it, the muted one when it is expected), its plain name,
|
||||||
|
/// its count and share, and a chevron. Clicking the line shows, in small print under it,
|
||||||
|
/// what it means and what to do; the reasons a setting would fix start open.
|
||||||
|
pub fn reasons(ui: &mut Ui, view: &View) {
|
||||||
|
if view.not_cached.is_empty() {
|
||||||
|
ui.label(theme::small(ui, "Every compile could be cached in this range."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
let width = ui.available_width();
|
||||||
|
let blocks = blocks(ui, view, width);
|
||||||
|
let indent = theme::drawing::SEVERITY_DOT + NAME_GAP;
|
||||||
|
// Every height is added by hand, so the list is as tall as `reasons_height` says.
|
||||||
|
ui.spacing_mut().item_spacing.y = 0.0;
|
||||||
|
for (index, (reason, block)) in view.not_cached.iter().zip(&blocks).enumerate() {
|
||||||
|
if index > 0 {
|
||||||
|
let (gap, _) = ui.allocate_exact_size(egui::vec2(width, SEPARATOR), Sense::hover());
|
||||||
|
ui.painter().rect_filled(gap, 0.0, p.grid);
|
||||||
|
}
|
||||||
|
let (row, response) = ui.allocate_exact_size(egui::vec2(width, block.row), Sense::click());
|
||||||
|
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||||
|
response.widget_info(|| {
|
||||||
|
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, reason.name.as_str())
|
||||||
|
});
|
||||||
|
if response.clicked() {
|
||||||
|
ui.ctx().data_mut(|data| data.insert_temp(open_id(&reason.reason), !block.open));
|
||||||
|
ui.ctx().request_repaint();
|
||||||
|
}
|
||||||
|
let painter = ui.painter();
|
||||||
|
if response.hovered() || response.has_focus() {
|
||||||
|
painter.rect_filled(row, theme::space::CONTROL_RADIUS, p.hover);
|
||||||
|
}
|
||||||
|
if response.has_focus() {
|
||||||
|
painter.rect_stroke(row, theme::space::CONTROL_RADIUS, Stroke::new(1.0, p.muted), egui::StrokeKind::Inside);
|
||||||
|
}
|
||||||
|
let side = theme::drawing::SEVERITY_DOT;
|
||||||
|
let dot = if reason.fixable { p.warn } else { p.not_cacheable };
|
||||||
|
let name_top = row.top() + (block.row - block.name.size().y) / 2.0;
|
||||||
|
painter.rect_filled(egui::Rect::from_center_size(egui::pos2(row.left() + side / 2.0, row.center().y), egui::vec2(side, side)), 0.0, dot);
|
||||||
|
painter.galley(egui::pos2(row.left() + indent, name_top), block.name.clone(), p.text);
|
||||||
|
let chevron_left = row.right() - CHEVRON;
|
||||||
|
chevron(painter, egui::pos2(chevron_left + CHEVRON / 2.0, row.center().y), block.open, p.muted);
|
||||||
|
let share_left = chevron_left - NAME_GAP - block.share.size().x;
|
||||||
|
let at = |galley: &Arc<Galley>, left: f32| {
|
||||||
|
egui::pos2(left, row.top() + (block.row - galley.size().y) / 2.0)
|
||||||
|
};
|
||||||
|
painter.galley(at(&block.share, share_left), block.share.clone(), p.text);
|
||||||
|
let count_left = share_left - NAME_GAP - block.count.size().x;
|
||||||
|
painter.galley(at(&block.count, count_left), block.count.clone(), p.text);
|
||||||
|
let mut opened = false;
|
||||||
|
for galley in block.meaning.iter().chain(block.action.as_ref()) {
|
||||||
|
ui.add_space(theme::space::LINE);
|
||||||
|
let (place, _) = ui.allocate_exact_size(egui::vec2(width, galley.size().y), Sense::hover());
|
||||||
|
ui.painter().galley(egui::pos2(place.left() + indent, place.top()), galley.clone(), p.muted);
|
||||||
|
opened = true;
|
||||||
|
}
|
||||||
|
if opened {
|
||||||
|
ui.add_space(theme::space::ITEM);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How tall "Why compiles were not cacheable" is in a panel `panel_width` wide.
|
||||||
|
pub fn reasons_height(ui: &Ui, view: &View, panel_width: f32) -> f32 {
|
||||||
|
let inner = panel_width - 2.0 * theme::space::PANEL_PADDING;
|
||||||
|
let entries: Vec<_> = blocks(ui, view, inner).iter().map(Block::entry).collect();
|
||||||
|
let list = disclosure::list_height(&entries, theme::space::LINE, theme::space::ITEM, SEPARATOR);
|
||||||
|
theme::layout::REASONS_FIXED_HEIGHT + list.max(theme::space::ROW)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// "By language": one row per language, with hits, misses, errors, the hit rate
|
||||||
|
/// in its state colour, and a bar of hits against misses.
|
||||||
|
pub fn languages(ui: &mut Ui, view: &View) {
|
||||||
|
if view.languages.is_empty() {
|
||||||
|
ui.label(theme::small(ui, "No compiles were counted in this range."));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let p = theme::ui(ui);
|
||||||
|
// The bar is the first thing to go where the columns are too tight to leave it room.
|
||||||
|
let with_bars = ui.available_rect_before_wrap().width() >= theme::layout::LANGUAGE_BARS_FROM;
|
||||||
|
let mut head = vec!["", "Hits", "Misses", "Errors", "Hit rate"];
|
||||||
|
if with_bars {
|
||||||
|
head.push("");
|
||||||
|
}
|
||||||
|
let mut rows: Vec<Vec<Cell>> = view
|
||||||
|
.languages
|
||||||
|
.iter()
|
||||||
|
.map(|language| {
|
||||||
|
let rate = crate::overtime::hit_rate(language.hits, language.misses);
|
||||||
|
vec![
|
||||||
|
Cell::Text(theme::strong(language.name.clone())),
|
||||||
|
Cell::Text(theme::number(fmt::count(language.hits))),
|
||||||
|
Cell::Text(theme::number(fmt::count(language.misses))),
|
||||||
|
Cell::Text(
|
||||||
|
theme::number(fmt::count(language.errors))
|
||||||
|
.color(if language.errors > 0 { p.bad } else { p.text }),
|
||||||
|
),
|
||||||
|
Cell::Text(
|
||||||
|
theme::number(fmt::percent(rate)).color(theme::hit_rate_color(rate, p)),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if with_bars {
|
||||||
|
for (row, language) in rows.iter_mut().zip(&view.languages) {
|
||||||
|
row.push(Cell::Bar(language.hits, language.misses));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
style::table(ui, &head, &rows);
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 253 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 226 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 104 KiB |
@@ -8,3 +8,7 @@ test:
|
|||||||
|
|
||||||
run:
|
run:
|
||||||
cargo run -p sccache-dash
|
cargo run -p sccache-dash
|
||||||
|
|
||||||
|
# Screenshots of the whole page at the 3, 2 and 1 column widths; read them before merging a page change.
|
||||||
|
shots url="http://127.0.0.1:8226/" out="target/shots":
|
||||||
|
prlimit --core=1:1 -- node scripts/shots.js {{url}} {{out}}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# Tools for building and running sccache-dash.
|
||||||
|
[tools]
|
||||||
|
# Builds the dashboard page (crates/ui) to WebAssembly. The release binary is
|
||||||
|
# downloaded; building trunk from source takes half an hour.
|
||||||
|
"ubi:trunk-rs/trunk" = "0.22.2"
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
// Screenshots of the whole page at each layout width (3, 2 and 1 column), read
|
||||||
|
// before any page change is merged. Usage: just shots [url] [out-dir]
|
||||||
|
const path = require('path');
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
const root = execSync('mise where npm:playwright 2>/dev/null || mise where playwright', { encoding: 'utf8' }).trim();
|
||||||
|
const { chromium } = require(path.join(root, 'node_modules/playwright'));
|
||||||
|
const [, , url = 'http://127.0.0.1:8226/', out = 'target/shots'] = process.argv;
|
||||||
|
(async () => {
|
||||||
|
require('fs').mkdirSync(out, { recursive: true });
|
||||||
|
const browser = await chromium.launch({
|
||||||
|
args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'],
|
||||||
|
});
|
||||||
|
for (const [width, height] of [[1400, 2600], [900, 3600], [390, 5600]]) {
|
||||||
|
// The page scrolls inside its canvas, so a tall window shows all of it.
|
||||||
|
const page = await browser.newPage({ viewport: { width, height }, colorScheme: 'dark' });
|
||||||
|
await page.goto(url);
|
||||||
|
await page.waitForTimeout(5000);
|
||||||
|
const file = path.join(out, `page-${width}.png`);
|
||||||
|
await page.screenshot({ path: file });
|
||||||
|
console.log(file);
|
||||||
|
await page.close();
|
||||||
|
}
|
||||||
|
await browser.close();
|
||||||
|
})().catch((error) => { console.error(error); process.exit(1); });
|
||||||
Reference in new issue
Block a user