From b80749ebb55a3e940e1bb047b516ff89edfb12ae Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 28 Nov 2026 11:30:54 -0700 Subject: [PATCH 1/3] 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. --- crates/ui/Cargo.toml | 43 +++ crates/ui/index.html | 29 ++ crates/ui/src/app.rs | 734 ++++++++++++++++++++++++++++++++++++ crates/ui/src/cards.rs | 147 ++++++++ crates/ui/src/extras.rs | 31 ++ crates/ui/src/fmt.rs | 284 ++++++++++++++ crates/ui/src/lib.rs | 52 +++ crates/ui/src/main.rs | 5 + crates/ui/src/net.rs | 110 ++++++ crates/ui/src/overtime.rs | 326 ++++++++++++++++ crates/ui/src/problems.rs | 41 ++ crates/ui/src/raw.rs | 59 +++ crates/ui/src/speed.rs | 64 ++++ crates/ui/src/style.rs | 185 +++++++++ crates/ui/src/where_went.rs | 128 +++++++ mise.toml | 4 + 16 files changed, 2242 insertions(+) create mode 100644 crates/ui/Cargo.toml create mode 100644 crates/ui/index.html create mode 100644 crates/ui/src/app.rs create mode 100644 crates/ui/src/cards.rs create mode 100644 crates/ui/src/extras.rs create mode 100644 crates/ui/src/fmt.rs create mode 100644 crates/ui/src/lib.rs create mode 100644 crates/ui/src/main.rs create mode 100644 crates/ui/src/net.rs create mode 100644 crates/ui/src/overtime.rs create mode 100644 crates/ui/src/problems.rs create mode 100644 crates/ui/src/raw.rs create mode 100644 crates/ui/src/speed.rs create mode 100644 crates/ui/src/style.rs create mode 100644 crates/ui/src/where_went.rs create mode 100644 mise.toml diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml new file mode 100644 index 0000000..14885f5 --- /dev/null +++ b/crates/ui/Cargo.toml @@ -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", +] } diff --git a/crates/ui/index.html b/crates/ui/index.html new file mode 100644 index 0000000..a1c9824 --- /dev/null +++ b/crates/ui/index.html @@ -0,0 +1,29 @@ + + + + + + sccache dash + + + + + + + diff --git a/crates/ui/src/app.rs b/crates/ui/src/app.rs new file mode 100644 index 0000000..570d2d1 --- /dev/null +++ b/crates/ui/src/app.rs @@ -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, + pending: Option<(Ask, net::Answer)>, + /// Why the last request failed, if it did. + error: Option, + /// Page time, in seconds, when the last view was asked for. + sent_at: Option, + /// Languages unticked in the "Over time" filter. + hidden_languages: Vec, + /// 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, 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( + storage: Option<&dyn eframe::Storage>, + key: &str, +) -> Option { + 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, + 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)>, + hover: Option, +} + +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> = view + .buckets + .iter() + .map(|bucket| (!bucket.gap).then(|| overtime::hit_rate(bucket.hits, bucket.misses)).flatten()) + .collect(); + let saved: Vec> = 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); + } +} diff --git a/crates/ui/src/cards.rs b/crates/ui/src/cards.rs new file mode 100644 index 0000000..c1f7da3 --- /dev/null +++ b/crates/ui/src/cards.rs @@ -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, + /// The line between the count and the comparison. + detail: String, + /// The same count in the period before, when the server has one. + previous: Option, + /// 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, + 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 }, + ) +} diff --git a/crates/ui/src/extras.rs b/crates/ui/src/extras.rs new file mode 100644 index 0000000..9137665 --- /dev/null +++ b/crates/ui/src/extras.rs @@ -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()); + } + }); + } + }); +} diff --git a/crates/ui/src/fmt.rs b/crates/ui/src/fmt.rs new file mode 100644 index 0000000..cb2846f --- /dev/null +++ b/crates/ui/src/fmt.rs @@ -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::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) -> 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"); + } +} diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs new file mode 100644 index 0000000..b3d560c --- /dev/null +++ b/crates/ui/src/lib.rs @@ -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::().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:?}")); + }); + } +} diff --git a/crates/ui/src/main.rs b/crates/ui/src/main.rs new file mode 100644 index 0000000..992a5b2 --- /dev/null +++ b/crates/ui/src/main.rs @@ -0,0 +1,5 @@ +//! Entry point of the WebAssembly module; the page itself lives in the library. + +fn main() { + sccache_dash_ui::open(); +} diff --git a/crates/ui/src/net.rs b/crates/ui/src/net.rs new file mode 100644 index 0000000..5ac9bfb --- /dev/null +++ b/crates/ui/src/net.rs @@ -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>>>, +} + +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> { + 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) -> Result { + 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) -> 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::() + .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()) + } +} diff --git a/crates/ui/src/overtime.rs b/crates/ui/src/overtime.rs new file mode 100644 index 0000000..45a773a --- /dev/null +++ b/crates/ui/src/overtime.rs @@ -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 { + (hits + misses > 0).then(|| hits as f64 / (hits + misses) as f64) +} + +pub fn section(ui: &mut Ui, view: &View, hidden: &mut Vec, 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) { + 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) -> 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 { + 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::new(); + let mut run: Vec = 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"); + } +} diff --git a/crates/ui/src/problems.rs b/crates/ui/src/problems.rs new file mode 100644 index 0000000..9e10727 --- /dev/null +++ b/crates/ui/src/problems.rs @@ -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); + } + }); +} diff --git a/crates/ui/src/raw.rs b/crates/ui/src/raw.rs new file mode 100644 index 0000000..611aa77 --- /dev/null +++ b/crates/ui/src/raw.rs @@ -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()); + }); +} diff --git a/crates/ui/src/speed.rs b/crates/ui/src/speed.rs new file mode 100644 index 0000000..55c66de --- /dev/null +++ b/crates/ui/src/speed.rs @@ -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, faster: Option) -> Option { + 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); +} diff --git a/crates/ui/src/style.rs b/crates/ui/src/style.rs new file mode 100644 index 0000000..558988a --- /dev/null +++ b/crates/ui/src/style.rs @@ -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, 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( + ui: &mut Ui, + id: &'static str, + title: impl Into, + body: impl FnOnce(&mut Ui) -> R, +) -> Option { + 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, 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], 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 = Vec::new(); + let flush = |run: &mut Vec, 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) +} diff --git a/crates/ui/src/where_went.rs b/crates/ui/src/where_went.rs new file mode 100644 index 0000000..c42815d --- /dev/null +++ b/crates/ui/src/where_went.rs @@ -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::().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) { + 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, 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), + ); + } + }); +} diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..6c61ed4 --- /dev/null +++ b/mise.toml @@ -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" From dc876b5a5c4f384fe5cb2820f2ce401c8eae81a1 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 28 Nov 2026 12:10:01 -0700 Subject: [PATCH 2/3] 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. --- crates/ui/Cargo.toml | 18 +--- crates/ui/src/app.rs | 172 +++++----------------------------- crates/ui/src/cards.rs | 7 +- crates/ui/src/extras.rs | 27 +++--- crates/ui/src/fmt.rs | 78 ++++++++-------- crates/ui/src/lib.rs | 139 ++++++++++++++++++++++++++-- crates/ui/src/net.rs | 2 +- crates/ui/src/overtime.rs | 41 ++++---- crates/ui/src/problems.rs | 5 +- crates/ui/src/speed.rs | 163 ++++++++++++++++++++++++++++++-- crates/ui/src/style.rs | 73 +++++++++++++-- crates/ui/src/where_went.rs | 180 ++++++++++++++++++------------------ mise.toml | 5 +- 13 files changed, 549 insertions(+), 361 deletions(-) diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index 14885f5..f79b3da 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -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", -] } diff --git a/crates/ui/src/app.rs b/crates/ui/src/app.rs index 570d2d1..3eb9b04 100644 --- a/crates/ui/src/app.rs +++ b/crates/ui/src/app.rs @@ -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, /// Languages unticked in the "Over time" filter. hidden_languages: Vec, - /// 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, - 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)>, hover: Option, @@ -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); - } -} diff --git a/crates/ui/src/cards.rs b/crates/ui/src/cards.rs index c1f7da3..d7b04b0 100644 --- a/crates/ui/src/cards.rs +++ b/crates/ui/src/cards.rs @@ -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()); }); + }); } } diff --git a/crates/ui/src/extras.rs b/crates/ui/src/extras.rs index 9137665..bbf6f82 100644 --- a/crates/ui/src/extras.rs +++ b/crates/ui/src/extras.rs @@ -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), + ], + ); + } } }); } diff --git a/crates/ui/src/fmt.rs b/crates/ui/src/fmt.rs index cb2846f..6c10fad 100644 --- a/crates/ui/src/fmt.rs +++ b/crates/ui/src/fmt.rs @@ -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::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 { + 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 = parts + .iter() + .map(|part| 100.0 * *part as f64 / total as f64) + .collect(); + let mut whole: Vec = exact.iter().map(|value| value.floor() as u64).collect(); + let mut left = 100 - whole.iter().sum::(); + let mut by_fraction: Vec = (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::(), 100); + } } diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index b3d560c..77ee2ca 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -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()); + } +} diff --git a/crates/ui/src/net.rs b/crates/ui/src/net.rs index 5ac9bfb..4d496ed 100644 --- a/crates/ui/src/net.rs +++ b/crates/ui/src/net.rs @@ -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. diff --git a/crates/ui/src/overtime.rs b/crates/ui/src/overtime.rs index 45a773a..b4e958e 100644 --- a/crates/ui/src/overtime.rs +++ b/crates/ui/src/overtime.rs @@ -17,11 +17,10 @@ pub fn hit_rate(hits: u64, misses: u64) -> Option { (hits + misses > 0).then(|| hits as f64 / (hits + misses) as f64) } -pub fn section(ui: &mut Ui, view: &View, hidden: &mut Vec, refit: &mut bool, dark: bool) { +pub fn section(ui: &mut Ui, view: &View, hidden: &mut Vec, 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, 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) -> 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 { @@ -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 { diff --git a/crates/ui/src/problems.rs b/crates/ui/src/problems.rs index 9e10727..f3ca013 100644 --- a/crates/ui/src/problems.rs +++ b/crates/ui/src/problems.rs @@ -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()); diff --git a/crates/ui/src/speed.rs b/crates/ui/src/speed.rs index 55c66de..0abf3de 100644 --- a/crates/ui/src/speed.rs +++ b/crates/ui/src/speed.rs @@ -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 ×.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(×.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 ×.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, + ); + } +} diff --git a/crates/ui/src/style.rs b/crates/ui/src/style.rs index 558988a..bcb7e15 100644 --- a/crates/ui/src/style.rs +++ b/crates/ui/src/style.rs @@ -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( body: impl FnOnce(&mut Ui) -> R, ) -> Option { 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( pub fn banner(ui: &mut Ui, text: impl Into, 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], 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], 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); + +/// 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::() - 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>) { + 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)); + } + }, + ); +} diff --git a/crates/ui/src/where_went.rs b/crates/ui/src/where_went.rs index c42815d..67f8dbc 100644 --- a/crates/ui/src/where_went.rs +++ b/crates/ui/src/where_went.rs @@ -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::>()); style::section(ui, "where", "Where compiles went", |ui| { - let total = parts.iter().map(|(_, count, _)| count).sum::().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) { - 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, 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)), + ), + ], + ); + } } diff --git a/mise.toml b/mise.toml index 6c61ed4..91e212a 100644 --- a/mise.toml +++ b/mise.toml @@ -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" From 46b8dcf2742cd88fe2bc1a910d56d80b314c1b84 Mon Sep 17 00:00:00 2001 From: Stephen Waits Date: Sat, 28 Nov 2026 12:13:45 -0700 Subject: [PATCH 3/3] Hit-rate chart: a mark every quarter, so the axis reads 0% to 100% --- crates/ui/src/overtime.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/crates/ui/src/overtime.rs b/crates/ui/src/overtime.rs index b4e958e..6a4bfde 100644 --- a/crates/ui/src/overtime.rs +++ b/crates/ui/src/overtime.rs @@ -235,6 +235,15 @@ fn hit_rate_chart( |point| format!("{} · {:.0}%", fmt::moment_text(point.x.round() as i64), point.y), ) .default_y_bounds(0.0, 100.0) + // A mark every quarter, so the axis reads 0%, 25%, 50%, 75%, 100%. + .y_grid_spacer(|_: GridInput| { + (0..=4) + .map(|quarter| GridMark { + value: quarter as f64 * 25.0, + step_size: 25.0, + }) + .collect() + }) .y_axis_formatter(|mark: GridMark, _| format!("{:.0}%", mark.value)); let chart = plot.show(ui, |plot| { marks(plot, &view.buckets, step, dark, tz);