Dashboard page for sccache-dash (crates/ui)
An eframe/egui page compiled to WebAssembly with trunk. It draws the one View the server sends: controls on top, three big figures, six cards, and the collapsible sections Problems, Where compiles went, Over time, Speed, Extras and Raw counters. The range, refresh interval and theme are remembered between visits with eframe storage. mise.toml names trunk 0.22.2 as the build tool.
This commit is contained in:
1 parent
a8e7bd66cf
commit
b80749ebb5
16 files changed
+2242
No files matched your search
@@ -0,0 +1,734 @@
|
||||
//! The dashboard: what it remembers, how it fetches, and the top of the page.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use eframe::egui;
|
||||
use sccache_dash_api::{Range, View};
|
||||
|
||||
use crate::fmt;
|
||||
use crate::{cards, extras, net, overtime, problems, raw, speed, style, where_went};
|
||||
|
||||
/// The ranges, in the order the buttons show them.
|
||||
const RANGES: [Range; 5] = [
|
||||
Range::Hour,
|
||||
Range::Day,
|
||||
Range::Week,
|
||||
Range::Month,
|
||||
Range::SinceReset,
|
||||
];
|
||||
|
||||
/// Refresh intervals offered, in seconds; zero means off.
|
||||
const REFRESH_CHOICES: [u64; 4] = [0, 5, 10, 30];
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
enum ThemeChoice {
|
||||
/// Follow the browser's own light or dark setting.
|
||||
Auto,
|
||||
Light,
|
||||
Dark,
|
||||
}
|
||||
|
||||
impl ThemeChoice {
|
||||
const ALL: [Self; 3] = [Self::Auto, Self::Light, Self::Dark];
|
||||
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Auto => "Auto",
|
||||
Self::Light => "Light",
|
||||
Self::Dark => "Dark",
|
||||
}
|
||||
}
|
||||
|
||||
fn preference(self) -> egui::ThemePreference {
|
||||
match self {
|
||||
Self::Auto => egui::ThemePreference::System,
|
||||
Self::Light => egui::ThemePreference::Light,
|
||||
Self::Dark => egui::ThemePreference::Dark,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a request in flight is for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Ask {
|
||||
View,
|
||||
Zero,
|
||||
}
|
||||
|
||||
/// The whole page. It draws one `View` at a time and keeps the last one on
|
||||
/// screen until the next arrives.
|
||||
pub struct Dashboard {
|
||||
range: Range,
|
||||
refresh_secs: u64,
|
||||
theme: ThemeChoice,
|
||||
view: Option<View>,
|
||||
pending: Option<(Ask, net::Answer)>,
|
||||
/// Why the last request failed, if it did.
|
||||
error: Option<String>,
|
||||
/// Page time, in seconds, when the last view was asked for.
|
||||
sent_at: Option<f64>,
|
||||
/// Languages unticked in the "Over time" filter.
|
||||
hidden_languages: Vec<String>,
|
||||
/// Set when the charts should forget their zoom and fit the data again.
|
||||
refit_charts: bool,
|
||||
/// Whether the "Zero stats" question is open.
|
||||
asking_zero: bool,
|
||||
/// A short message for the controls row, and the page time it goes away.
|
||||
note: Option<(String, f64)>,
|
||||
/// Set when the range, refresh interval or theme changed and should be remembered.
|
||||
settings_changed: bool,
|
||||
}
|
||||
|
||||
impl Dashboard {
|
||||
pub fn new(cc: &eframe::CreationContext<'_>) -> Self {
|
||||
let storage = cc.storage;
|
||||
let dashboard = Self {
|
||||
range: remembered(storage, "range").unwrap_or(Range::Day),
|
||||
refresh_secs: remembered(storage, "refresh").unwrap_or(10),
|
||||
theme: remembered(storage, "theme").unwrap_or(ThemeChoice::Auto),
|
||||
view: None,
|
||||
pending: None,
|
||||
error: None,
|
||||
sent_at: None,
|
||||
hidden_languages: Vec::new(),
|
||||
refit_charts: false,
|
||||
asking_zero: false,
|
||||
note: None,
|
||||
settings_changed: false,
|
||||
};
|
||||
let ctx = &cc.egui_ctx;
|
||||
ctx.set_theme(dashboard.theme.preference());
|
||||
ctx.all_styles_mut(|style| {
|
||||
style
|
||||
.text_styles
|
||||
.insert(egui::TextStyle::Small, egui::FontId::proportional(11.5));
|
||||
style.spacing.item_spacing = egui::vec2(8.0, 4.0);
|
||||
});
|
||||
dashboard
|
||||
}
|
||||
|
||||
fn now(ctx: &egui::Context) -> f64 {
|
||||
ctx.input(|input| input.time)
|
||||
}
|
||||
|
||||
/// Send a request, replacing any request still in flight.
|
||||
fn send(&mut self, ctx: &egui::Context, ask: Ask) {
|
||||
if ask == Ask::View {
|
||||
self.sent_at = Some(Self::now(ctx));
|
||||
}
|
||||
let request = match ask {
|
||||
Ask::View => net::view(self.range),
|
||||
Ask::Zero => net::zero(),
|
||||
};
|
||||
self.pending = Some((ask, net::Answer::send(request, ctx)));
|
||||
}
|
||||
|
||||
/// Pick up the answer to the request in flight, if it has arrived.
|
||||
fn collect(&mut self, ctx: &egui::Context, now: f64) {
|
||||
if self.note.as_ref().is_some_and(|(_, until)| *until <= now) {
|
||||
self.note = None;
|
||||
}
|
||||
let Some(answer) = self
|
||||
.pending
|
||||
.as_ref()
|
||||
.and_then(|(_, answer)| answer.take())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some((ask, _)) = self.pending.take() else {
|
||||
return;
|
||||
};
|
||||
match ask {
|
||||
Ask::View => match net::view_from(answer) {
|
||||
Ok(view) => {
|
||||
self.view = Some(view);
|
||||
self.error = None;
|
||||
}
|
||||
Err(error) => self.error = Some(error),
|
||||
},
|
||||
Ask::Zero => match net::accepted(answer) {
|
||||
Ok(()) => {
|
||||
self.flash("Stats zeroed", now);
|
||||
self.send(ctx, Ask::View);
|
||||
}
|
||||
Err(error) => self.error = Some(format!("The stats could not be zeroed: {error}")),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep asking for a new view at the chosen interval.
|
||||
fn tick(&mut self, ctx: &egui::Context, now: f64) {
|
||||
if self.pending.is_some() {
|
||||
return;
|
||||
}
|
||||
let Some(sent_at) = self.sent_at else {
|
||||
self.send(ctx, Ask::View);
|
||||
return;
|
||||
};
|
||||
if self.refresh_secs == 0 {
|
||||
return;
|
||||
}
|
||||
let every = self.refresh_secs as f64;
|
||||
let since = now - sent_at;
|
||||
if since >= every {
|
||||
self.send(ctx, Ask::View);
|
||||
} else {
|
||||
ctx.request_repaint_after(Duration::from_secs_f64((every - since).max(0.05)));
|
||||
}
|
||||
}
|
||||
|
||||
fn flash(&mut self, text: impl Into<String>, now: f64) {
|
||||
self.note = Some((text.into(), now + 4.0));
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for Dashboard {
|
||||
/// Runs before every frame, also while the window is hidden: pick up answers and keep asking.
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
let now = Self::now(ctx);
|
||||
self.collect(ctx, now);
|
||||
self.tick(ctx, now);
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
controls(self, ui);
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false; 2])
|
||||
.show(ui, |ui| {
|
||||
ui.add_space(8.0);
|
||||
let Self {
|
||||
range,
|
||||
view,
|
||||
error,
|
||||
hidden_languages,
|
||||
refit_charts,
|
||||
..
|
||||
} = self;
|
||||
match view {
|
||||
None => waiting(ui, error.as_deref(), self.refresh_secs),
|
||||
Some(view) => {
|
||||
page(ui, view, *range, error.as_deref(), hidden_languages, refit_charts)
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if self.asking_zero {
|
||||
zero_question(self, ui.ctx());
|
||||
}
|
||||
if self.settings_changed {
|
||||
if let Some(storage) = frame.storage_mut() {
|
||||
remember(self, storage);
|
||||
}
|
||||
self.settings_changed = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Remember the range, refresh interval and theme when the page is closed.
|
||||
fn save(&mut self, storage: &mut dyn eframe::Storage) {
|
||||
remember(self, storage);
|
||||
}
|
||||
}
|
||||
|
||||
/// Put the range, refresh interval and theme into the storage eframe keeps between visits.
|
||||
fn remember(dashboard: &Dashboard, storage: &mut dyn eframe::Storage) {
|
||||
eframe::set_value(storage, "range", &dashboard.range);
|
||||
eframe::set_value(storage, "refresh", &dashboard.refresh_secs);
|
||||
eframe::set_value(storage, "theme", &dashboard.theme);
|
||||
}
|
||||
|
||||
fn remembered<T: serde::de::DeserializeOwned>(
|
||||
storage: Option<&dyn eframe::Storage>,
|
||||
key: &str,
|
||||
) -> Option<T> {
|
||||
storage.and_then(|storage| eframe::get_value(storage, key))
|
||||
}
|
||||
|
||||
/// The row of controls that stays at the top of the page.
|
||||
fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let now = Dashboard::now(&ctx);
|
||||
egui::Panel::top("controls").show(ui, |ui| {
|
||||
ui.add_space(6.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for range in RANGES {
|
||||
if ui
|
||||
.add(egui::Button::selectable(
|
||||
dashboard.range == range,
|
||||
fmt::range_code(range),
|
||||
))
|
||||
.clicked()
|
||||
{
|
||||
dashboard.range = range;
|
||||
dashboard.settings_changed = true;
|
||||
dashboard.refit_charts = true;
|
||||
dashboard.send(&ctx, Ask::View);
|
||||
}
|
||||
}
|
||||
|
||||
ui.add_space(8.0);
|
||||
let mut refresh_secs = dashboard.refresh_secs;
|
||||
egui::ComboBox::from_id_salt("refresh")
|
||||
.selected_text(fmt::refresh_label(refresh_secs))
|
||||
.show_ui(ui, |ui| {
|
||||
for secs in REFRESH_CHOICES {
|
||||
ui.selectable_value(&mut refresh_secs, secs, fmt::refresh_label(secs));
|
||||
}
|
||||
});
|
||||
if refresh_secs != dashboard.refresh_secs {
|
||||
dashboard.refresh_secs = refresh_secs;
|
||||
dashboard.settings_changed = true;
|
||||
}
|
||||
if ui.button("Refresh").clicked() {
|
||||
dashboard.send(&ctx, Ask::View);
|
||||
}
|
||||
|
||||
ui.add_space(8.0);
|
||||
for theme in ThemeChoice::ALL {
|
||||
if ui
|
||||
.add(egui::Button::selectable(dashboard.theme == theme, theme.name()))
|
||||
.clicked()
|
||||
{
|
||||
dashboard.theme = theme;
|
||||
dashboard.settings_changed = true;
|
||||
ctx.set_theme(theme.preference());
|
||||
}
|
||||
}
|
||||
|
||||
ui.add_space(8.0);
|
||||
let online = dashboard.view.is_some();
|
||||
let copy = ui.add_enabled(online, egui::Button::new("Copy summary"));
|
||||
if copy.clicked() {
|
||||
if let Some(view) = &dashboard.view {
|
||||
ctx.copy_text(view.summary_markdown.clone());
|
||||
}
|
||||
dashboard.flash("Summary copied", now);
|
||||
}
|
||||
let export = ui.add_enabled(online, egui::Button::new("Export JSON"));
|
||||
if export.clicked() {
|
||||
let note = net::download("/api/export").map_or_else(
|
||||
|error| format!("Export failed: {error}"),
|
||||
|()| "Export started".to_owned(),
|
||||
);
|
||||
dashboard.flash(note, now);
|
||||
}
|
||||
let zeroing = dashboard
|
||||
.pending
|
||||
.as_ref()
|
||||
.is_some_and(|(ask, _)| *ask == Ask::Zero);
|
||||
let zero = ui.add_enabled(online && !zeroing, egui::Button::new("Zero stats"));
|
||||
if zero.clicked() {
|
||||
dashboard.asking_zero = true;
|
||||
}
|
||||
|
||||
// A fixed-size slot, so that messages come and go without moving the controls.
|
||||
ui.add_space(8.0);
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(120.0, 20.0),
|
||||
egui::Layout::left_to_right(egui::Align::Center),
|
||||
|ui| {
|
||||
if dashboard
|
||||
.pending
|
||||
.as_ref()
|
||||
.is_some_and(|(ask, _)| *ask == Ask::View)
|
||||
{
|
||||
ui.spinner();
|
||||
ui.label(egui::RichText::new("Updating").small());
|
||||
} else if let Some((note, _)) = &dashboard.note {
|
||||
ui.add(egui::Label::new(egui::RichText::new(note).small()).truncate());
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
});
|
||||
}
|
||||
|
||||
/// Ask before zeroing: it can't be undone.
|
||||
fn zero_question(dashboard: &mut Dashboard, ctx: &egui::Context) {
|
||||
let modal = egui::Modal::new(egui::Id::unique("zero-stats-question")).show(ctx, |ui| {
|
||||
ui.set_max_width(360.0);
|
||||
ui.label(egui::RichText::new("Zero sccache's stats?").strong());
|
||||
ui.add(egui::Label::new(
|
||||
"The counters go back to zero. The saved history stays, so the charts keep their \
|
||||
older data. This can't be undone.",
|
||||
).wrap());
|
||||
ui.horizontal(|ui| {
|
||||
if ui.button("Zero stats").clicked() {
|
||||
Some(true)
|
||||
} else if ui.button("Cancel").clicked() {
|
||||
Some(false)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.inner
|
||||
});
|
||||
let answer = modal.inner;
|
||||
if modal.should_close() || answer == Some(false) {
|
||||
dashboard.asking_zero = false;
|
||||
}
|
||||
if answer == Some(true) {
|
||||
dashboard.asking_zero = false;
|
||||
dashboard.send(ctx, Ask::Zero);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the page says while no view has arrived yet.
|
||||
fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) {
|
||||
let [_, _, bad] = style::marks(ui.visuals().dark_mode);
|
||||
let retry = if refresh_secs > 0 {
|
||||
format!("Trying again every {refresh_secs} seconds.")
|
||||
} else {
|
||||
"Press Refresh to try again.".to_owned()
|
||||
};
|
||||
let (heading, body, color) = match error {
|
||||
Some(error) => (
|
||||
"Can't reach the server".to_owned(),
|
||||
format!(
|
||||
"{error}.\n\nCheck that sccache-dash is running on this machine. {retry}"
|
||||
),
|
||||
bad,
|
||||
),
|
||||
None => (
|
||||
"Waiting for the first figures".to_owned(),
|
||||
"Asking the server for your cache numbers.".to_owned(),
|
||||
ui.visuals().text_color(),
|
||||
),
|
||||
};
|
||||
// The same height the headline and cards take, so the page doesn't jump when they arrive.
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(ui.available_width(), 250.0),
|
||||
egui::Layout::centered_and_justified(egui::Direction::TopDown),
|
||||
|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(egui::RichText::new(heading).size(20.0).color(color));
|
||||
ui.add(egui::Label::new(body).wrap());
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// The whole page below the controls.
|
||||
fn page(
|
||||
ui: &mut egui::Ui,
|
||||
view: &View,
|
||||
asked: Range,
|
||||
error: Option<&str>,
|
||||
hidden_languages: &mut Vec<String>,
|
||||
refit_charts: &mut bool,
|
||||
) {
|
||||
let dark = ui.visuals().dark_mode;
|
||||
let [_, _, bad] = style::marks(dark);
|
||||
if let Some(error) = error {
|
||||
let from = fmt::moment_text(view.generated_at + fmt::local_offset());
|
||||
style::banner(
|
||||
ui,
|
||||
format!("Lost contact with the server: {error}. These figures are from {from}."),
|
||||
bad,
|
||||
);
|
||||
}
|
||||
if let Some(error) = &view.server.error {
|
||||
style::banner(ui, format!("sccache is not working: {error}"), bad);
|
||||
}
|
||||
headline(ui, view, asked, dark);
|
||||
ui.add_space(10.0);
|
||||
cards::row(ui, view, dark);
|
||||
problems::section(ui, view, dark);
|
||||
where_went::section(ui, view, dark);
|
||||
overtime::section(ui, view, hidden_languages, refit_charts, dark);
|
||||
speed::section(ui, view);
|
||||
extras::section(ui, view);
|
||||
raw::section(ui, view);
|
||||
ui.add_space(12.0);
|
||||
}
|
||||
|
||||
/// One of the three big figures.
|
||||
struct Figure<'a> {
|
||||
value: String,
|
||||
color: egui::Color32,
|
||||
caption: String,
|
||||
/// Smaller print under the figure.
|
||||
small: String,
|
||||
/// A trend line and the value it is drawn against.
|
||||
trend: Option<(&'a [Option<f64>], f64)>,
|
||||
hover: Option<String>,
|
||||
}
|
||||
|
||||
impl Figure<'_> {
|
||||
/// Draw in a column `width` wide and always the same height.
|
||||
fn draw(self, ui: &mut egui::Ui, width: f32) {
|
||||
let gap = ui.spacing().item_spacing.y;
|
||||
let block = ui.allocate_ui_with_layout(
|
||||
egui::vec2(width, FIGURE_HEIGHT),
|
||||
egui::Layout::top_down(egui::Align::Min),
|
||||
|ui| {
|
||||
ui.set_width(width);
|
||||
ui.add(
|
||||
egui::Label::new(egui::RichText::new(&self.value).size(30.0).color(self.color))
|
||||
.truncate(),
|
||||
);
|
||||
ui.add(egui::Label::new(egui::RichText::new(&self.caption).small()).truncate());
|
||||
match self.trend {
|
||||
Some((values, top)) => style::sparkline(ui, TREND_HEIGHT, values, top, self.color),
|
||||
None => ui.add_space(TREND_HEIGHT + gap),
|
||||
}
|
||||
ui.add(egui::Label::new(egui::RichText::new(&self.small).small().weak()).truncate());
|
||||
},
|
||||
);
|
||||
if let Some(hover) = self.hover {
|
||||
block.response.on_hover_text(hover);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const TREND_HEIGHT: f32 = 22.0;
|
||||
const FIGURE_HEIGHT: f32 = 104.0;
|
||||
|
||||
/// The big numbers, what they mean, and where the cache lives.
|
||||
fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
|
||||
let range = view.range.unwrap_or(asked);
|
||||
let totals = &view.totals;
|
||||
let text_color = ui.visuals().text_color();
|
||||
|
||||
let rates: Vec<Option<f64>> = view
|
||||
.buckets
|
||||
.iter()
|
||||
.map(|bucket| (!bucket.gap).then(|| overtime::hit_rate(bucket.hits, bucket.misses)).flatten())
|
||||
.collect();
|
||||
let saved: Vec<Option<f64>> = view
|
||||
.buckets
|
||||
.iter()
|
||||
.map(|bucket| (!bucket.gap).then_some(bucket.saved_seconds))
|
||||
.collect();
|
||||
let saved_top = saved.iter().flatten().fold(0.0_f64, |top, seconds| top.max(*seconds));
|
||||
|
||||
let problems = view.problems.len();
|
||||
let worst = view.problems.first();
|
||||
let problem_color = match worst.map(|problem| problem.severity) {
|
||||
Some(sccache_dash_api::Severity::Error) => style::marks(dark)[2],
|
||||
Some(sccache_dash_api::Severity::Warning) => style::marks(dark)[1],
|
||||
None => text_color,
|
||||
};
|
||||
|
||||
ui.label(egui::RichText::new(fmt::range_title(range)).strong());
|
||||
|
||||
let width = ui.available_width();
|
||||
let spacing = ui.spacing().item_spacing.x;
|
||||
// Side by side where there is room; one under another on a phone.
|
||||
let columns = if width >= 600.0 { 3.0 } else { 1.0 };
|
||||
let column = (width - spacing * (columns - 1.0)) / columns;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
Figure {
|
||||
value: fmt::percent(totals.hit_rate()),
|
||||
color: style::hit_rate_color(totals.hit_rate(), dark),
|
||||
caption: "from cache".into(),
|
||||
small: format!("{} of all compiler calls", fmt::percent(totals.hit_rate_of_all())),
|
||||
trend: Some((&rates, 1.0)),
|
||||
hover: None,
|
||||
}
|
||||
.draw(ui, column);
|
||||
let left_out = view.time_saved.hits_left_out;
|
||||
Figure {
|
||||
value: format!("~{}", fmt::duration(view.time_saved.seconds)),
|
||||
color: text_color,
|
||||
caption: "saved (rough)".into(),
|
||||
small: if left_out > 0 {
|
||||
format!("{} hits left out of this figure", fmt::count(left_out))
|
||||
} else {
|
||||
"every hit counted".into()
|
||||
},
|
||||
trend: Some((&saved, saved_top)),
|
||||
hover: Some(view.time_saved.note.clone()),
|
||||
}
|
||||
.draw(ui, column);
|
||||
Figure {
|
||||
value: if problems == 1 {
|
||||
"1 problem".into()
|
||||
} else if problems == 0 {
|
||||
"No problems".into()
|
||||
} else {
|
||||
format!("{} problems", fmt::count(problems as u64))
|
||||
},
|
||||
color: problem_color,
|
||||
caption: worst
|
||||
.map(|problem| problem.title.clone())
|
||||
.unwrap_or_else(|| "Nothing needs attention".into()),
|
||||
small: String::new(),
|
||||
trend: None,
|
||||
hover: None,
|
||||
}
|
||||
.draw(ui, column);
|
||||
});
|
||||
|
||||
let built = totals.executed.saturating_sub(totals.hits);
|
||||
ui.add(egui::Label::new(format!(
|
||||
"{} compiles · {} from cache · {} built",
|
||||
fmt::count(totals.requests),
|
||||
fmt::count(totals.hits),
|
||||
fmt::count(built)
|
||||
)).wrap());
|
||||
|
||||
let server = &view.server;
|
||||
let mut parts = Vec::new();
|
||||
if let Some(location) = &server.cache_location {
|
||||
// sccache words it `Local disk: "/home/me/.cache/sccache"`; the kind is enough here.
|
||||
let kind = location.split(':').next().unwrap_or(location);
|
||||
let kind = if kind.eq_ignore_ascii_case("LOCAL DISK") {
|
||||
"local disk".to_owned()
|
||||
} else {
|
||||
kind.to_owned()
|
||||
};
|
||||
parts.push(kind);
|
||||
}
|
||||
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
|
||||
parts.push(format!("{} of {}", fmt::bytes(size), fmt::bytes(max)));
|
||||
}
|
||||
if let Some(version) = server.version.as_deref().or(server.client_version.as_deref()) {
|
||||
parts.push(format!("sccache {version}"));
|
||||
}
|
||||
parts.push(
|
||||
match server.status {
|
||||
sccache_dash_api::Status::Running => "running",
|
||||
sccache_dash_api::Status::Idle => "idle",
|
||||
sccache_dash_api::Status::NotRunning => "not running",
|
||||
}
|
||||
.to_owned(),
|
||||
);
|
||||
let line = format!("Cache: {}", parts.join(" · "));
|
||||
let response = ui.add(egui::Label::new(line).wrap());
|
||||
if let Some(location) = &server.cache_location {
|
||||
response.on_hover_text(location.clone());
|
||||
}
|
||||
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
|
||||
let full = if max > 0 { size as f64 / max as f64 } else { 0.0 };
|
||||
let color = if full >= 0.95 { style::marks(dark)[2] } else { style::CACHE };
|
||||
style::meter(ui, 6.0, full, color);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A view with something in every part of the page.
|
||||
const SAMPLE: &str = r#"{
|
||||
"range": "24h",
|
||||
"generated_at": 1764300000,
|
||||
"server": {
|
||||
"status": "Running",
|
||||
"version": "0.18.0",
|
||||
"client_version": "0.18.0",
|
||||
"cache_location": "Local disk: \"/home/me/.cache/sccache\"",
|
||||
"cache_size": 10726353131,
|
||||
"max_cache_size": 10737418240,
|
||||
"error": null
|
||||
},
|
||||
"totals": {
|
||||
"requests": 5610, "executed": 5610, "hits": 2815, "misses": 2795,
|
||||
"not_cacheable": 0, "unsupported_compiler": 0, "not_compile": 0,
|
||||
"timeouts": 3, "read_errors": 2, "write_errors": 1, "other_errors": 0,
|
||||
"compile_fails": 12, "forced_recaches": 4, "cache_writes": 2795
|
||||
},
|
||||
"previous": {
|
||||
"requests": 5000, "executed": 5000, "hits": 2000, "misses": 3000,
|
||||
"not_cacheable": 0, "unsupported_compiler": 0, "not_compile": 0,
|
||||
"timeouts": 0, "read_errors": 0, "write_errors": 0, "other_errors": 0,
|
||||
"compile_fails": 9, "forced_recaches": 0, "cache_writes": 3000
|
||||
},
|
||||
"timing": { "avg_hit_read_ms": 0.72, "avg_cache_write_ms": 310.0, "avg_compile_ms": 8050.0 },
|
||||
"time_saved": { "seconds": 11100.0, "hits_left_out": 7, "note": "Low on purpose." },
|
||||
"languages": [
|
||||
{ "name": "Rust", "hits": 229, "misses": 3256, "errors": 0 },
|
||||
{ "name": "C/C++", "hits": 2082, "misses": 0, "errors": 0 }
|
||||
],
|
||||
"not_cached": [["crate-type", 621], ["incremental", 105]],
|
||||
"buckets": [
|
||||
{ "start": 1764290000, "hits": 10, "misses": 5, "other": 1, "errors": 0, "saved_seconds": 60.0,
|
||||
"languages": [["Rust", 10, 5]], "reset": false, "gap": false },
|
||||
{ "start": 1764290600, "hits": 0, "misses": 0, "other": 0, "errors": 0, "saved_seconds": 0.0,
|
||||
"languages": [], "reset": false, "gap": true },
|
||||
{ "start": 1764291200, "hits": 4, "misses": 4, "other": 0, "errors": 0, "saved_seconds": 30.0,
|
||||
"languages": [["C/C++", 4, 4]], "reset": true, "gap": false }
|
||||
],
|
||||
"problems": [
|
||||
{ "severity": "Warning", "title": "Rust hit rate 8%", "detail": "Most Rust compiles miss." }
|
||||
],
|
||||
"extras": [ { "title": "Multi-level cache", "rows": [["Levels", "2"]] } ],
|
||||
"raw": { "stats": { "compile_requests": 5610 }, "version": "0.18.0" },
|
||||
"summary_markdown": "**Cache:** 50%"
|
||||
}"#;
|
||||
|
||||
fn sample() -> View {
|
||||
serde_json::from_str(SAMPLE).expect("the sample is a View")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_view_deserialises() {
|
||||
let view = sample();
|
||||
assert_eq!(view.range, Some(Range::Day));
|
||||
assert_eq!(view.totals.hit_rate(), Some(0.5));
|
||||
assert_eq!(view.server.version.as_deref(), Some("0.18.0"));
|
||||
assert_eq!(view.not_cached[0], ("crate-type".to_owned(), 621));
|
||||
assert_eq!(view.buckets[1].gap, true);
|
||||
assert_eq!(view.extras[0].rows[0].1, "2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_view_deserialises() {
|
||||
let view: View = serde_json::from_str(
|
||||
r#"{"range": null, "generated_at": 0, "server": {"status": "NotRunning"},
|
||||
"totals": {}, "previous": null, "timing": {}, "time_saved": {"seconds": 0.0, "hits_left_out": 0, "note": ""},
|
||||
"languages": [], "not_cached": [], "buckets": [], "problems": [], "extras": [],
|
||||
"raw": null, "summary_markdown": ""}"#,
|
||||
)
|
||||
.expect("an empty view is still a View");
|
||||
assert_eq!(view.totals.hit_rate(), None);
|
||||
assert!(view.raw.is_null());
|
||||
}
|
||||
|
||||
/// Run the page once without a window and fail if drawing it panics.
|
||||
fn draw(view: Option<&View>) {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.set_fonts(egui::FontDefinitions::default());
|
||||
let mut hidden = Vec::new();
|
||||
let mut refit = true;
|
||||
// An area stands in for the window's own `Ui`.
|
||||
let _ = ctx.run(egui::RawInput::default(), |ctx| {
|
||||
egui::Area::new(egui::Id::unique("test-page"))
|
||||
.show(ctx, |ui| {
|
||||
ui.set_max_width(800.0);
|
||||
egui::ScrollArea::vertical()
|
||||
.auto_shrink([false; 2])
|
||||
.show(ui, |ui| match view {
|
||||
None => waiting(ui, Some("connection refused"), 10),
|
||||
Some(view) => page(ui, view, Range::Day, None, &mut hidden, &mut refit),
|
||||
});
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_draws_a_full_view() {
|
||||
let view = sample();
|
||||
draw(Some(&view));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_draws_a_view_with_nothing_in_it() {
|
||||
let view: View = serde_json::from_value(serde_json::json!({
|
||||
"range": "reset", "generated_at": 1, "server": {"status": "Idle"},
|
||||
"totals": {}, "previous": null, "timing": {}, "time_saved": {},
|
||||
"languages": [], "not_cached": [], "buckets": [], "problems": [], "extras": [],
|
||||
"raw": null, "summary_markdown": ""
|
||||
}))
|
||||
.expect("an empty view is still a View");
|
||||
draw(Some(&view));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_draws_while_waiting() {
|
||||
draw(None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user