Skip to main content

dashboard/
dashboard.rs

1//! A service dashboard fed new numbers every second: key figures in tiles across the top,
2//! charts of the last one or five minutes, and a table of the service's components sortable by
3//! any column. It runs once a second while receiving numbers, and not at all while paused.
4//!   cargo run -p taut --example dashboard
5//! (The numbers are synthetic and deterministic: a real service would supply them from wherever
6//! it keeps them.)
7#![windows_subsystem = "windows"]
8use std::time::{Duration, Instant};
9use taut::{Align, Chart, Column, Length, Series, Table, Ui, Window};
10
11/// The parts of the service, and how much of its work each one gets.
12const PARTS: [(&str, f32); 5] = [("/search", 0.38), ("/pages", 0.27), ("/login", 0.14), ("/upload", 0.12), ("/reports", 0.09)];
13/// How far back the charts go: a minute, or five.
14const SPANS: [&str; 2] = ["Last minute", "Last 5 minutes"];
15/// The most seconds kept.
16const KEPT: usize = 300;
17
18/// What the service did in one second.
19#[derive(Clone, Copy)]
20pub struct Second {
21    requests: f32,
22    /// How long an answer took, in thousandths of a second, as a rule.
23    answer: f32,
24    failed: f32,
25}
26
27/// Everything the dashboard keeps.
28pub struct Dashboard {
29    /// The seconds so far, the newest last.
30    seconds: Vec<Second>,
31    span: usize,
32    paused: bool,
33    table: Table,
34    /// What time it is, and when the next numbers are due.
35    now: Duration,
36    next: Duration,
37    /// How many seconds have been taken in all: what makes the next numbers.
38    count: u64,
39}
40
41impl Default for Dashboard {
42    fn default() -> Self {
43        Dashboard { seconds: Vec::new(), span: 0, paused: false, table: Table::default(), now: Duration::ZERO, next: Duration::from_secs(1), count: 0 }
44    }
45}
46
47impl Dashboard {
48    /// Takes in the numbers of every second that has gone by since the last were taken.
49    fn take_in(&mut self) {
50        while self.next <= self.now {
51            if !self.paused {
52                self.seconds.push(made_up(self.count));
53                self.count += 1;
54            }
55            self.next += Duration::from_secs(1);
56        }
57        let over = self.seconds.len().saturating_sub(KEPT);
58        self.seconds.drain(..over);
59    }
60
61    /// The seconds the charts show.
62    fn shown(&self) -> &[Second] {
63        let span = [60, KEPT][self.span];
64        &self.seconds[self.seconds.len().saturating_sub(span)..]
65    }
66}
67
68/// The numbers of the `nth` second: waves of work, a little noise, and now and then a
69/// stretch in which more fails.
70fn made_up(nth: u64) -> Second {
71    let at = nth as f32;
72    let noise = |salt: u64| ((nth.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(salt) >> 33) % 1000) as f32 / 1000.0;
73    let requests = 420.0 + 160.0 * (at / 37.0).sin() + 60.0 * (at / 9.0).cos() + 40.0 * noise(1);
74    let answer = 38.0 + requests / 25.0 + 12.0 * noise(2);
75    let failed = if nth % 90 > 80 { 6.0 + 10.0 * noise(3) } else { (2.0 * noise(4)).floor() };
76    Second { requests: requests.round(), answer: answer.round(), failed }
77}
78
79pub fn describe(app: &mut Dashboard, ui: &mut Ui) {
80    let t = ui.theme;
81    app.take_in();
82    if !app.paused {
83        ui.wake_after(app.next.saturating_sub(app.now));
84    }
85    ui.column().grow().scroll().pad(16.0).gap(16.0).open();
86
87    // What is shown, and whether numbers are taken in.
88    ui.row().gap(12.0).align(Align::Start, Align::Center).open();
89    ui.text("Service", t.font.bold(), t.text);
90    ui.spacer();
91    ui.segmented(&mut app.span, &SPANS);
92    ui.toggle(&mut app.paused, "Paused");
93    ui.close();
94
95    // The numbers, from the second second on (a chart of one number has no line to draw);
96    // and the parts of the service, which are there from the start.
97    let shown = app.shown();
98    let last = shown.last().copied().filter(|_| shown.len() > 1);
99    match last {
100        Some(last) => numbers(shown, last, ui),
101        None => _ = ui.note("Waiting for the first numbers\u{2026}"),
102    }
103    parts(app, last, ui);
104    ui.close();
105}
106
107/// The numbers that matter most, as tiles, and how they went, as charts.
108fn numbers(shown: &[Second], last: Second, ui: &mut Ui) {
109    let t = ui.theme;
110    let minute = &shown[shown.len().saturating_sub(60)..];
111    let mean = |of: fn(&Second) -> f32| minute.iter().map(of).sum::<f32>() / minute.len() as f32;
112    // The numbers that matter most, each as large as can be read at a glance.
113    ui.wrapping_row().gap(12.0).open();
114    tile(ui, "Requests a second", &format!("{}", last.requests), &format!("{:.0} on average this minute", mean(|second| second.requests)));
115    tile(ui, "Answer time", &format!("{} ms", last.answer), &format!("{:.0} ms on average", mean(|second| second.answer)));
116    tile(ui, "Failed this minute", &format!("{:.0}", minute.iter().map(|second| second.failed).sum::<f32>()), "requests");
117    ui.close();
118
119    // How they went. A chart for each, so each has its own axis: three side by side where
120    // the row has room for them (the room it has in this run, as layout gives it: beside
121    // the strip a bar runs in, where there is one), else fewer.
122    let ends = (-(shown.len() as f32 - 1.0), 0.0);
123    let [requests, answers, failed] = [|second: &Second| second.requests, |second: &Second| second.answer, |second: &Second| second.failed].map(|of| shown.iter().map(of).collect::<Vec<f32>>());
124    ui.wrapping_row().gap(12.0).open();
125    let wide = ((ui.available_size().w - 24.0) / 3.0).floor().max(240.0);
126    chart(ui, "Requests a second", &Chart::of(&[Series::area("", &requests)]).x_range(ends.0, ends.1), wide);
127    chart(ui, "Answer time, ms", &Chart::of(&[Series::line("", &answers)]).x_range(ends.0, ends.1), wide);
128    let most = failed.iter().fold(5.0f32, |most, failed| most.max(*failed));
129    chart(ui, "Failed requests", &Chart::of(&[Series::bars("", &failed).color(t.red)]).y_range(0.0, most), wide);
130    ui.close();
131}
132
133/// A tile: what the number is, the number, and a word on it.
134fn tile(ui: &mut Ui, name: &str, number: &str, beside: &str) {
135    let t = ui.theme;
136    ui.column().w(Length::Px(200.0)).pad(12.0).gap(4.0).fill(t.panel).border(t.line, 1.0).radius(8.0).open();
137    ui.text(name, t.small_font, t.text_dim);
138    ui.text(number, taut::Font::new(t.font.size * 2.0).bold(), t.text);
139    ui.text(beside, t.small_font, t.text_faint);
140    ui.close();
141}
142
143/// A chart in a card, under its name.
144fn chart(ui: &mut Ui, name: &str, chart: &Chart, wide: f32) {
145    let t = ui.theme;
146    ui.column().pad(12.0).gap(6.0).fill(t.panel).border(t.line, 1.0).radius(8.0).open();
147    ui.text(name, t.small_font, t.text_dim);
148    ui.chart(chart, wide - 24.0, 160.0);
149    ui.close();
150}
151
152/// The parts of the service, in a table that sorts; with no numbers yet, a dash in each cell.
153fn parts(app: &mut Dashboard, last: Option<Second>, ui: &mut Ui) {
154    let t = ui.theme;
155    let mut wide = |widest: &str| ui.text_width(widest, t.font).ceil() + 4.0;
156    let columns = [Column::new("Part"), Column::new("Requests a second").px(wide("Requests a second")).align(Align::End), Column::new("Failed").px(wide("Failed")).align(Align::End)];
157    let last = last.unwrap_or(Second { requests: f32::NAN, answer: f32::NAN, failed: f32::NAN });
158    let mut rows: Vec<(&str, f32, f32)> = PARTS.iter().map(|(name, share)| (*name, (last.requests * share).round(), (last.failed * share * 2.0).round())).collect();
159    ui.column().open();
160    ui.table(&mut app.table, &columns);
161    // (Sorted every run: the numbers change every second. By each column it is sorted by,
162    // the first counting most; by name where they say nothing.)
163    rows.sort_by(|a, b| {
164        let mut order = std::cmp::Ordering::Equal;
165        for (column, down) in &app.table.sort {
166            let one = match column {
167                1 => a.1.total_cmp(&b.1),
168                2 => a.2.total_cmp(&b.2),
169                _ => a.0.cmp(b.0),
170            };
171            order = order.then(if *down { one.reverse() } else { one });
172        }
173        order.then(a.0.cmp(b.0))
174    });
175    for row in ui.rows(rows.len(), 26.0) {
176        ui.table_row().key(rows[row].0).open();
177        ui.label(rows[row].0);
178        for number in [rows[row].1, rows[row].2] {
179            ui.label(&if number.is_nan() { "-".to_string() } else { number.to_string() });
180        }
181        ui.close();
182    }
183    ui.close();
184    ui.close();
185    ui.close();
186}
187
188fn main() {
189    let (mut app, started) = (Dashboard::default(), Instant::now());
190    let window = Window { title: "Dashboard", width: 960.0, height: 720.0, min_width: 420.0, min_height: 300.0, ..Default::default() };
191    taut::run(window, move |ui| {
192        app.now = started.elapsed();
193        describe(&mut app, ui);
194    });
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use taut::Role;
201    use taut::testing::Trial;
202
203    #[test]
204    fn new_numbers_come_every_second_until_it_is_paused() {
205        let mut trial = Trial::new(Dashboard::default(), describe);
206        trial.set_time(|dashboard, now| dashboard.now = now);
207        trial.resize(900.0, 700.0, 1.0);
208        assert!(trial.has(Role::Text, "Waiting for the first numbers\u{2026}"));
209
210        // A minute and a half: ninety seconds of numbers, of which the charts show a minute.
211        trial.wait(Duration::from_secs(90));
212        assert_eq!(trial.app.seconds.len(), 90);
213        assert_eq!(trial.app.shown().len(), 60);
214        let last = made_up(89);
215        assert!(trial.has(Role::Text, &last.requests.to_string()) && trial.has(Role::Text, &format!("{} ms", last.answer)));
216        trial.looks_like("tests/looks/dashboard.png");
217
218        // Five minutes' worth, once there are that many.
219        trial.press(Role::Tab, "Last 5 minutes");
220        assert_eq!(trial.app.shown().len(), 90);
221
222        // Paused, nothing comes, and the window is not woken for it; then it goes on.
223        trial.press(Role::Button, "Paused");
224        assert_eq!(trial.ui.wake_in(), None, "nothing to wake for");
225        trial.wait(Duration::from_secs(10));
226        assert_eq!(trial.app.seconds.len(), 90);
227        trial.press(Role::Button, "Paused");
228        trial.wait(Duration::from_secs(3));
229        assert_eq!(trial.app.seconds.len(), 93);
230
231        // The table sorts by what is failing most, and by requests the other way round.
232        trial.press(Role::ColumnHeader, "Requests a second");
233        let first = |trial: &Trial<Dashboard>| trial.visible_access_nodes().iter().find(|node| node.role == Role::Cell && node.grid == Some([0, 0])).map(|node| node.name.clone());
234        assert_eq!(first(&trial).as_deref(), Some("/reports"), "the least first");
235        trial.press(Role::ColumnHeader, "Requests a second");
236        assert_eq!(first(&trial).as_deref(), Some("/search"));
237    }
238}