diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml new file mode 100644 index 0000000..f79b3da --- /dev/null +++ b/crates/ui/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "sccache-dash-ui" +description = "Dashboard page for sccache-dash" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +sccache-dash-api = { path = "../api" } + +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +# The page is drawn with eframe in the browser for now. A native window would +# open the same `Dashboard`, and needs eframe here with its x11 and wayland features. +[target.'cfg(target_arch = "wasm32")'.dependencies] +eframe = { version = "0.37", default-features = false, features = [ + "default_fonts", + "glow", + "persistence", +] } +egui_plot = "0.38" +ehttp = "0.7" +wasm-bindgen = "0.2" +wasm-bindgen-futures = "0.4" +js-sys = "0.3" +web-sys = { version = "0.3", features = [ + "Document", + "Element", + "HtmlAnchorElement", + "HtmlCanvasElement", + "Window", +] } 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..3eb9b04 --- /dev/null +++ b/crates/ui/src/app.rs @@ -0,0 +1,606 @@ +//! 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}; + +/// 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, + /// Whether the "Zero stats" question is open. + asking_zero: bool, + /// A short message for the controls row, and the page time it goes away. + note: Option<(String, f64)>, + /// Set when the range, refresh interval or theme changed and should be remembered. + settings_changed: bool, +} + +impl Dashboard { + pub fn new(cc: &eframe::CreationContext<'_>) -> Self { + let storage = cc.storage; + let dashboard = Self { + range: remembered(storage, "range").unwrap_or(Range::Day), + refresh_secs: remembered(storage, "refresh").unwrap_or(10), + theme: remembered(storage, "theme").unwrap_or(ThemeChoice::Auto), + view: None, + pending: None, + error: None, + sent_at: None, + hidden_languages: Vec::new(), + asking_zero: false, + note: None, + settings_changed: false, + }; + let ctx = &cc.egui_ctx; + ctx.set_theme(dashboard.theme.preference()); + 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, + .. + } = self; + match view { + None => waiting(ui, error.as_deref(), self.refresh_secs), + Some(view) => { + page(ui, view, *range, error.as_deref(), hidden_languages) + } + } + }); + }); + + if self.asking_zero { + zero_question(self, ui.ctx()); + } + if self.settings_changed { + if let Some(storage) = frame.storage_mut() { + remember(self, storage); + } + self.settings_changed = false; + } + } + + /// Remember the range, refresh interval and theme when the page is closed. + fn save(&mut self, storage: &mut dyn eframe::Storage) { + remember(self, storage); + } +} + +/// Put the range, refresh interval and theme into the storage eframe keeps between visits. +fn remember(dashboard: &Dashboard, storage: &mut dyn eframe::Storage) { + eframe::set_value(storage, "range", &dashboard.range); + eframe::set_value(storage, "refresh", &dashboard.refresh_secs); + eframe::set_value(storage, "theme", &dashboard.theme); +} + +fn remembered( + 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 Range::ALL { + if ui + .add(egui::Button::selectable( + dashboard.range == range, + range.code(), + )) + .clicked() + { + dashboard.range = range; + dashboard.settings_changed = 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_rect_before_wrap().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, +) { + 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, 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 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, +} + +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()); + ui.add(egui::Label::new(egui::RichText::new(&self.small2).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 = 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) { + 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(range.label().to_uppercase()).strong()); + + 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 }; + 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, + 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: 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() + }, + 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(), + small2: String::new(), + trend: None, + hover: None, + } + .draw(ui, column); + }); + + // 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), + 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); + } +} diff --git a/crates/ui/src/cards.rs b/crates/ui/src/cards.rs new file mode 100644 index 0000000..d7b04b0 --- /dev/null +++ b/crates/ui/src/cards.rs @@ -0,0 +1,150 @@ +//! 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_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 }; + 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; + // 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(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()); + 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..bbf6f82 --- /dev/null +++ b/crates/ui/src/extras.rs @@ -0,0 +1,34 @@ +//! Extras: the tables sccache only fills in for some setups. + +use eframe::egui::{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()); + 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 new file mode 100644 index 0000000..6c10fad --- /dev/null +++ b/crates/ui/src/fmt.rs @@ -0,0 +1,280 @@ +//! How numbers, durations and times are written on the page. + +use sccache_dash_api::Range; + +/// How a comparison with the period before is worded, from the range's own +/// label: "previous 24 hours". +pub fn previous_label(range: Range) -> String { + let label = range.label(); + format!("previous {}", label.strip_prefix("last ").unwrap_or(label)) +} + +/// 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()]; + } + 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". +pub fn refresh_label(secs: u64) -> String { + if secs == 0 { + "Off".into() + } else { + format!("Every {secs} s") + } +} + +/// A count with thousands separators: 2815 becomes "2,815". +pub fn count(n: u64) -> String { + let digits = n.to_string(); + let first = (digits.len() - 1) % 3 + 1; + let mut out = String::with_capacity(digits.len() + digits.len() / 3); + out.push_str(&digits[..first]); + for (index, digit) in digits[first..].chars().enumerate() { + if index % 3 == 0 { + out.push(','); + } + out.push(digit); + } + out +} + +/// A ratio as whole percent: 0.456 becomes "46%"; "—" when there is no ratio. +pub fn percent(ratio: Option) -> 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"); + } + + #[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 new file mode 100644 index 0000000..77ee2ca --- /dev/null +++ b/crates/ui/src/lib.rs @@ -0,0 +1,171 @@ +//! 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 fmt; + +// Drawing needs eframe, which is only built for the browser so far; the rest +// (and the tests) build anywhere. +#[cfg(target_arch = "wasm32")] +mod app; +#[cfg(target_arch = "wasm32")] +mod cards; +#[cfg(target_arch = "wasm32")] +mod extras; +#[cfg(target_arch = "wasm32")] +mod net; +#[cfg(target_arch = "wasm32")] +mod overtime; +#[cfg(target_arch = "wasm32")] +mod problems; +#[cfg(target_arch = "wasm32")] +mod raw; +#[cfg(target_arch = "wasm32")] +mod speed; +#[cfg(target_arch = "wasm32")] +mod style; +#[cfg(target_arch = "wasm32")] +mod 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:?}")); + }); + } +} + +#[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/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..4d496ed --- /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={}", range.code())) +} + +/// Ask the server to zero sccache's counters. +pub fn zero() -> ehttp::Request { + ehttp::Request::post("/api/zero", Vec::new()) +} + +/// The view inside a server answer. +pub fn view_from(answer: Result) -> 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..6a4bfde --- /dev/null +++ b/crates/ui/src/overtime.rs @@ -0,0 +1,330 @@ +//! 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, dark: bool) { + style::section(ui, "overtime", "Over time", |ui| { + filter(ui, view, hidden); + + 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, dark); + + ui.add_space(6.0); + ui.label(RichText::new("Compiles").strong()); + volume_chart(ui, view, hidden, axes, 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; 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, +) -> 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)), + ); + plot.reset() +} + +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, + 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), + ) + .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); + 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, + 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), + ) + .legend(Legend::default().position(Corner::RightTop)) + .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) = (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), + ] { + 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]); + plot.bar_chart(from_cache); + plot.bar_chart(built); + if hidden.is_empty() { + plot.bar_chart(other); + } + }); + if !any { + overlay(ui, &chart, "Nothing recorded in this range"); + } +} diff --git a/crates/ui/src/problems.rs b/crates/ui/src/problems.rs new file mode 100644 index 0000000..f3ca013 --- /dev/null +++ b/crates/ui/src/problems.rs @@ -0,0 +1,42 @@ +//! 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", + }; + // 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_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()); + }); + 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..0abf3de --- /dev/null +++ b/crates/ui/src/speed.rs @@ -0,0 +1,207 @@ +//! 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, 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, Color32::GRAY), + ]; + let label_width = if ui.available_rect_before_wrap().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 {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 { + "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(), + ); + + build_times(ui, view); + }); +} + +/// `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); +} + +/// "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 new file mode 100644 index 0000000..bcb7e15 --- /dev/null +++ b/crates/ui/src/style.rs @@ -0,0 +1,246 @@ +//! Colours and small drawings shared by the sections. + +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); +/// 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); + +/// 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); + // 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, |ui| { + ui.set_max_width(body_width); + body(ui) + }) + .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(); + // 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); +} + +/// 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_rect_before_wrap().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_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()); + 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_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(); + 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) +} + +/// 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 new file mode 100644 index 0000000..67f8dbc --- /dev/null +++ b/crates/ui/src/where_went.rs @@ -0,0 +1,132 @@ +//! 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, 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; + // 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", 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), + ]; + 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| { + style::stacked_bar(ui, 22.0, &parts, all); + ui.add_space(4.0); + ui.horizontal_wrapped(|ui| { + for ((name, count, color), percent) in parts.iter().zip(&percents) { + style::swatch(ui, *color); + ui.label(*name); + ui.label( + 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()); + 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() { + ui.add_space(6.0); + ui.label(RichText::new("By language").strong()); + languages(ui, view); + } + }); +} + +/// One row per language: hits, misses, errors, hit rate and a small bar. +fn languages(ui: &mut Ui, view: &View) { + let dark = ui.visuals().dark_mode; + 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 { 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 new file mode 100644 index 0000000..91e212a --- /dev/null +++ b/mise.toml @@ -0,0 +1,5 @@ +# Tools for building and running sccache-dash. +[tools] +# Builds the dashboard page (crates/ui) to WebAssembly. The release binary is +# downloaded; building trunk from source takes half an hour. +"ubi:trunk-rs/trunk" = "0.22.2"