Skip to main content

mortise_core/metrics/
figures.rs

1//! The figures of the Metrics tab: for each row, the rates over a range and the line of requests per
2//! minute. A row is a module of the app, or a route of one module.
3
4use std::collections::HashMap;
5use std::time::Duration;
6
7use crate::app::AppSnapshot;
8use crate::metrics::place::Placing;
9use crate::metrics::sample::{Cell, MetricsStore, Step, Subject};
10
11/// The time the figures of the tab cover.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum Range {
14    FifteenMinutes,
15    #[default]
16    Hour,
17    Day,
18}
19
20impl Range {
21    pub const ALL: [Range; 3] = [Range::FifteenMinutes, Range::Hour, Range::Day];
22
23    pub fn span(self) -> Duration {
24        let minutes = match self {
25            Range::FifteenMinutes => 15,
26            Range::Hour => 60,
27            Range::Day => 24 * 60,
28        };
29        Duration::from_secs(minutes * 60)
30    }
31}
32
33/// What the rows of the table are.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Scope<'a> {
36    /// One row per module of the app.
37    All,
38    /// One row per route of the module with this name.
39    Module(&'a str),
40}
41
42/// The 95% figure: a bucket bound, in seconds.
43#[derive(Debug, Clone, Copy, PartialEq)]
44pub enum Under {
45    /// The smallest finite bound with at least 95% of requests at or under it.
46    Bound(f64),
47    /// More than 5% of requests are over the largest finite bound, which this holds.
48    Above(f64),
49}
50
51/// What one row of the table counts over the range.
52#[derive(Debug, Clone, PartialEq, Default)]
53pub struct Rates {
54    pub requests_per_minute: f64,
55    pub jobs_per_minute: f64,
56    /// `None` with no request in the range, or no bucket bound kept.
57    pub under_95: Option<Under>,
58    /// The share, 0 to 1, of requests answered with a 5xx status. `None` with no request.
59    pub errors: Option<f64>,
60    /// Database time against request time. `None` with no request time, for a route, and when
61    /// `Figures::database_known` is false.
62    pub database: Option<f64>,
63}
64
65/// What a row is about.
66/// Rows of one kind sort by name: a route by its route, then its method.
67#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
68pub enum RowOf {
69    Module(String),
70    /// A route of the module, by method and `http_route`. `route` is `None` for a request with a
71    /// `module` label and no route.
72    Route {
73        route: Option<String>,
74        method: String,
75    },
76}
77
78/// The row of the app as a whole: a module with no name.
79impl Default for RowOf {
80    fn default() -> Self {
81        RowOf::Module(String::new())
82    }
83}
84
85/// A rate between two neighbouring kept reads.
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct Point {
88    /// How long before the newest read this point is: zero for the newest.
89    pub ago: Duration,
90    pub per_minute: f64,
91}
92
93/// Requests per minute over a range.
94#[derive(Debug, Clone, PartialEq, Default)]
95pub struct Line {
96    /// Oldest first. A new run starts after a gap: the chart draws no segment between two runs.
97    pub runs: Vec<Vec<Point>>,
98}
99
100impl Line {
101    /// The newest point when it is the newest read: "842 now".
102    pub fn now(&self) -> Option<f64> {
103        self.runs
104            .last()
105            .and_then(|run| run.last())
106            .filter(|point| point.ago.is_zero())
107            .map(|point| point.per_minute)
108    }
109}
110
111/// One row of the table.
112#[derive(Debug, Clone, PartialEq, Default)]
113pub struct Row {
114    pub of: RowOf,
115    pub rates: Rates,
116    /// Requests per minute over the range, for the chart. Built for `Figures::total` and the
117    /// selected row only: empty for every other row, as a day of a few thousand routes would be
118    /// millions of points.
119    pub line: Line,
120    /// Requests per minute over the last hour, for the column "Last hour". Built for every row.
121    pub last_hour: Line,
122}
123
124/// The figures of a scope over a range.
125#[derive(Debug, Clone, PartialEq, Default)]
126pub struct Figures {
127    /// The time the rates cover. `None` before two reads of one run lie in the range.
128    pub covered: Option<Duration>,
129    /// All: one row per module of the app. Module: one row per route of the module.
130    /// Most requests first, then by name (route, then method).
131    pub rows: Vec<Row>,
132    /// All: "Not in a module". Module: `None`.
133    pub outside: Option<Row>,
134    /// Everything in the scope: the app, or the module.
135    pub total: Row,
136    /// Some kept series has a `module` label.
137    pub database_known: bool,
138}
139
140/// Where a kept subject counts.
141#[derive(Debug, Clone, Copy, Default)]
142struct Target {
143    /// The row in `rows`, or the last slot for "Not in a module".
144    slot: Option<usize>,
145    /// It counts in the total of the scope.
146    total: bool,
147}
148
149/// What the subjects of one row grew by, added.
150#[derive(Debug, Clone, Default)]
151struct Sum {
152    requests: Cell,
153    jobs: f64,
154    database: f64,
155}
156
157impl Sum {
158    fn add(&mut self, subject: &Subject, cell: &Cell) {
159        match subject {
160            Subject::Request { .. } => {
161                let requests = &mut self.requests;
162                requests.count += cell.count;
163                requests.errors += cell.errors;
164                requests.sum += cell.sum;
165                if requests.buckets.len() < cell.buckets.len() {
166                    requests.buckets.resize(cell.buckets.len(), 0.0);
167                }
168                // Buckets are cumulative, so a bucket holds at least every bucket below it. A
169                // series that lacks a bound the store holds has 0 there: the running maximum
170                // gives it the bucket of the bound below.
171                let mut below = 0.0_f64;
172                for (bucket, &grew) in requests.buckets.iter_mut().zip(&cell.buckets) {
173                    below = below.max(grew);
174                    *bucket += below;
175                }
176            }
177            Subject::Job { .. } => self.jobs += cell.count,
178            Subject::Database { .. } => self.database += cell.sum,
179        }
180    }
181
182    /// The rates over `covered`. `database` is false for a route, and when no series has a
183    /// `module` label.
184    fn rates(&self, covered: Duration, bounds: &[f64], database: bool) -> Rates {
185        let per_minute = 60.0 / covered.as_secs_f64();
186        let Cell {
187            count,
188            errors,
189            sum,
190            buckets,
191        } = &self.requests;
192        let requested = *count > 0.0;
193        // Buckets are cumulative. 20 × bucket ≥ 19 × count is 95% with no rounding of 0.95.
194        let under_95 = bounds.last().filter(|_| requested).map(|&largest| {
195            bounds
196                .iter()
197                .zip(buckets)
198                .find(|(_, bucket)| **bucket * 20.0 >= count * 19.0)
199                .map_or(Under::Above(largest), |(&bound, _)| Under::Bound(bound))
200        });
201        Rates {
202            requests_per_minute: count * per_minute,
203            jobs_per_minute: self.jobs * per_minute,
204            under_95,
205            errors: requested.then(|| errors / count),
206            database: (database && *sum > 0.0).then(|| self.database / sum),
207        }
208    }
209}
210
211/// The line of each slot: what the request subjects of the slot grew by at each step. The last
212/// slot is the total. `targets` holds a target per kept subject; one that is no request counts
213/// nowhere. A slot that `built` does not hold gets an empty line.
214fn lines(steps: &[Step], newest: Duration, targets: &[Target], built: &[bool]) -> Vec<Line> {
215    let width = built.len();
216    let mut lines = vec![Line::default(); width];
217    let mut counts = vec![0.0; width];
218    for step in steps {
219        counts.fill(0.0);
220        for (target, grew) in targets.iter().zip(&step.counts) {
221            if let Some(slot) = target.slot {
222                counts[slot] += grew;
223            }
224            if target.total {
225                counts[width - 1] += grew;
226            }
227        }
228        let ago = newest.saturating_sub(step.at);
229        let per_minute = 60.0 / step.covered.as_secs_f64();
230        for ((line, &count), _) in lines
231            .iter_mut()
232            .zip(&counts)
233            .zip(built)
234            .filter(|(_, built)| **built)
235        {
236            let point = Point {
237                ago,
238                per_minute: count * per_minute,
239            };
240            match line.runs.last_mut() {
241                Some(run) if !step.starts => run.push(point),
242                _ => line.runs.push(vec![point]),
243            }
244        }
245    }
246    lines
247}
248
249impl Figures {
250    /// Places what the store kept over `range` and works out the rows of `scope`. In the scope All,
251    /// every module of `app` has a row, also with no change. The line over the range is built for
252    /// the total and the `selected` row only.
253    pub(crate) fn of(
254        app: &AppSnapshot,
255        placing: &Placing<'_>,
256        scope: Scope<'_>,
257        store: &MetricsStore,
258        range: Range,
259        selected: Option<&RowOf>,
260    ) -> Self {
261        let subjects: Vec<&Subject> = store.subjects().collect();
262        let database_known = subjects.iter().any(|subject| match subject {
263            Subject::Request { module, .. } | Subject::Job { module, .. } => module.is_some(),
264            Subject::Database { .. } => true,
265        });
266
267        // The rows, then where each subject counts.
268        let (mut ofs, targets): (Vec<RowOf>, Vec<Target>) = match scope {
269            Scope::All => {
270                let ofs: Vec<RowOf> = app
271                    .modules
272                    .iter()
273                    .map(|module| RowOf::Module(module.name.clone()))
274                    .collect();
275                let slot: HashMap<&str, usize> = app
276                    .modules
277                    .iter()
278                    .enumerate()
279                    .map(|(slot, module)| (module.name.as_str(), slot))
280                    .collect();
281                let targets = subjects
282                    .iter()
283                    .map(|subject| Target {
284                        slot: Some(
285                            placing
286                                .place(subject)
287                                .and_then(|name| slot.get(name).copied())
288                                .unwrap_or(ofs.len()),
289                        ),
290                        total: true,
291                    })
292                    .collect();
293                (ofs, targets)
294            }
295            Scope::Module(name) => {
296                let mut ofs = Vec::new();
297                let mut slot: HashMap<RowOf, usize> = HashMap::new();
298                let targets = subjects
299                    .iter()
300                    .map(|subject| {
301                        // `place` gives only names of modules of the app.
302                        if placing.place(subject) != Some(name) {
303                            return Target::default();
304                        }
305                        let Subject::Request { route, method, .. } = subject else {
306                            return Target {
307                                slot: None,
308                                total: true,
309                            };
310                        };
311                        let of = RowOf::Route {
312                            route: route.clone(),
313                            method: method.clone(),
314                        };
315                        let at = *slot.entry(of).or_insert_with_key(|of| {
316                            ofs.push(of.clone());
317                            ofs.len() - 1
318                        });
319                        Target {
320                            slot: Some(at),
321                            total: true,
322                        }
323                    })
324                    .collect();
325                (ofs, targets)
326            }
327        };
328        // The slots: the rows, "Not in a module", then the total.
329        let outside = ofs.len();
330        let width = outside + 2;
331        ofs.push(RowOf::default());
332        ofs.push(match scope {
333            Scope::All => RowOf::default(),
334            Scope::Module(name) => RowOf::Module(name.to_owned()),
335        });
336
337        let change = store.change(range.span());
338        let mut rates = vec![Rates::default(); width];
339        if let Some(change) = &change {
340            let mut sums = vec![Sum::default(); width];
341            for ((subject, cell), target) in change.cells.iter().zip(&targets) {
342                if let Some(slot) = target.slot {
343                    sums[slot].add(subject, cell);
344                }
345                if target.total {
346                    sums[width - 1].add(subject, cell);
347                }
348            }
349            let routes = matches!(scope, Scope::Module(_));
350            for (slot, (sum, rates)) in sums.iter().zip(&mut rates).enumerate() {
351                let database = database_known && !(routes && slot < outside);
352                *rates = sum.rates(change.covered, change.bounds, database);
353            }
354        }
355
356        // Lines count requests only.
357        let requests: Vec<Target> = targets
358            .iter()
359            .zip(&subjects)
360            .map(|(target, subject)| match subject {
361                Subject::Request { .. } => *target,
362                _ => Target::default(),
363            })
364            .collect();
365        let newest = store.newest().unwrap_or_default();
366        // The line over the range: the total, and the selected row.
367        let built: Vec<bool> = ofs
368            .iter()
369            .enumerate()
370            .map(|(slot, of)| slot == width - 1 || Some(of) == selected)
371            .collect();
372        let line = lines(&store.steps(range.span()), newest, &requests, &built);
373        let every = vec![true; width];
374        let last_hour = lines(&store.steps(Range::Hour.span()), newest, &requests, &every);
375
376        let mut rows: Vec<Row> = ofs
377            .into_iter()
378            .zip(rates)
379            .zip(line.into_iter().zip(last_hour))
380            .map(|((of, rates), (line, last_hour))| Row {
381                of,
382                rates,
383                line,
384                last_hour,
385            })
386            .collect();
387        let total = rows.pop().unwrap_or_default();
388        let outside = rows.pop().filter(|_| scope == Scope::All);
389        rows.sort_by(|a, b| {
390            b.rates
391                .requests_per_minute
392                .total_cmp(&a.rates.requests_per_minute)
393                .then_with(|| a.of.cmp(&b.of))
394        });
395        Self {
396            covered: change.map(|change| change.covered),
397            rows,
398            outside,
399            total,
400            database_known,
401        }
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use std::path::Path;
408
409    use super::*;
410    use crate::metrics::sample::Reading;
411
412    const PACE: Duration = Duration::from_secs(15);
413
414    fn secs(seconds: u64) -> Duration {
415        Duration::from_secs(seconds)
416    }
417
418    fn shop() -> AppSnapshot {
419        let fixtures = concat!(env!("CARGO_MANIFEST_DIR"), "/../../fixtures/shop-api");
420        crate::read_app(Path::new(fixtures)).unwrap()
421    }
422
423    fn request(module: &str, route: &str) -> Subject {
424        Subject::Request {
425            module: Some(module.to_owned()),
426            route: Some(route.to_owned()),
427            method: "GET".to_owned(),
428        }
429    }
430
431    fn reading(bounds: &[f64], cells: Vec<(Subject, Cell)>) -> Reading {
432        Reading {
433            bounds: bounds.to_vec(),
434            series: cells
435                .into_iter()
436                .map(|(subject, cell)| ((subject, String::new()), cell))
437                .collect(),
438        }
439    }
440
441    #[test]
442    fn a_module_label_gives_database_time_and_slow_requests_read_above() {
443        let app = shop();
444        let placing = Placing::new(&app, None);
445        let mut store = MetricsStore::new(PACE);
446        store.push(secs(0), reading(&[], Vec::new())).unwrap();
447        let cell = |count: f64, sum: f64, buckets: Vec<f64>| Cell {
448            count,
449            errors: 0.0,
450            sum,
451            buckets,
452        };
453        let cells = vec![
454            (
455                request("billing", "/billing/invoices"),
456                cell(10.0, 8.0, vec![10.0, 10.0]),
457            ),
458            (
459                Subject::Database {
460                    module: "billing".to_owned(),
461                },
462                cell(0.0, 2.0, Vec::new()),
463            ),
464            // Every request slower than 10 s, the largest finite bound.
465            (
466                request("catalog", "/catalog"),
467                cell(10.0, 150.0, vec![0.0, 0.0]),
468            ),
469        ];
470        store.push(secs(15), reading(&[0.1, 10.0], cells)).unwrap();
471
472        let figures = Figures::of(&app, &placing, Scope::All, &store, Range::Hour, None);
473        assert!(figures.database_known);
474        let of = |name: &str| {
475            let row = figures
476                .rows
477                .iter()
478                .find(|row| row.of == RowOf::Module(name.to_owned()));
479            row.map(|row| (row.rates.under_95, row.rates.database))
480        };
481        assert_eq!(of("Billing"), Some((Some(Under::Bound(0.1)), Some(0.25))));
482        // A module with no database series reads 0% once any series has the label.
483        assert_eq!(of("Catalog"), Some((Some(Under::Above(10.0)), Some(0.0))));
484        // A route has no database time.
485        let billing = Figures::of(
486            &app,
487            &placing,
488            Scope::Module("Billing"),
489            &store,
490            Range::Hour,
491            None,
492        );
493        assert_eq!(billing.rows[0].rates.database, None);
494        assert_eq!(billing.total.rates.database, Some(0.25));
495
496        // Two series of one row give different bounds: each lacks the bound of the other. All
497        // 200 requests are at or under 2 s.
498        let mut store = MetricsStore::new(PACE);
499        store.push(secs(0), reading(&[], Vec::new())).unwrap();
500        let cells = vec![
501            (
502                request("billing", "/billing/a"),
503                cell(100.0, 10.0, vec![100.0, f64::NAN]),
504            ),
505            (
506                request("billing", "/billing/b"),
507                cell(100.0, 150.0, vec![f64::NAN, 100.0]),
508            ),
509        ];
510        store.push(secs(15), reading(&[1.0, 2.0], cells)).unwrap();
511        let figures = Figures::of(&app, &placing, Scope::All, &store, Range::Hour, None);
512        let billing = figures
513            .rows
514            .iter()
515            .find(|row| row.of == RowOf::Module("Billing".to_owned()));
516        assert_eq!(
517            billing.and_then(|row| row.rates.under_95),
518            Some(Under::Bound(2.0))
519        );
520    }
521
522    #[test]
523    fn the_line_of_a_day_has_a_point_per_kept_step_and_breaks_at_a_gap() {
524        let app = shop();
525        let placing = Placing::new(&app, None);
526        let route = request("billing", "/billing/invoices");
527        let mut store = MetricsStore::new(PACE);
528        // A read every 15 s for 25 hours, one request each, with no read for 75 s after 5 hours
529        // and for 10 minutes after 10 hours. The newest read counts 3.
530        let newest = 90_000;
531        let mut count = 0.0;
532        for at in (0..=newest).step_by(15) {
533            if (18_015..18_090).contains(&at) || (36_015..36_600).contains(&at) {
534                continue;
535            }
536            count += if at == newest { 3.0 } else { 1.0 };
537            let cell = Cell {
538                count,
539                ..Cell::default()
540            };
541            store
542                .push(secs(at), reading(&[], vec![(route.clone(), cell)]))
543                .unwrap();
544        }
545
546        let billing = RowOf::Module("Billing".to_owned());
547        let figures = Figures::of(
548            &app,
549            &placing,
550            Scope::All,
551            &store,
552            Range::Day,
553            Some(&billing),
554        );
555        let line = &figures.total.line;
556        let agos = |ats: Vec<u64>| -> Vec<Duration> {
557            ats.into_iter().map(|at| secs(newest - at)).collect()
558        };
559        let runs: Vec<Vec<Duration>> = line
560            .runs
561            .iter()
562            .map(|run| run.iter().map(|point| point.ago).collect())
563            .collect();
564        // A point every 5 minutes before the last hour and every 15 s in it. The read after a
565        // gap starts a run, and gives no point. Thinning drops the read at 18,090 s, as 18,000 s
566        // holds its 5 minute step, and the line still breaks before 18,300 s.
567        assert_eq!(
568            runs,
569            [
570                agos((3_900..=18_000).step_by(300).collect()),
571                agos((18_600..=36_000).step_by(300).collect()),
572                agos(
573                    (36_900..=86_400)
574                        .step_by(300)
575                        .chain((86_415..=newest).step_by(15))
576                        .collect()
577                ),
578            ]
579        );
580        let rates: Vec<f64> = line
581            .runs
582            .iter()
583            .flatten()
584            .map(|point| point.per_minute)
585            .collect();
586        let (last, before) = rates.split_last().unwrap();
587        assert!(before.iter().all(|&rate| rate == 4.0));
588        assert_eq!(*last, 12.0);
589        assert_eq!(line.now(), Some(12.0));
590        // The column "Last hour" is the same line over 1 hour, whatever the range.
591        let hour: Vec<Point> = line.runs[2]
592            .iter()
593            .copied()
594            .filter(|point| point.ago < Range::Hour.span())
595            .collect();
596        assert_eq!(figures.total.last_hour.runs, [hour]);
597        // The selected row has its line over the range; another row has none.
598        assert_eq!(figures.rows[0].of, billing);
599        assert_eq!(figures.rows[0].line, *line);
600        assert_eq!(figures.rows[1].line, Line::default());
601        assert!(!figures.rows[1].last_hour.runs.is_empty());
602    }
603}