Dashboard page for sccache-dash (crates/ui)

An eframe/egui page compiled to WebAssembly with trunk. It draws the one
View the server sends: controls on top, three big figures, six cards, and
the collapsible sections Problems, Where compiles went, Over time, Speed,
Extras and Raw counters. The range, refresh interval and theme are
remembered between visits with eframe storage.

mise.toml names trunk 0.22.2 as the build tool.
This commit is contained in:
swaits committed 2026-11-28 11:30:54 -07:00
1 parent a8e7bd66cf
commit b80749ebb5
16 files changed
+2242

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
[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" }
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`.
[target.'cfg(target_arch = "wasm32")'.dependencies]
eframe = { version = "0.37", default-features = false, features = [
"default_fonts",
"glow",
"persistence",
] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = [
"Document",
"Element",
"HtmlAnchorElement",
"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",
] }
+29
View File
@@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>sccache dash</title>
<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;
background: #111;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<canvas id="the_canvas_id"></canvas>
</body>
</html>
+734
View File
@@ -0,0 +1,734 @@
//! 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::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];
#[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>,
/// 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.
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(),
refit_charts: false,
asking_zero: false,
note: None,
settings_changed: false,
};
let ctx = &cc.egui_ctx;
ctx.set_theme(dashboard.theme.preference());
ctx.all_styles_mut(|style| {
style
.text_styles
.insert(egui::TextStyle::Small, egui::FontId::proportional(11.5));
style.spacing.item_spacing = egui::vec2(8.0, 4.0);
});
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) {
controls(self, ui);
egui::CentralPanel::default().show(ui, |ui| {
egui::ScrollArea::vertical()
.auto_shrink([false; 2])
.show(ui, |ui| {
ui.add_space(8.0);
let Self {
range,
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)
}
}
});
});
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))
}
/// The row of controls that stays at the top of the page.
fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
let now = Dashboard::now(&ctx);
egui::Panel::top("controls").show(ui, |ui| {
ui.add_space(6.0);
ui.horizontal_wrapped(|ui| {
for range in RANGES {
if ui
.add(egui::Button::selectable(
dashboard.range == range,
fmt::range_code(range),
))
.clicked()
{
dashboard.range = range;
dashboard.settings_changed = true;
dashboard.refit_charts = true;
dashboard.send(&ctx, Ask::View);
}
}
ui.add_space(8.0);
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);
}
ui.add_space(8.0);
for theme in ThemeChoice::ALL {
if ui
.add(egui::Button::selectable(dashboard.theme == theme, theme.name()))
.clicked()
{
dashboard.theme = theme;
dashboard.settings_changed = true;
ctx.set_theme(theme.preference());
}
}
ui.add_space(8.0);
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.add_space(8.0);
ui.allocate_ui_with_layout(
egui::vec2(120.0, 20.0),
egui::Layout::left_to_right(egui::Align::Center),
|ui| {
if dashboard
.pending
.as_ref()
.is_some_and(|(ask, _)| *ask == Ask::View)
{
ui.spinner();
ui.label(egui::RichText::new("Updating").small());
} else if let Some((note, _)) = &dashboard.note {
ui.add(egui::Label::new(egui::RichText::new(note).small()).truncate());
}
},
);
});
ui.add_space(6.0);
});
}
/// 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.label(egui::RichText::new("Zero sccache's stats?").strong());
ui.add(egui::Label::new(
"The counters go back to zero. The saved history stays, so the charts keep their \
older data. This can't be undone.",
).wrap());
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 [_, _, bad] = style::marks(ui.visuals().dark_mode);
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}"
),
bad,
),
None => (
"Waiting for the first figures".to_owned(),
"Asking the server for your cache numbers.".to_owned(),
ui.visuals().text_color(),
),
};
// 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::Layout::centered_and_justified(egui::Direction::TopDown),
|ui| {
ui.vertical(|ui| {
ui.label(egui::RichText::new(heading).size(20.0).color(color));
ui.add(egui::Label::new(body).wrap());
});
},
);
}
/// The whole page below the controls.
fn page(
ui: &mut egui::Ui,
view: &View,
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);
if let Some(error) = error {
let from = fmt::moment_text(view.generated_at + fmt::local_offset());
style::banner(
ui,
format!("Lost contact with the server: {error}. These figures are from {from}."),
bad,
);
}
if let Some(error) = &view.server.error {
style::banner(ui, format!("sccache is not working: {error}"), bad);
}
headline(ui, view, asked, dark);
ui.add_space(10.0);
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);
speed::section(ui, view);
extras::section(ui, view);
raw::section(ui, view);
ui.add_space(12.0);
}
/// One of the three big figures.
struct Figure<'a> {
value: String,
color: egui::Color32,
caption: String,
/// Smaller print under the figure.
small: String,
/// A trend line and the value it is drawn against.
trend: Option<(&'a [Option<f64>], f64)>,
hover: Option<String>,
}
impl Figure<'_> {
/// Draw in a column `width` wide and always the same height.
fn draw(self, ui: &mut egui::Ui, width: f32) {
let gap = ui.spacing().item_spacing.y;
let block = ui.allocate_ui_with_layout(
egui::vec2(width, FIGURE_HEIGHT),
egui::Layout::top_down(egui::Align::Min),
|ui| {
ui.set_width(width);
ui.add(
egui::Label::new(egui::RichText::new(&self.value).size(30.0).color(self.color))
.truncate(),
);
ui.add(egui::Label::new(egui::RichText::new(&self.caption).small()).truncate());
match self.trend {
Some((values, top)) => style::sparkline(ui, TREND_HEIGHT, values, top, self.color),
None => ui.add_space(TREND_HEIGHT + gap),
}
ui.add(egui::Label::new(egui::RichText::new(&self.small).small().weak()).truncate());
},
);
if let Some(hover) = self.hover {
block.response.on_hover_text(hover);
}
}
}
const TREND_HEIGHT: f32 = 22.0;
const FIGURE_HEIGHT: f32 = 104.0;
/// The big numbers, what they mean, and where the cache lives.
fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
let range = view.range.unwrap_or(asked);
let totals = &view.totals;
let text_color = ui.visuals().text_color();
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 worst = view.problems.first();
let problem_color = match worst.map(|problem| problem.severity) {
Some(sccache_dash_api::Severity::Error) => style::marks(dark)[2],
Some(sccache_dash_api::Severity::Warning) => style::marks(dark)[1],
None => text_color,
};
ui.label(egui::RichText::new(fmt::range_title(range)).strong());
let width = ui.available_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 };
let column = (width - spacing * (columns - 1.0)) / columns;
ui.horizontal_wrapped(|ui| {
Figure {
value: fmt::percent(totals.hit_rate()),
color: style::hit_rate_color(totals.hit_rate(), dark),
caption: "from cache".into(),
small: format!("{} of all compiler calls", fmt::percent(totals.hit_rate_of_all())),
trend: Some((&rates, 1.0)),
hover: None,
}
.draw(ui, column);
let left_out = view.time_saved.hits_left_out;
Figure {
value: format!("~{}", fmt::duration(view.time_saved.seconds)),
color: text_color,
caption: "saved (rough)".into(),
small: if left_out > 0 {
format!("{} hits left out of this figure", fmt::count(left_out))
} else {
"every hit counted".into()
},
trend: Some((&saved, saved_top)),
hover: Some(view.time_saved.note.clone()),
}
.draw(ui, column);
Figure {
value: if problems == 1 {
"1 problem".into()
} else if problems == 0 {
"No problems".into()
} else {
format!("{} problems", fmt::count(problems as u64))
},
color: problem_color,
caption: worst
.map(|problem| problem.title.clone())
.unwrap_or_else(|| "Nothing needs attention".into()),
small: String::new(),
trend: None,
hover: None,
}
.draw(ui, column);
});
let built = totals.executed.saturating_sub(totals.hits);
ui.add(egui::Label::new(format!(
"{} compiles · {} from cache · {} built",
fmt::count(totals.requests),
fmt::count(totals.hits),
fmt::count(built)
)).wrap());
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 = format!("Cache: {}", parts.join(" · "));
let response = ui.add(egui::Label::new(line).wrap());
if let Some(location) = &server.cache_location {
response.on_hover_text(location.clone());
}
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 >= 0.95 { style::marks(dark)[2] } else { style::CACHE };
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);
}
}
+147
View File
@@ -0,0 +1,147 @@
//! The six compact cards under the headline.
use eframe::egui::{self, Color32, RichText, Ui};
use sccache_dash_api::{Range, View};
use crate::fmt;
use crate::style;
/// Every card is this tall, whatever it has to say.
const HEIGHT: f32 = 78.0;
pub fn row(ui: &mut Ui, view: &View, dark: bool) {
let totals = &view.totals;
let previous = view.previous.as_ref();
let range = view.range.unwrap_or(Range::Day);
let [good, _, bad] = style::marks(dark);
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(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(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 width = ui.available_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 };
let card_width = (width - spacing * (per_row - 1.0)) / per_row;
ui.horizontal_wrapped(|ui| {
for card in cards {
card.draw(ui, card_width, range, [good, bad]);
}
});
}
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,
}
impl Card {
fn draw(self, ui: &mut Ui, width: f32, range: Range, [good, bad]: [Color32; 2]) {
let margin = 8.0;
egui::Frame::group(ui.style())
.inner_margin(margin)
.show(ui, |ui| {
ui.set_width(width - 2.0 * margin);
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());
ui.add(egui::Label::new(RichText::new(fmt::count(self.count)).size(20.0).color(color)).truncate());
let detail = ui.add(
egui::Label::new(RichText::new(&self.detail).small().weak()).truncate(),
);
if !self.detail.is_empty() {
detail.on_hover_text(self.detail.clone());
}
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());
});
}
}
/// 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,
[good, bad]: [Color32; 2],
) -> (String, Color32) {
let gray = Color32::GRAY;
let Some(previous) = previous else {
return (String::new(), gray);
};
if previous == 0 {
return (if count == 0 { String::new() } else { "was 0 before".into() }, gray);
}
let change = (count as f64 - previous as f64) / previous as f64 * 100.0;
if change.abs() < 0.5 {
return ("no change".into(), gray);
}
let better = (change > 0.0) == good_when_up;
(
format!("{change:+.0}% vs {}", fmt::previous_label(range)),
if better { good } else { bad },
)
}
+31
View File
@@ -0,0 +1,31 @@
//! Extras: the tables sccache only fills in for some setups.
use eframe::egui::{self, RichText, Ui};
use sccache_dash_api::View;
use crate::style;
pub fn section(ui: &mut Ui, view: &View) {
if view.extras.is_empty() {
return;
}
style::section(ui, "extras", "Extras", |ui| {
for (index, extra) in view.extras.iter().enumerate() {
if index > 0 {
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());
}
});
}
});
}
+284
View File
@@ -0,0 +1,284 @@
//! How numbers, durations and times are written on the page.
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",
}
}
/// 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",
}
}
/// 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",
}
}
/// 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 > 0 && 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()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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");
}
}
+52
View File
@@ -0,0 +1,52 @@
//! 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;
/// 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:?}"));
});
}
}
+5
View File
@@ -0,0 +1,5 @@
//! Entry point of the WebAssembly module; the page itself lives in the library.
fn main() {
sccache_dash_ui::open();
}
+110
View File
@@ -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={}", crate::fmt::range_code(range)))
}
/// 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())
}
}
+326
View File
@@ -0,0 +1,326 @@
//! Over time: hit rate and compile volume per bucket, with a language filter.
use eframe::egui::{self, Color32, RichText, Stroke, Ui};
use egui_plot::{
Bar, BarChart, CoordinatesFormatter, Corner, GridInput, GridMark, Legend, Line, LineStyle,
Plot, PlotBounds, PlotPoint, PlotPoints, PlotResponse, PlotUi, Span, VLine,
};
use sccache_dash_api::{Bucket, Range, View};
use crate::fmt;
use crate::style;
const CHART_HEIGHT: f32 = 170.0;
/// 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)
}
pub fn section(ui: &mut Ui, view: &View, hidden: &mut Vec<String>, refit: &mut bool, 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
.buckets
.iter()
.filter(|bucket| !bucket.gap)
.map(|bucket| (bucket.start + tz) as f64)
.fold(None::<(f64, f64)>, |window, start| {
Some(match window {
Some((first, last)) => (first.min(start), last.max(start)),
None => (start, start),
})
});
let axes = Axes { window, step, tz };
ui.label(RichText::new("Hit rate").strong());
hit_rate_chart(ui, view, hidden, axes, refit, dark);
ui.add_space(6.0);
ui.label(RichText::new("Compiles").strong());
volume_chart(ui, view, hidden, axes, refit, dark);
});
}
/// What both charts share: the time window, the bucket width and the time zone.
#[derive(Clone, Copy)]
struct Axes {
/// First and last bucket start shown, if any bucket was recorded.
window: Option<(f64, f64)>,
/// Seconds per bucket.
step: f64,
/// Seconds to add to a Unix time to get local clock time.
tz: i64,
}
/// Checkboxes that narrow both charts to some languages.
fn filter(ui: &mut Ui, view: &View, hidden: &mut Vec<String>) {
ui.horizontal_wrapped(|ui| {
let mut all = hidden.is_empty();
if ui.checkbox(&mut all, "All languages").changed() {
*hidden = if all {
view.languages
.iter()
.map(|language| language.name.clone())
.collect()
} else {
Vec::new()
};
}
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.label(
RichText::new(
"Only the chosen languages are counted. The other outcomes can't be split by \
language, so they're left out.",
)
.small()
.weak(),
);
}
}
/// 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,
}
}
/// 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.
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;
let tick = fmt::tick_step(last - first + 2.0 * step);
let plot = Plot::new(name)
.height(CHART_HEIGHT)
.allow_scroll(false)
.allow_drag(false)
.allow_zoom(false)
.allow_boxed_zoom(false)
.include_x(first - step)
.include_x(last + step)
.x_grid_spacer(move |input: GridInput| ticks(input.bounds.0, input.bounds.1, tick))
.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)),
);
if refit {
plot.reset()
} else {
plot
}
}
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 gaps as grey bands, so a gap never reads as zero.
fn marks(plot: &mut PlotUi<'_>, buckets: &[Bucket], step: f64, dark: bool, tz: i64) {
let warn = style::marks(dark)[1];
let shade = if dark {
Color32::WHITE.gamma_multiply(0.08)
} else {
Color32::BLACK.gamma_multiply(0.08)
};
for bucket in buckets {
let start = (bucket.start + tz) as f64;
if bucket.reset {
plot.vline(
VLine::new("Reset", start)
.stroke(Stroke::new(1.5, warn))
.style(LineStyle::Dashed { length: 12.0 }),
);
}
if bucket.gap {
plot.span(
Span::new("Not recorded", start..=start + step)
.fill(shade)
.border_width(0.0),
);
}
}
}
fn overlay(ui: &mut Ui, chart: &PlotResponse<()>, text: &str) {
ui.painter().text(
chart.response.rect.center(),
egui::Align2::CENTER_CENTER,
text,
egui::TextStyle::Body.resolve(ui.style()),
ui.visuals().weak_text_color(),
);
}
/// 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,
refit: bool,
dark: bool,
) {
let (step, tz) = (axes.step, axes.tz);
// 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 + tz) as f64, 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,
|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));
let chart = plot.show(ui, |plot| {
marks(plot, &view.buckets, step, dark, tz);
for points in &runs {
plot.line(
Line::new("Hit rate", PlotPoints::Owned(points.clone()))
.color(style::CACHE)
.width(2.0),
);
}
});
if runs.is_empty() {
overlay(ui, &chart, "No cacheable compiles in this range");
}
}
fn volume_chart(
ui: &mut Ui,
view: &View,
hidden: &[String],
axes: Axes,
refit: bool,
dark: bool,
) {
let (step, tz) = (axes.step, axes.tz);
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)
.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 any = false;
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
let x = (bucket.start + tz) as f64;
let (hits, misses) = split(bucket, hidden);
for (bars, count) in [
(&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));
any = true;
}
}
}
let chart = plot.show(ui, |plot| {
marks(plot, &view.buckets, step, dark, tz);
let from_cache = BarChart::new("From cache", from_cache)
.width(width)
.color(style::CACHE);
let built = BarChart::new("Built", built)
.width(width)
.color(style::BUILT)
.stack_on(&[&from_cache]);
let other = BarChart::new("Not cacheable and other", other)
.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 {
overlay(ui, &chart, "Nothing recorded in this range");
}
}
+41
View File
@@ -0,0 +1,41 @@
//! Problems: what is wrong, most serious first.
use eframe::egui::{self, RichText, Stroke, Ui};
use sccache_dash_api::{Severity, View};
use crate::style;
pub fn section(ui: &mut Ui, view: &View, dark: bool) {
style::section(ui, "problems", "Problems", |ui| {
if view.problems.is_empty() {
ui.label("No problems.");
return;
}
let [_, warn, bad] = style::marks(dark);
for problem in &view.problems {
let color = match problem.severity {
Severity::Error => bad,
Severity::Warning => warn,
};
let kind = match problem.severity {
Severity::Error => "Error",
Severity::Warning => "Warning",
};
let width = ui.available_width();
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.horizontal_wrapped(|ui| {
ui.label(RichText::new(kind).small().strong().color(color));
ui.label(RichText::new(&problem.title).strong());
});
ui.add(egui::Label::new(&problem.detail).wrap());
});
ui.add_space(4.0);
}
});
}
+59
View File
@@ -0,0 +1,59 @@
//! Raw counters: the sccache stats exactly as the server read them.
use eframe::egui::{self, RichText, Ui};
use sccache_dash_api::View;
use crate::style;
pub fn section(ui: &mut Ui, view: &View) {
style::section(ui, "raw", "Raw counters", |ui| match &view.raw {
serde_json::Value::Null => {
ui.label("sccache's raw counters could not be read.");
}
value => tree(ui, value, "raw"),
});
}
/// A tree: one collapsible line per group, `name value` per counter.
fn tree(ui: &mut Ui, value: &serde_json::Value, path: &str) {
match value {
serde_json::Value::Object(fields) => {
for (name, value) in fields {
branch(ui, name, value, path);
}
}
serde_json::Value::Array(items) => {
for (index, value) in items.iter().enumerate() {
branch(ui, &index.to_string(), value, path);
}
}
leaf => counter(ui, "", leaf),
}
}
fn branch(ui: &mut Ui, name: &str, value: &serde_json::Value, path: &str) {
let path = format!("{path}/{name}");
if value.is_object() || value.is_array() {
egui::CollapsingHeader::new(RichText::new(name).strong())
.id_salt(path.clone())
.default_open(true)
.show(ui, |ui| tree(ui, value, &path));
} else {
counter(ui, name, value);
}
}
/// One counter as sccache prints its value.
fn counter(ui: &mut Ui, name: &str, value: &serde_json::Value) {
let text = match value {
serde_json::Value::String(text) => text.clone(),
serde_json::Value::Null => "null".to_owned(),
number => number.to_string(),
};
ui.horizontal_wrapped(|ui| {
if !name.is_empty() {
ui.label(name);
}
ui.label(RichText::new(text).weak());
});
}
+64
View File
@@ -0,0 +1,64 @@
//! Speed: how long a cache fetch, a cache write and a build take on average.
use eframe::egui::{self, Layout, RichText, Ui};
use sccache_dash_api::View;
use crate::fmt;
use crate::style;
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),
];
let label_width = if ui.available_width() < 480.0 {
124.0
} else {
170.0
};
for (label, ms, color) in rows {
ui.horizontal(|ui| {
cell(ui, label_width, Layout::left_to_right(egui::Align::Center), |ui| {
ui.add(egui::Label::new(label).truncate());
});
let text = ms.map_or("—".into(), |ms| fmt::duration(ms / 1000.0));
cell(ui, 72.0, Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(RichText::new(text).strong());
});
style::meter(ui, 12.0, 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 {}x faster than building.", times)
} else if let Some(times) = faster(build, write) {
format!("Writing to the cache is about {times}x faster than building.")
} else {
"There are no timings to compare in this range.".to_owned()
};
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(),
);
});
}
/// `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))
}
/// Draw with a fixed width, so the bars all start at the same place.
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);
}
+185
View File
@@ -0,0 +1,185 @@
//! Colours and small drawings shared by the sections.
use eframe::egui::{self, Color32, Pos2, RichText, Sense, Shape, Stroke, Ui};
/// Served from the cache.
pub const CACHE: Color32 = Color32::from_rgb(0x4C, 0xAF, 0x50);
/// Compiled because the cache had nothing.
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] {
if dark {
[
Color32::from_rgb(0x3F, 0xB9, 0x50),
Color32::from_rgb(0xD2, 0x99, 0x22),
Color32::from_rgb(0xF8, 0x51, 0x49),
]
} else {
[
Color32::from_rgb(0x1A, 0x7F, 0x37),
Color32::from_rgb(0x9A, 0x67, 0x00),
Color32::from_rgb(0xCF, 0x22, 0x2E),
]
}
}
/// The colour of a hit rate: green from 70%, yellow from 40%, red below.
pub fn hit_rate_color(rate: Option<f64>, dark: bool) -> Color32 {
let [good, warn, bad] = marks(dark);
match rate {
Some(rate) if rate >= 0.7 => good,
Some(rate) if rate >= 0.4 => warn,
Some(_) => bad,
None => Color32::GRAY,
}
}
/// A titled section that starts open and can be folded away.
pub fn section<R>(
ui: &mut Ui,
id: &'static str,
title: impl Into<egui::WidgetText>,
body: impl FnOnce(&mut Ui) -> R,
) -> Option<R> {
ui.add_space(8.0);
egui::CollapsingHeader::new(title.into().strong().size(17.0))
.id_salt(id)
.default_open(true)
.show(ui, body)
.body_returned
}
/// A message that must be noticed, in the colour of how bad it is.
pub fn banner(ui: &mut Ui, text: impl Into<RichText>, color: Color32) {
let mut text: RichText = text.into();
text = text.strong();
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.add(egui::Label::new(text).wrap());
});
ui.add_space(6.0);
}
/// A small coloured square in front of a legend entry.
pub fn swatch(ui: &mut Ui, color: Color32) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(10.0, 10.0), Sense::hover());
ui.painter().rect_filled(rect, 2.0, color);
}
/// 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 (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_width(), height), Sense::hover());
let painter = ui.painter();
painter.hline(
rect.x_range(),
rect.bottom() - 0.5,
Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color),
);
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);
}
/// 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 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());
if width > 0.5 {
painter.rect_filled(
egui::Rect::from_min_max(rect.min, egui::pos2(rect.left() + width, rect.bottom())),
height / 2.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.
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 painter = ui.painter();
painter.rect_filled(rect, 4.0, ui.visuals().extreme_bg_color);
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 = egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(x + width, rect.bottom()));
painter.rect_filled(part_rect, 4.0, *color);
x += width;
tip.push_str(&format!("{name}: {} ({})\n", crate::fmt::count(*part), crate::fmt::share(*part, total)));
}
}
if !tip.is_empty() {
response.clone().on_hover_text(tip.trim_end());
}
}
/// A short bar of fixed width showing hits against misses for one language.
pub fn hit_bar(ui: &mut Ui, width: f32, hits: u64, misses: u64) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 12.0), Sense::hover());
let painter = ui.painter();
painter.rect_filled(rect, 3.0, ui.visuals().extreme_bg_color);
let total = hits + misses;
if total > 0 {
let hit_width = rect.width() * hits as f32 / total as f32;
painter.rect_filled(
egui::Rect::from_min_max(rect.min, egui::pos2(rect.left() + hit_width, rect.bottom())),
3.0,
CACHE,
);
}
}
/// 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)
}
+128
View File
@@ -0,0 +1,128 @@
//! Where compiles went: one bar split by outcome, why some could not be
//! cached, and how each language fared.
use eframe::egui::{self, Layout, RichText, Ui};
use sccache_dash_api::View;
use crate::fmt;
use crate::style;
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] = [
("From cache", totals.hits, style::CACHE),
("Built", built, 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);
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);
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);
ui.label(
RichText::new(format!("{} · {}", fmt::count(count), fmt::share(count, totals.requests)))
.weak(),
);
ui.add_space(8.0);
}
});
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));
}
});
}
if !view.languages.is_empty() {
ui.add_space(6.0);
ui.label(RichText::new("By language").strong());
languages(ui, view);
}
});
}
/// 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,
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),
);
}
});
}
+4
View File
@@ -0,0 +1,4 @@
# Tools for building and running sccache-dash.
[tools]
# Builds the dashboard page (crates/ui) to WebAssembly.
"cargo:trunk" = "0.22.2"