Dashboard page: fit the page, five shares, build-time histograms

- Built is the miss count, as sccache counts timeouts, cache errors and
  forced recaches inside it. The bar under the headline has five shares
  that add up to every compiler call and always to 100%; what happened
  inside the built share is one line under the bar.
- The time saved shows its 90% range in small print under the figure.
- Speed gains "How long builds take, by language": one fixed-height
  histogram per language on a shared log scale of build time, with the
  mean, median and p90 marked.
- The api crate's Range helpers replace the page's own copies.
- Drawing is built only for the browser, so the tests (and the rest of
  the crate) build anywhere without eframe's native backends.
- Tables are drawn row by row; egui's Grid lost its rows when a cell
  held more than a plain widget. Fold-away bodies are held to the width
  of the page, and the charts fit their data every frame.
- mise.toml takes trunk 0.22.2 as a release binary; building it from
  source took over half an hour.
This commit is contained in:
swaits committed 2026-11-28 12:10:01 -07:00
1 parent c589b7c868
commit dc876b5a5c
13 files changed
+549 -361

No files matched your search

+4 -14
View File
@@ -8,19 +8,19 @@ license.workspace = true
[dependencies]
sccache-dash-api = { path = "../api" }
egui_plot = "0.38"
ehttp = "0.7"
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`.
# 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"
@@ -31,13 +31,3 @@ web-sys = { version = "0.3", features = [
"HtmlCanvasElement",
"Window",
] }
# Native builds only run the tests so far; x11 and wayland are what lets eframe build there.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
eframe = { version = "0.37", default-features = false, features = [
"default_fonts",
"glow",
"persistence",
"wayland",
"x11",
] }
+22 -150
View File
@@ -8,15 +8,6 @@ use sccache_dash_api::{Range, View};
use crate::fmt;
use crate::{cards, extras, net, overtime, problems, raw, speed, style, where_went};
/// The ranges, in the order the buttons show them.
const RANGES: [Range; 5] = [
Range::Hour,
Range::Day,
Range::Week,
Range::Month,
Range::SinceReset,
];
/// Refresh intervals offered, in seconds; zero means off.
const REFRESH_CHOICES: [u64; 4] = [0, 5, 10, 30];
@@ -69,8 +60,6 @@ pub struct Dashboard {
sent_at: Option<f64>,
/// Languages unticked in the "Over time" filter.
hidden_languages: Vec<String>,
/// Set when the charts should forget their zoom and fit the data again.
refit_charts: bool,
/// Whether the "Zero stats" question is open.
asking_zero: bool,
/// A short message for the controls row, and the page time it goes away.
@@ -91,7 +80,6 @@ impl Dashboard {
error: None,
sent_at: None,
hidden_languages: Vec::new(),
refit_charts: false,
asking_zero: false,
note: None,
settings_changed: false,
@@ -202,13 +190,12 @@ impl eframe::App for Dashboard {
view,
error,
hidden_languages,
refit_charts,
..
} = self;
match view {
None => waiting(ui, error.as_deref(), self.refresh_secs),
Some(view) => {
page(ui, view, *range, error.as_deref(), hidden_languages, refit_charts)
page(ui, view, *range, error.as_deref(), hidden_languages)
}
}
});
@@ -252,17 +239,16 @@ fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) {
egui::Panel::top("controls").show(ui, |ui| {
ui.add_space(6.0);
ui.horizontal_wrapped(|ui| {
for range in RANGES {
for range in Range::ALL {
if ui
.add(egui::Button::selectable(
dashboard.range == range,
fmt::range_code(range),
range.code(),
))
.clicked()
{
dashboard.range = range;
dashboard.settings_changed = true;
dashboard.refit_charts = true;
dashboard.send(&ctx, Ask::View);
}
}
@@ -399,7 +385,7 @@ fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) {
};
// The same height the headline and cards take, so the page doesn't jump when they arrive.
ui.allocate_ui_with_layout(
egui::vec2(ui.available_width(), 250.0),
egui::vec2(ui.available_rect_before_wrap().width(), 250.0),
egui::Layout::centered_and_justified(egui::Direction::TopDown),
|ui| {
ui.vertical(|ui| {
@@ -417,7 +403,6 @@ fn page(
asked: Range,
error: Option<&str>,
hidden_languages: &mut Vec<String>,
refit_charts: &mut bool,
) {
let dark = ui.visuals().dark_mode;
let [_, _, bad] = style::marks(dark);
@@ -437,7 +422,7 @@ fn page(
cards::row(ui, view, dark);
problems::section(ui, view, dark);
where_went::section(ui, view, dark);
overtime::section(ui, view, hidden_languages, refit_charts, dark);
overtime::section(ui, view, hidden_languages, dark);
speed::section(ui, view);
extras::section(ui, view);
raw::section(ui, view);
@@ -451,6 +436,8 @@ struct Figure<'a> {
caption: String,
/// Smaller print under the figure.
small: String,
/// A second line of smaller print, kept so the block's height never changes.
small2: String,
/// A trend line and the value it is drawn against.
trend: Option<(&'a [Option<f64>], f64)>,
hover: Option<String>,
@@ -475,6 +462,7 @@ impl Figure<'_> {
None => ui.add_space(TREND_HEIGHT + gap),
}
ui.add(egui::Label::new(egui::RichText::new(&self.small).small().weak()).truncate());
ui.add(egui::Label::new(egui::RichText::new(&self.small2).small().weak()).truncate());
},
);
if let Some(hover) = self.hover {
@@ -484,7 +472,7 @@ impl Figure<'_> {
}
const TREND_HEIGHT: f32 = 22.0;
const FIGURE_HEIGHT: f32 = 104.0;
const FIGURE_HEIGHT: f32 = 120.0;
/// The big numbers, what they mean, and where the cache lives.
fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
@@ -512,9 +500,9 @@ fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
None => text_color,
};
ui.label(egui::RichText::new(fmt::range_title(range)).strong());
ui.label(egui::RichText::new(range.label().to_uppercase()).strong());
let width = ui.available_width();
let width = ui.available_rect_before_wrap().width();
let spacing = ui.spacing().item_spacing.x;
// Side by side where there is room; one under another on a phone.
let columns = if width >= 600.0 { 3.0 } else { 1.0 };
@@ -527,14 +515,21 @@ fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
small: format!("{} of all compiler calls", fmt::percent(totals.hit_rate_of_all())),
trend: Some((&rates, 1.0)),
hover: None,
small2: String::new(),
}
.draw(ui, column);
let left_out = view.time_saved.hits_left_out;
// The 90% range goes first; the hits left out are the line under it.
let interval = view
.time_saved
.interval_90
.map(|(low, high)| format!("{} – {} (90% range)", fmt::duration(low), fmt::duration(high)));
Figure {
value: format!("~{}", fmt::duration(view.time_saved.seconds)),
color: text_color,
caption: "saved (rough)".into(),
small: if left_out > 0 {
small: interval.unwrap_or_default(),
small2: if left_out > 0 {
format!("{} hits left out of this figure", fmt::count(left_out))
} else {
"every hit counted".into()
@@ -556,13 +551,15 @@ fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
.map(|problem| problem.title.clone())
.unwrap_or_else(|| "Nothing needs attention".into()),
small: String::new(),
small2: String::new(),
trend: None,
hover: None,
}
.draw(ui, column);
});
let built = totals.executed.saturating_sub(totals.hits);
// Timeouts, cache errors and forced recaches are inside the built count, as sccache counts them.
let built = totals.misses;
ui.add(egui::Label::new(format!(
"{} compiles · {} from cache · {} built",
fmt::count(totals.requests),
@@ -607,128 +604,3 @@ fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
style::meter(ui, 6.0, full, color);
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 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, "hits_left_out": 7, "note": "Low on purpose." },
"languages": [
{ "name": "Rust", "hits": 229, "misses": 3256, "errors": 0 },
{ "name": "C/C++", "hits": 2082, "misses": 0, "errors": 0 }
],
"not_cached": [["crate-type", 621], ["incremental", 105]],
"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%"
}"#;
fn sample() -> View {
serde_json::from_str(SAMPLE).expect("the sample is a View")
}
#[test]
fn a_view_deserialises() {
let view = sample();
assert_eq!(view.range, Some(Range::Day));
assert_eq!(view.totals.hit_rate(), Some(0.5));
assert_eq!(view.server.version.as_deref(), Some("0.18.0"));
assert_eq!(view.not_cached[0], ("crate-type".to_owned(), 621));
assert_eq!(view.buckets[1].gap, true);
assert_eq!(view.extras[0].rows[0].1, "2");
}
#[test]
fn an_empty_view_deserialises() {
let view: View = serde_json::from_str(
r#"{"range": null, "generated_at": 0, "server": {"status": "NotRunning"},
"totals": {}, "previous": null, "timing": {}, "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!(view.raw.is_null());
}
/// Run the page once without a window and fail if drawing it panics.
fn draw(view: Option<&View>) {
let ctx = egui::Context::default();
ctx.set_fonts(egui::FontDefinitions::default());
let mut hidden = Vec::new();
let mut refit = true;
// An area stands in for the window's own `Ui`.
let _ = ctx.run(egui::RawInput::default(), |ctx| {
egui::Area::new(egui::Id::unique("test-page"))
.show(ctx, |ui| {
ui.set_max_width(800.0);
egui::ScrollArea::vertical()
.auto_shrink([false; 2])
.show(ui, |ui| match view {
None => waiting(ui, Some("connection refused"), 10),
Some(view) => page(ui, view, Range::Day, None, &mut hidden, &mut refit),
});
})
});
}
#[test]
fn the_page_draws_a_full_view() {
let view = sample();
draw(Some(&view));
}
#[test]
fn the_page_draws_a_view_with_nothing_in_it() {
let view: View = serde_json::from_value(serde_json::json!({
"range": "reset", "generated_at": 1, "server": {"status": "Idle"},
"totals": {}, "previous": null, "timing": {}, "time_saved": {},
"languages": [], "not_cached": [], "buckets": [], "problems": [], "extras": [],
"raw": null, "summary_markdown": ""
}))
.expect("an empty view is still a View");
draw(Some(&view));
}
#[test]
fn the_page_draws_while_waiting() {
draw(None);
}
}
+5 -2
View File
@@ -72,7 +72,7 @@ pub fn row(ui: &mut Ui, view: &View, dark: bool) {
},
];
let width = ui.available_width();
let width = ui.available_rect_before_wrap().width();
let spacing = ui.spacing().item_spacing.x;
// Three across where there is room, two on a phone.
let per_row = if width >= 700.0 { 3.0 } else { 2.0 };
@@ -100,10 +100,12 @@ struct Card {
impl Card {
fn draw(self, ui: &mut Ui, width: f32, range: Range, [good, bad]: [Color32; 2]) {
let margin = 8.0;
// Laid out from the top down inside exactly `width`, whatever row it sits in.
ui.allocate_ui_with_layout(egui::vec2(width, HEIGHT), egui::Layout::top_down(egui::Align::Min), |ui| {
egui::Frame::group(ui.style())
.inner_margin(margin)
.show(ui, |ui| {
ui.set_width(width - 2.0 * margin);
ui.set_width(ui.available_rect_before_wrap().width() - 2.0);
ui.set_min_height(HEIGHT - 2.0 * margin);
ui.add(egui::Label::new(RichText::new(self.title).small()).truncate());
let color = self.color.unwrap_or_else(|| ui.visuals().text_color());
@@ -117,6 +119,7 @@ impl Card {
let (change, color) = change(self.count, self.previous, range, self.good_when_up, [good, bad]);
ui.add(egui::Label::new(RichText::new(change).small().color(color)).truncate());
});
});
}
}
+15 -12
View File
@@ -1,6 +1,6 @@
//! Extras: the tables sccache only fills in for some setups.
use eframe::egui::{self, RichText, Ui};
use eframe::egui::{RichText, Ui};
use sccache_dash_api::View;
use crate::style;
@@ -15,17 +15,20 @@ pub fn section(ui: &mut Ui, view: &View) {
ui.add_space(6.0);
}
ui.label(RichText::new(&extra.title).strong());
egui::Grid::new(("extra-table", index))
.num_columns(2)
.striped(true)
.spacing([24.0, 4.0])
.show(ui, |ui| {
for (label, value) in &extra.rows {
ui.add(egui::Label::new(label).truncate())
.on_hover_text(label.clone());
ui.add(egui::Label::new(value).wrap());
}
});
let label_width = if ui.available_rect_before_wrap().width() < 480.0 {
104.0
} else {
160.0
};
for (label, value) in &extra.rows {
style::table_row(
ui,
vec![
style::text_cell(RichText::new(label.as_str()).strong(), label_width, false, false),
style::text_cell(RichText::new(value.as_str()), f32::INFINITY, false, true),
],
);
}
}
});
}
+37 -41
View File
@@ -2,50 +2,36 @@
use sccache_dash_api::Range;
/// The code the server uses for a range, as in `/api/view?range=24h`.
pub fn range_code(range: Range) -> &'static str {
match range {
Range::Hour => "1h",
Range::Day => "24h",
Range::Week => "7d",
Range::Month => "30d",
Range::SinceReset => "reset",
}
/// 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 range a remembered code names.
pub fn range_from_code(code: &str) -> Option<Range> {
[
Range::Hour,
Range::Day,
Range::Week,
Range::Month,
Range::SinceReset,
]
.into_iter()
.find(|range| range_code(*range) == code)
}
/// The heading over the figures: "LAST 24 HOURS".
pub fn range_title(range: Range) -> &'static str {
match range {
Range::Hour => "LAST HOUR",
Range::Day => "LAST 24 HOURS",
Range::Week => "LAST 7 DAYS",
Range::Month => "LAST 30 DAYS",
Range::SinceReset => "SINCE RESET",
/// 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()];
}
}
/// How a comparison with the period before is worded: "previous 24h".
pub fn previous_label(range: Range) -> &'static str {
match range {
Range::Hour => "previous hour",
Range::Day => "previous 24h",
Range::Week => "previous 7d",
Range::Month => "previous 30d",
Range::SinceReset => "the period before",
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".
@@ -64,7 +50,7 @@ pub fn count(n: u64) -> String {
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 > 0 && index % 3 == 0 {
if index % 3 == 0 {
out.push(',');
}
out.push(digit);
@@ -281,4 +267,14 @@ mod tests {
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);
}
}
+129 -10
View File
@@ -1,17 +1,30 @@
//! 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 app;
pub mod cards;
pub mod extras;
pub mod fmt;
pub mod net;
pub mod overtime;
pub mod problems;
pub mod raw;
pub mod speed;
pub mod style;
pub mod where_went;
// 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 where_went;
/// The canvas in `index.html` the page is drawn on.
pub const CANVAS_ID: &str = "the_canvas_id";
@@ -50,3 +63,109 @@ mod web {
});
}
}
#[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": [["crate-type", 621], ["incremental", 105]],
"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], ("crate-type".to_owned(), 621));
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());
}
}
+1 -1
View File
@@ -32,7 +32,7 @@ impl Answer {
/// Ask for the view of a range.
pub fn view(range: Range) -> ehttp::Request {
ehttp::Request::get(format!("/api/view?range={}", crate::fmt::range_code(range)))
ehttp::Request::get(format!("/api/view?range={}", range.code()))
}
/// Ask the server to zero sccache's counters.
+18 -23
View File
@@ -17,11 +17,10 @@ pub fn hit_rate(hits: u64, misses: u64) -> Option<f64> {
(hits + misses > 0).then(|| hits as f64 / (hits + misses) as f64)
}
pub fn section(ui: &mut Ui, view: &View, hidden: &mut Vec<String>, refit: &mut bool, dark: bool) {
pub fn section(ui: &mut Ui, view: &View, hidden: &mut Vec<String>, dark: bool) {
style::section(ui, "overtime", "Over time", |ui| {
filter(ui, view, hidden);
let refit = std::mem::take(refit);
let tz = fmt::local_offset();
let step = bucket_step(&view.buckets, view.range);
let window = view
@@ -38,11 +37,11 @@ pub fn section(ui: &mut Ui, view: &View, hidden: &mut Vec<String>, refit: &mut b
let axes = Axes { window, step, tz };
ui.label(RichText::new("Hit rate").strong());
hit_rate_chart(ui, view, hidden, axes, refit, dark);
hit_rate_chart(ui, view, hidden, axes, dark);
ui.add_space(6.0);
ui.label(RichText::new("Compiles").strong());
volume_chart(ui, view, hidden, axes, refit, dark);
volume_chart(ui, view, hidden, axes, dark);
});
}
@@ -111,12 +110,12 @@ fn bucket_step(buckets: &[Bucket], range: Option<Range>) -> f64 {
/// A chart with a time axis: 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.
/// scrolling the page; that also means it can fit its data afresh every frame,
/// so new buckets are never cut off.
fn time_plot<'a>(
name: &'static str,
axes: Axes,
readout: impl Fn(&PlotPoint) -> String + 'a,
refit: bool,
) -> Plot<'a> {
let (first, last) = axes.window.unwrap_or((0.0, axes.step));
let step = axes.step;
@@ -137,11 +136,7 @@ fn time_plot<'a>(
Corner::LeftTop,
CoordinatesFormatter::new(move |point: &PlotPoint, _bounds: &PlotBounds| readout(point)),
);
if refit {
plot.reset()
} else {
plot
}
plot.reset()
}
fn ticks(from: f64, to: f64, tick: i64) -> Vec<GridMark> {
@@ -216,7 +211,6 @@ fn hit_rate_chart(
view: &View,
hidden: &[String],
axes: Axes,
refit: bool,
dark: bool,
) {
let (step, tz) = (axes.step, axes.tz);
@@ -239,7 +233,6 @@ fn hit_rate_chart(
"hit-rate-chart",
axes,
|point| format!("{} · {:.0}%", fmt::moment_text(point.x.round() as i64), point.y),
refit,
)
.default_y_bounds(0.0, 100.0)
.y_axis_formatter(|mark: GridMark, _| format!("{:.0}%", mark.value));
@@ -263,22 +256,30 @@ fn volume_chart(
view: &View,
hidden: &[String],
axes: Axes,
refit: bool,
dark: bool,
) {
let (step, tz) = (axes.step, axes.tz);
// 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,
|point| fmt::moment_text(point.x.round() as i64),
refit,
)
.legend(Legend::default().position(Corner::RightTop))
.default_y_bounds(0.0, 4.0)
.default_y_bounds(0.0, top)
.y_axis_formatter(|mark: GridMark, _| fmt::count(mark.value.max(0.0).round() as u64));
let width = step * 0.8;
let (mut from_cache, mut built, mut other, mut errors) = (vec![], vec![], vec![], vec![]);
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 + tz) as f64;
@@ -287,7 +288,6 @@ fn volume_chart(
(&mut from_cache, hits),
(&mut built, misses),
(&mut other, bucket.other),
(&mut errors, bucket.errors),
] {
if count > 0 {
bars.push(Bar::new(x, count as f64));
@@ -309,15 +309,10 @@ fn volume_chart(
.width(width)
.color(style::NOT_CACHEABLE)
.stack_on(&[&built]);
let errors = BarChart::new("Errors and timeouts", errors)
.width(width)
.color(style::ERRORS)
.stack_on(&[&other]);
plot.bar_chart(from_cache);
plot.bar_chart(built);
if hidden.is_empty() {
plot.bar_chart(other);
plot.bar_chart(errors);
}
});
if !any {
+3 -2
View File
@@ -21,14 +21,15 @@ pub fn section(ui: &mut Ui, view: &View, dark: bool) {
Severity::Error => "Error",
Severity::Warning => "Warning",
};
let width = ui.available_width();
// As wide as there is room, minus a little (see `banner`).
let width = ui.available_rect_before_wrap().width() - 2.0 * 8.0;
egui::Frame::NONE
.fill(color.gamma_multiply(0.14))
.stroke(Stroke::new(1.0, color))
.corner_radius(6.0)
.inner_margin(8.0)
.show(ui, |ui| {
ui.set_width(width - 16.0);
ui.set_min_width(width - 6.0);
ui.horizontal_wrapped(|ui| {
ui.label(RichText::new(kind).small().strong().color(color));
ui.label(RichText::new(&problem.title).strong());
+153 -10
View File
@@ -1,20 +1,26 @@
//! Speed: how long a cache fetch, a cache write and a build take on average.
//! 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, Layout, RichText, Ui};
use sccache_dash_api::View;
use eframe::egui::{self, Color32, Layout, RichText, Sense, Ui};
use sccache_dash_api::{BuildTimes, View};
use crate::fmt;
use crate::style;
/// Every histogram is this tall, whatever it holds.
const HISTOGRAM_HEIGHT: f32 = 44.0;
/// The slowest build time the axis reaches, as log10 of milliseconds (1,000 s).
const AXIS_TOP: f64 = 6.0;
pub fn section(ui: &mut Ui, view: &View) {
let timing = view.timing;
style::section(ui, "speed", "Speed", |ui| {
let rows = [
("Cache fetch (a hit)", timing.avg_hit_read_ms, style::CACHE),
("Cache write", timing.avg_cache_write_ms, style::BUILT),
("Build (compile)", timing.avg_compile_ms, egui::Color32::GRAY),
("Build (compile)", timing.avg_compile_ms, Color32::GRAY),
];
let label_width = if ui.available_width() < 480.0 {
let label_width = if ui.available_rect_before_wrap().width() < 480.0 {
124.0
} else {
170.0
@@ -35,7 +41,7 @@ pub fn section(ui: &mut Ui, view: &View) {
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 {}x faster than building.", times)
format!("A cache hit is about {times}x faster than building.")
} else if let Some(times) = faster(build, write) {
format!("Writing to the cache is about {times}x faster than building.")
} else {
@@ -43,11 +49,15 @@ pub fn section(ui: &mut Ui, view: &View) {
};
ui.label(sentence);
ui.label(
RichText::new("The bars use a log scale, so a fraction of a millisecond and several \
seconds are both visible.")
.small()
.weak(),
RichText::new(
"The bars use a log scale, so a fraction of a millisecond and several \
seconds are both visible.",
)
.small()
.weak(),
);
build_times(ui, view);
});
}
@@ -62,3 +72,136 @@ fn cell(ui: &mut Ui, width: f32, layout: Layout, contents: impl FnOnce(&mut Ui))
let height = ui.text_style_height(&egui::TextStyle::Body);
ui.allocate_ui_with_layout(egui::vec2(width, height), layout, contents);
}
/// "How long builds take, by language": 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 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(8.0);
ui.label(RichText::new("How long builds take, by language").strong());
// 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 &times.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);
let [_, median_color, p90_color] = style::marks(ui.visuals().dark_mode);
let mean_color = ui.visuals().text_color();
for times in languages {
ui.horizontal_wrapped(|ui| {
ui.label(RichText::new(&times.language).strong());
ui.label(format!("{} builds", fmt::count(times.compiles)));
ui.add_space(6.0);
ui.label(RichText::new(format!("mean {}", ms(times.mean_ms))).small().color(mean_color));
ui.label(
RichText::new(format!("median {}", ms(times.median_ms)))
.small()
.color(median_color),
);
ui.label(
RichText::new(format!("p90 {}", ms(times.p90_ms)))
.small()
.color(p90_color),
);
});
histogram(
ui,
times,
low,
high,
[mean_color, median_color, p90_color],
);
axis(ui, low, high);
ui.add_space(4.0);
}
ui.add(
egui::Label::new(
RichText::new(
"Each point is the average of the builds that finished within one 10-second reading.",
)
.small()
.weak(),
)
.wrap(),
);
}
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, colors: [Color32; 3]) {
let width = ui.available_rect_before_wrap().width();
let (rect, response) =
ui.allocate_exact_size(egui::vec2(width, HISTOGRAM_HEIGHT), Sense::hover());
let painter = ui.painter();
painter.rect_filled(rect, 3.0, ui.visuals().extreme_bg_color);
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 &times.bins {
if bin.compiles == 0 {
continue;
}
let height = HISTOGRAM_HEIGHT * bin.compiles as f32 / top.max(1) as f32;
let bar = egui::Rect::from_min_max(
egui::pos2(at(bin.from_ms), rect.bottom() - height),
egui::pos2((at(bin.to_ms) - 1.0).max(at(bin.from_ms) + 1.0), rect.bottom()),
);
painter.rect_filled(bar, 1.0, style::BUILT.gamma_multiply(0.75));
}
for (value, color) in [times.mean_ms, times.median_ms, times.p90_ms].into_iter().zip(colors) {
let x = at(value);
painter.rect_filled(
egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(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 width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 14.0), Sense::hover());
let font = egui::TextStyle::Small.resolve(ui.style());
let color = ui.visuals().weak_text_color();
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;
ui.painter().text(
egui::pos2(x, rect.center().y),
egui::Align2::CENTER_CENTER,
ms(10.0_f64.powf(value)),
font.clone(),
color,
);
}
}
+67 -6
View File
@@ -1,6 +1,6 @@
//! Colours and small drawings shared by the sections.
use eframe::egui::{self, Color32, Pos2, RichText, Sense, Shape, Stroke, Ui};
use eframe::egui::{self, Align, Color32, Layout, Pos2, RichText, Sense, Shape, Stroke, Ui};
/// Served from the cache.
pub const CACHE: Color32 = Color32::from_rgb(0x4C, 0xAF, 0x50);
@@ -9,7 +9,6 @@ pub const BUILT: Color32 = Color32::from_rgb(0x42, 0xA5, 0xF5);
pub const NOT_CACHEABLE: Color32 = Color32::from_rgb(0xFF, 0xA7, 0x26);
pub const UNSUPPORTED: Color32 = Color32::from_rgb(0xAB, 0x47, 0xBC);
pub const NOT_COMPILE: Color32 = Color32::from_rgb(0x26, 0xA6, 0x9A);
pub const ERRORS: Color32 = Color32::from_rgb(0xEF, 0x53, 0x50);
/// Text colours that mean "good", "worth a look" and "bad", for the theme being drawn.
pub fn marks(dark: bool) -> [Color32; 3] {
@@ -47,10 +46,16 @@ pub fn section<R>(
body: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
ui.add_space(8.0);
// The body is indented, and then thinks it may run that much further right;
// hold it to the width that is left so nothing is pushed off the page.
let body_width = ui.available_rect_before_wrap().width() - ui.spacing().indent;
egui::CollapsingHeader::new(title.into().strong().size(17.0))
.id_salt(id)
.default_open(true)
.show(ui, body)
.show(ui, |ui| {
ui.set_max_width(body_width);
body(ui)
})
.body_returned
}
@@ -58,12 +63,16 @@ pub fn section<R>(
pub fn banner(ui: &mut Ui, text: impl Into<RichText>, color: Color32) {
let mut text: RichText = text.into();
text = text.strong();
// As wide as there is room, minus a little: text that wraps measures itself a few
// pixels wider, and a page that is told to fit exactly that wide grows each time.
let width = ui.available_rect_before_wrap().width() - 2.0 * 8.0 - 6.0;
egui::Frame::NONE
.fill(color.gamma_multiply(0.22))
.stroke(Stroke::new(1.0, color))
.corner_radius(6.0)
.inner_margin(8.0)
.show(ui, |ui| {
ui.set_min_width(width);
ui.add(egui::Label::new(text).wrap());
});
ui.add_space(6.0);
@@ -79,7 +88,7 @@ pub fn swatch(ui: &mut Ui, color: Color32) {
/// 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 (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), height), Sense::hover());
let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_rect_before_wrap().width(), height), Sense::hover());
let painter = ui.painter();
painter.hline(
rect.x_range(),
@@ -117,7 +126,7 @@ pub fn sparkline(ui: &mut Ui, height: f32, values: &[Option<f64>], top: f64, col
/// 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 (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), height), Sense::hover());
let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_rect_before_wrap().width(), height), Sense::hover());
let painter = ui.painter();
painter.rect_filled(rect, height / 2.0, ui.visuals().extreme_bg_color);
let width = (rect.width() * fraction.clamp(0.0, 1.0) as f32).min(rect.width());
@@ -133,7 +142,7 @@ pub fn meter(ui: &mut Ui, height: f32, fraction: f64, fill: Color32) {
/// 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.
pub fn stacked_bar(ui: &mut Ui, height: f32, parts: &[(&'static str, u64, Color32)], total: u64) {
let (rect, response) = ui.allocate_exact_size(egui::vec2(ui.available_width(), height), Sense::hover());
let (rect, response) = ui.allocate_exact_size(egui::vec2(ui.available_rect_before_wrap().width(), height), Sense::hover());
let painter = ui.painter();
painter.rect_filled(rect, 4.0, ui.visuals().extreme_bg_color);
let mut x = rect.left();
@@ -183,3 +192,55 @@ pub fn log_fraction(ms: f64) -> f64 {
let position = (ms.log10() - LOW) / (HIGH - LOW);
position.clamp(0.02, 1.0)
}
/// A cell of [`table_row`]: how wide (`f32::INFINITY` for the width that is left),
/// which side its content lines up with, and what draws it.
pub type Cell<'a> = (f32, egui::Align, Box<dyn FnOnce(&mut Ui) + 'a>);
/// Text in a cell, cut short if it is too long (or wrapped when `wrap` is set);
/// the whole text shows on hover.
pub fn text_cell(text: RichText, width: f32, right: bool, wrap: bool) -> Cell<'static> {
let hover = text.text().to_owned();
let align = if right { egui::Align::Max } else { egui::Align::Min };
let draw = Box::new(move |ui: &mut Ui| {
let label = egui::Label::new(text);
let label = if wrap { label.wrap() } else { label.truncate() };
ui.add(label).on_hover_text(hover);
});
(width, align, draw)
}
/// The width an `f32::INFINITY` cell gets in a row whose other cells are `fixed` wide.
pub fn leftover(ui: &Ui, fixed: &[f32]) -> f32 {
let all = ui.available_rect_before_wrap().width();
(all - fixed.iter().sum::<f32>() - ROW_SPACING * fixed.len() as f32).max(0.0)
}
pub const ROW_SPACING: f32 = 4.0;
/// One table row: cells of fixed widths from the left, one under another across rows.
pub fn table_row(ui: &mut Ui, cells: Vec<Cell<'_>>) {
let line = ui.text_style_height(&egui::TextStyle::Body) + 2.0;
let total = ui.available_rect_before_wrap().width();
let fixed: f32 = cells
.iter()
.filter(|(width, _, _)| width.is_finite())
.map(|(width, _, _)| *width)
.sum();
let rest = (total - fixed - ROW_SPACING * cells.len() as f32).max(0.0);
ui.allocate_ui_with_layout(
egui::vec2(total, line),
Layout::left_to_right(Align::Center),
|ui| {
ui.spacing_mut().item_spacing.x = ROW_SPACING;
for (width, align, draw) in cells {
let width = if width.is_finite() { width } else { rest };
let layout = match align {
Align::Max => Layout::right_to_left(Align::Center),
_ => Layout::left_to_right(Align::Center),
};
ui.allocate_ui_with_layout(egui::vec2(width, line), layout, |ui| draw(ui));
}
},
);
}
+92 -88
View File
@@ -1,61 +1,68 @@
//! Where compiles went: one bar split by outcome, why some could not be
//! cached, and how each language fared.
//! Where compiles went: one bar split by outcome, what happened inside the
//! built share, why some could not be cached, and how each language fared.
use eframe::egui::{self, Layout, RichText, Ui};
use eframe::egui::{self, RichText, Ui};
use sccache_dash_api::View;
use crate::fmt;
use crate::style;
pub fn section(ui: &mut Ui, view: &View, dark: bool) {
pub fn section(ui: &mut Ui, view: &View, _dark: bool) {
let totals = &view.totals;
let built = totals.executed.saturating_sub(totals.hits);
let errors = totals.timeouts + totals.errors();
let parts: [(&'static str, u64, egui::Color32); 6] = [
// 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, egui::Color32); 5] = [
("From cache", totals.hits, style::CACHE),
("Built", built, style::BUILT),
("Built", totals.misses, style::BUILT),
("Not cacheable", totals.not_cacheable, style::NOT_CACHEABLE),
("Unsupported compiler", totals.unsupported_compiler, style::UNSUPPORTED),
("Not a compile", totals.not_compile, style::NOT_COMPILE),
("Errors and timeouts", errors, style::ERRORS),
];
let [_, _, bad] = style::marks(dark);
let all: u64 = parts.iter().map(|(_, count, _)| count).sum();
let percents = fmt::shares(&parts.iter().map(|(_, count, _)| *count).collect::<Vec<_>>());
style::section(ui, "where", "Where compiles went", |ui| {
let total = parts.iter().map(|(_, count, _)| count).sum::<u64>().max(totals.requests);
style::stacked_bar(ui, 22.0, &parts, total);
style::stacked_bar(ui, 22.0, &parts, all);
ui.add_space(4.0);
ui.horizontal_wrapped(|ui| {
for (name, count, color) in parts {
style::swatch(ui, color);
let name = if name == "Errors and timeouts" && count > 0 {
RichText::new(name).color(bad)
} else {
RichText::new(name)
};
ui.label(name);
for ((name, count, color), percent) in parts.iter().zip(&percents) {
style::swatch(ui, *color);
ui.label(*name);
ui.label(
RichText::new(format!("{} · {}", fmt::count(count), fmt::share(count, totals.requests)))
.weak(),
RichText::new(format!("{} · {percent}%", fmt::count(*count))).weak(),
);
ui.add_space(8.0);
}
});
ui.add(
egui::Label::new(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)
))
.wrap(),
);
if !view.not_cached.is_empty() {
ui.add_space(6.0);
ui.label(RichText::new("Why compiles could not be cached").strong());
egui::Grid::new("not-cached-reasons")
.num_columns(3)
.striped(true)
.spacing([24.0, 4.0])
.show(ui, |ui| {
for (reason, count) in &view.not_cached {
ui.label(reason);
right(ui, fmt::count(*count));
right(ui, fmt::share(*count, totals.not_cacheable));
}
});
for (reason, count) in &view.not_cached {
style::table_row(
ui,
vec![
style::text_cell(RichText::new(reason.as_str()), f32::INFINITY, false, false),
style::text_cell(RichText::new(fmt::count(*count)), 72.0, true, false),
style::text_cell(
RichText::new(fmt::share(*count, totals.not_cacheable)),
56.0,
true,
false,
),
],
);
}
}
if !view.languages.is_empty() {
@@ -66,63 +73,60 @@ pub fn section(ui: &mut Ui, view: &View, dark: bool) {
});
}
/// Text pushed to the right edge of its cell.
fn right(ui: &mut Ui, text: impl Into<RichText>) {
ui.with_layout(Layout::right_to_left(egui::Align::Min), |ui| {
ui.label(text.into());
});
}
/// Text at the left of a cell of a fixed width, cut short if it is too long.
fn left(ui: &mut Ui, text: impl Into<RichText>, width: f32) {
let height = ui.text_style_height(&egui::TextStyle::Body);
ui.allocate_ui_with_layout(
egui::vec2(width, height),
Layout::left_to_right(egui::Align::Min),
|ui| {
ui.add(egui::Label::new(text.into()).truncate());
},
);
}
/// One row per language: hits, misses, errors, hit rate and a small bar.
fn languages(ui: &mut Ui, view: &View) {
let narrow = ui.available_width() < 480.0;
let (name_width, bar_width) = if narrow { (72.0, 56.0) } else { (120.0, 160.0) };
let text_color = ui.visuals().text_color();
let dark = ui.visuals().dark_mode;
egui::Grid::new("languages")
.num_columns(6)
.striped(true)
.spacing([12.0, 2.0])
.show(ui, |ui| {
ui.label("");
right(ui, RichText::new("Hits").small().weak());
right(ui, RichText::new("Misses").small().weak());
right(ui, RichText::new("Errors").small().weak());
right(ui, RichText::new("Hit rate").small().weak());
ui.label("");
for language in &view.languages {
left(ui, RichText::new(&language.name).strong(), name_width);
right(ui, RichText::new(fmt::count(language.hits)));
right(ui, RichText::new(fmt::count(language.misses)));
right(
ui,
let text_color = ui.visuals().text_color();
let [_, _, bad] = style::marks(dark);
// Narrower cells on a phone, so the whole row fits.
let (name, hits, misses, errors, rate) = if ui.available_rect_before_wrap().width() < 480.0 {
(68.0, 56.0, 64.0, 52.0, 48.0)
} else {
(130.0, 80.0, 80.0, 72.0, 76.0)
};
let widths = [name, hits, misses, errors, rate];
let bar = (style::leftover(ui, &widths) - style::ROW_SPACING).max(0.0);
let weak = |text: &'static str, width| style::text_cell(RichText::new(text).small().weak(), width, true, false);
style::table_row(
ui,
vec![
style::text_cell(RichText::new("").small(), name, false, false),
weak("Hits", hits),
weak("Misses", misses),
weak("Errors", errors),
weak("Hit rate", rate),
(f32::INFINITY, egui::Align::Min, Box::new(|_ui| {})),
],
);
for language in &view.languages {
let language_rate = crate::overtime::hit_rate(language.hits, language.misses);
let (language_hits, language_misses) = (language.hits, language.misses);
style::table_row(
ui,
vec![
style::text_cell(RichText::new(&language.name).strong(), name, false, false),
style::text_cell(RichText::new(fmt::count(language.hits)), hits, true, false),
style::text_cell(RichText::new(fmt::count(language.misses)), misses, true, false),
style::text_cell(
RichText::new(fmt::count(language.errors))
.color(if language.errors > 0 { style::marks(dark)[2] } else { text_color }),
);
let rate = crate::overtime::hit_rate(language.hits, language.misses);
right(
ui,
RichText::new(fmt::percent(rate)).color(style::hit_rate_color(rate, dark)),
);
let hits = language.hits;
let misses = language.misses;
ui.allocate_ui_with_layout(
egui::vec2(bar_width, 16.0),
Layout::left_to_right(egui::Align::Center),
|ui| style::hit_bar(ui, bar_width, hits, misses),
);
}
});
.color(if language.errors > 0 { bad } else { text_color }),
errors,
true,
false,
),
style::text_cell(
RichText::new(fmt::percent(language_rate))
.color(style::hit_rate_color(language_rate, dark)),
rate,
true,
false,
),
(
f32::INFINITY,
egui::Align::Min,
Box::new(move |ui| style::hit_bar(ui, bar, language_hits, language_misses)),
),
],
);
}
}
+3 -2
View File
@@ -1,4 +1,5 @@
# Tools for building and running sccache-dash.
[tools]
# Builds the dashboard page (crates/ui) to WebAssembly.
"cargo:trunk" = "0.22.2"
# 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"