Skip to main content

mortise_core/metrics/
sample.rs

1//! The reads of the metrics, kept in memory.
2//!
3//! A kept read holds running totals per subject. A figure over a span is the newest totals minus the
4//! totals of the oldest kept read in the span, over the time covered between the two. So older reads
5//! can be thinned without changing a figure. The time is a parameter: the store never asks the clock.
6//! [`LiveMetrics`] holds the store of one environment and the clock of a real run.
7
8use std::borrow::Cow;
9use std::collections::hash_map::Entry;
10use std::collections::{HashMap, VecDeque};
11use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
12use std::time::{Duration, Instant, SystemTime};
13
14use crate::app::AppSnapshot;
15use crate::metrics::figures::{Figures, Range, RowOf, Scope};
16use crate::metrics::place::Placing;
17use crate::metrics::prometheus::{Part, samples, typed};
18use crate::runtime::actuator::{NoMetrics, Route};
19use crate::runtime::live::Pace;
20
21/// A read older than this is dropped.
22const WINDOW: Duration = Duration::from_secs(24 * 60 * 60);
23/// In this last part of the window, one read per pace is kept: the last of each step.
24const FINE: Duration = Duration::from_secs(60 * 60);
25/// Before the fine part, the first read of each step is kept.
26const STEP: Duration = Duration::from_secs(5 * 60);
27/// A read more than this many paces after the one before starts a new run.
28const GAP_PACES: u32 = 3;
29/// The families that [`Reading::of`] folds. Every other family is skipped.
30const REQUESTS: &str = "http_server_request_duration_seconds";
31const JOBS: &str = "messaging_process_duration_seconds";
32const DATABASE: &str = "db_client_operation_duration_seconds";
33/// `count`, `errors` and `sum` come before the buckets in a row.
34const FIXED: usize = 3;
35/// The most numbers one read keeps: `FIXED` and one per bound, for each series. A reading over it is
36/// refused. The 60 module app of design D1 keeps 660 × 17 = 11,220.
37const MAX_ROW: usize = 32_768;
38/// The most bytes of identity the store keeps: for each series, its labels and the strings of its
39/// subject. A reading over it is refused as one over `MAX_ROW` is.
40const MAX_KEY_BYTES: usize = 4 * 1024 * 1024;
41
42/// What a series is about, as the answer says it. Not a module.
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub(crate) enum Subject {
45    /// A request series. Statuses are added into one subject.
46    Request {
47        module: Option<String>,
48        route: Option<String>,
49        method: String,
50    },
51    /// A job series. `class` is empty when the series has no `laravel_job_name`.
52    Job {
53        module: Option<String>,
54        class: String,
55    },
56    /// Database time. Kept only for a series with a `module` label.
57    Database { module: String },
58}
59
60impl Subject {
61    /// The bytes its strings hold, spare room included.
62    #[cfg(test)]
63    fn held(&self) -> usize {
64        let held = |text: &Option<String>| text.as_ref().map_or(0, String::capacity);
65        match self {
66            Subject::Request {
67                module,
68                route,
69                method,
70            } => held(module) + held(route) + method.capacity(),
71            Subject::Job { module, class } => held(module) + class.capacity(),
72            Subject::Database { module } => module.capacity(),
73        }
74    }
75
76    /// The bytes of its strings.
77    fn bytes(&self) -> usize {
78        let len = |text: &Option<String>| text.as_deref().map_or(0, str::len);
79        match self {
80            Subject::Request {
81                module,
82                route,
83                method,
84            } => len(module) + len(route) + method.len(),
85            Subject::Job { module, class } => len(module) + class.len(),
86            Subject::Database { module } => module.len(),
87        }
88    }
89}
90
91/// The counters of one series, or what a subject grew by. All are counts or seconds, so all are
92/// `f64`. In a [`Reading`], a counter the answer did not give is NaN: it is absent.
93#[derive(Debug, Clone, PartialEq, Default)]
94pub(crate) struct Cell {
95    /// `_count`.
96    pub count: f64,
97    /// `_count` of a series with a 5xx status.
98    pub errors: f64,
99    /// `_sum`, in seconds.
100    pub sum: f64,
101    /// `_bucket` per finite bound. Requests only. In a [`Reading`], in the order of its bounds; in
102    /// a [`Change`], in the order of the bounds of the store, lowest first.
103    pub buckets: Vec<f64>,
104}
105
106/// One answer, folded. This is the interface between the parser and the store.
107#[derive(Debug, Clone, PartialEq, Default)]
108pub(crate) struct Reading {
109    /// The finite bucket bounds of the request histogram, in the order the answer gives them.
110    /// `-0` is `0`.
111    pub bounds: Vec<f64>,
112    /// The counters of each series, by subject and the labels of the series (see [`series_key`]).
113    pub series: HashMap<(Subject, String), Cell>,
114}
115
116impl Cell {
117    /// A cell of a reading before any line of its series: every counter is absent.
118    fn absent() -> Self {
119        Self {
120            count: f64::NAN,
121            errors: f64::NAN,
122            sum: f64::NAN,
123            buckets: Vec::new(),
124        }
125    }
126}
127
128/// A reading that would make a read keep more than `MAX_ROW` numbers or `MAX_KEY_BYTES` bytes.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub(crate) struct TooMany;
131
132/// The labels of a series, `le` aside, sorted by name: `name="value",` each, with the value escaped.
133/// Two lines of one series give one key, whatever order they write the labels in.
134fn series_key(labels: &mut [(&str, Cow<'_, str>)]) -> String {
135    use std::fmt::Write;
136    labels.sort_unstable_by_key(|(name, _)| *name);
137    let mut key = String::new();
138    for (name, value) in labels.iter() {
139        // Writing to a `String` does not fail.
140        let _ = write!(key, "{name}={value:?},");
141    }
142    key
143}
144
145/// `true` when `series` with `bounds` need more than `MAX_ROW` numbers, or their identity more than
146/// `MAX_KEY_BYTES` bytes.
147fn over(series: usize, bounds: usize, bytes: usize) -> bool {
148    series.saturating_mul(FIXED + bounds) > MAX_ROW || bytes > MAX_KEY_BYTES
149}
150
151/// Adds `value` to a counter of a reading. An absent counter starts at `value`.
152fn put(counter: &mut f64, value: f64) {
153    *counter = if counter.is_nan() {
154        value
155    } else {
156        *counter + value
157    };
158}
159
160impl Reading {
161    /// Folds an answer. Runs on the worker thread.
162    ///
163    /// A `+Inf` bucket is dropped: it equals the count. An empty `module` label counts as no label.
164    /// A counter with no line, as a `_sum` that could not be read, is absent (NaN).
165    /// An answer over `MAX_ROW` numbers or `MAX_KEY_BYTES` bytes is refused before the reading grows
166    /// past it.
167    pub(crate) fn of(text: &str) -> Result<Reading, TooMany> {
168        let mut reading = Reading::default();
169        let mut bytes = 0;
170        // The index of each bound in `reading.bounds`, by its bits. `0.0` and `-0.0` are one bound.
171        let mut bound_at: HashMap<u64, usize> = HashMap::new();
172        for mut sample in samples(text) {
173            let module = || {
174                sample
175                    .label("module")
176                    .filter(|module| !module.is_empty())
177                    .map(str::to_owned)
178            };
179            let folded = match (sample.family, sample.part) {
180                (REQUESTS, Part::Count | Part::Sum) => true,
181                (REQUESTS, Part::Bucket(bound)) => bound.is_finite(),
182                (JOBS, Part::Count) | (DATABASE, Part::Sum) => true,
183                _ => false,
184            };
185            if !folded {
186                continue;
187            }
188            let subject = match sample.family {
189                REQUESTS => Subject::Request {
190                    module: module(),
191                    route: sample.label("http_route").map(str::to_owned),
192                    method: sample
193                        .label("http_request_method")
194                        .unwrap_or_default()
195                        .to_owned(),
196                },
197                JOBS => Subject::Job {
198                    module: module(),
199                    class: sample
200                        .label("laravel_job_name")
201                        .unwrap_or_default()
202                        .to_owned(),
203                },
204                _ => match module() {
205                    Some(module) => Subject::Database { module },
206                    None => continue,
207                },
208            };
209            let error = sample
210                .label("http_response_status_code")
211                .and_then(|status| status.parse::<u16>().ok())
212                .is_some_and(|status| (500..600).contains(&status));
213            let key = series_key(&mut sample.labels);
214            let size = subject.bytes() + key.len();
215            let mut series = reading.series.len();
216            let cell = match reading.series.entry((subject, key)) {
217                Entry::Occupied(cell) => cell.into_mut(),
218                Entry::Vacant(cell) => {
219                    series += 1;
220                    bytes += size;
221                    if over(series, reading.bounds.len(), bytes) {
222                        return Err(TooMany);
223                    }
224                    cell.insert(Cell::absent())
225                }
226            };
227            match sample.part {
228                Part::Count => {
229                    put(&mut cell.count, sample.value);
230                    put(&mut cell.errors, if error { sample.value } else { 0.0 });
231                }
232                Part::Sum => put(&mut cell.sum, sample.value),
233                Part::Bucket(bound) => {
234                    let bound = if bound == 0.0 { 0.0 } else { bound };
235                    let bits = bound.to_bits();
236                    let at = match bound_at.get(&bits) {
237                        Some(&at) => at,
238                        None => {
239                            if over(series, reading.bounds.len() + 1, bytes) {
240                                return Err(TooMany);
241                            }
242                            reading.bounds.push(bound);
243                            bound_at.insert(bits, reading.bounds.len() - 1);
244                            reading.bounds.len() - 1
245                        }
246                    };
247                    if cell.buckets.len() <= at {
248                        cell.buckets.resize(at + 1, f64::NAN);
249                    }
250                    put(&mut cell.buckets[at], sample.value);
251                }
252                Part::Value => {}
253            }
254        }
255        Ok(reading)
256    }
257}
258
259/// What changed over a span.
260#[derive(Debug)]
261pub(crate) struct Change<'a> {
262    /// The time between reads that the span covers. Never zero.
263    pub covered: Duration,
264    /// The bounds of the store, lowest first. Each cell has one bucket per bound.
265    pub bounds: &'a [f64],
266    /// Every kept subject with what it grew by. Zero is included. Each cell has one bucket per bound
267    /// of the store.
268    pub cells: Vec<(&'a Subject, Cell)>,
269}
270
271/// What changed between two neighbouring kept reads: one point of a line.
272#[derive(Debug, Clone, PartialEq)]
273pub(crate) struct Step {
274    /// The time of the later read.
275    pub at: Duration,
276    /// The covered time between the two reads. Never zero.
277    pub covered: Duration,
278    /// What the request count of each kept subject grew by, in the order of `Change::cells`.
279    pub counts: Vec<f64>,
280    /// `true` for the first step, and for a step after a pair that is no step: a new run of the line.
281    pub starts: bool,
282}
283
284/// One kept read.
285#[derive(Debug)]
286struct Read {
287    at: Duration,
288    /// The time covered by runs so far. It does not grow over a gap.
289    covered: Duration,
290    /// `true` for the first read of a run.
291    starts_run: bool,
292    /// The number of the run of this read.
293    run: u64,
294    /// The running totals, one row of `FIXED + bounds` numbers per subject, in the order of the
295    /// columns. A subject that was not known yet has no row here, which reads as zero.
296    totals: Vec<f64>,
297}
298
299impl Read {
300    fn total(&self, at: usize) -> f64 {
301        self.totals.get(at).copied().unwrap_or(0.0)
302    }
303}
304
305/// The counters of one series at the last read that held it.
306#[derive(Debug)]
307struct Base {
308    /// A counter that is not known is NaN: it was absent, or absent when the base was last set
309    /// over a reset.
310    counters: Vec<f64>,
311    /// The run of that read. A base of an older run is stale: the series was missing when the run
312    /// started, so what it grew by in the gap is not known.
313    run: u64,
314    /// The time of that read.
315    seen: Duration,
316}
317
318/// One kept subject.
319#[derive(Debug)]
320struct Column {
321    subject: Subject,
322    /// The base of each series of the subject, by its labels.
323    bases: HashMap<String, Base>,
324}
325
326/// The reads of one environment over the last 24 hours, thinned.
327#[derive(Debug)]
328pub(crate) struct MetricsStore {
329    every: Duration,
330    bounds: Vec<f64>,
331    /// For each bound, the time of the newest read whose reading gave it.
332    bound_seen: Vec<Duration>,
333    columns: Vec<Column>,
334    index: HashMap<Subject, usize>,
335    /// The number of the current run. It goes up at the first read of each run.
336    run: u64,
337    /// Reads older than the fine part, the first of each step, oldest first.
338    coarse: VecDeque<Read>,
339    /// Reads of the fine part, the last of each pace, oldest first. The newest read is the last,
340    /// until a read after a gap of more than the fine part moves it to `coarse`.
341    fine: VecDeque<Read>,
342    /// The time of the newest read and the time covered by then. Kept apart from the queues, as
343    /// thinning can move every read out of the fine part.
344    latest: Option<(Duration, Duration)>,
345    /// The running totals of the newest read, kept apart for the same reason. The next read
346    /// carries on from them.
347    totals: Vec<f64>,
348    /// The counters of the series being pushed, kept to save an allocation per series.
349    scratch: Vec<f64>,
350}
351
352impl MetricsStore {
353    /// `every` is the pace of the reads. A gap is longer than 3 times it.
354    pub(crate) fn new(every: Duration) -> Self {
355        Self {
356            every,
357            bounds: Vec::new(),
358            bound_seen: Vec::new(),
359            columns: Vec::new(),
360            index: HashMap::new(),
361            run: 0,
362            coarse: VecDeque::new(),
363            fine: VecDeque::new(),
364            latest: None,
365            totals: Vec::new(),
366            scratch: Vec::new(),
367        }
368    }
369
370    /// Adds a read taken at `at`, a time since any fixed start.
371    ///
372    /// What `at` makes too old is dropped first. Then a reading that would make the store keep more
373    /// than `MAX_ROW` numbers per read or `MAX_KEY_BYTES` bytes, counting every series of the kept
374    /// reads and every bound of the store and of the reading, is refused as a whole and adds
375    /// nothing.
376    pub(crate) fn push(&mut self, at: Duration, reading: Reading) -> Result<(), TooMany> {
377        if self.latest.is_some_and(|(newest, _)| at <= newest) {
378            return Ok(());
379        }
380        self.expire(at);
381        let Reading { bounds, series } = reading;
382        // The bounds of the reading that the store does not hold yet.
383        let mut added: Vec<f64> = bounds
384            .iter()
385            .copied()
386            .filter(|&bound| self.bucket(bound).is_none())
387            .collect();
388        added.sort_by(f64::total_cmp);
389        added.dedup();
390        let (mut kept, mut bytes) = self.retained();
391        for (subject, labels) in series.keys() {
392            if !self.holds(subject, labels) {
393                kept += 1;
394                bytes += subject.bytes() + labels.len();
395            }
396        }
397        if over(kept, self.bounds.len() + added.len(), bytes) {
398            return Err(TooMany);
399        }
400        if !added.is_empty() {
401            self.widen(&added);
402        }
403        // The bucket of the store for each bound of the reading: buckets match by bound, not by
404        // place.
405        let places: Vec<Option<usize>> = bounds.iter().map(|&bound| self.bucket(bound)).collect();
406        for &place in places.iter().flatten() {
407            self.bound_seen[place] = at;
408        }
409        let first = self
410            .latest
411            .is_none_or(|(before, _)| at - before > self.every * GAP_PACES);
412        let covered = match self.latest {
413            Some((before, covered)) if !first => covered + (at - before),
414            Some((_, covered)) => covered,
415            None => Duration::ZERO,
416        };
417        // One read per pace in the fine part: a read in the step of the one before takes its place.
418        // Totals only grow, so the dropped read is not needed for a figure. A read that starts a
419        // run is never replaced: the second read of a run always gives a rate.
420        let replaces = self
421            .fine
422            .back()
423            .is_some_and(|before| !before.starts_run && self.step(before.at) == self.step(at));
424        if first {
425            self.run += 1;
426        }
427        let run = self.run;
428        let width = self.width();
429        let mut counters = std::mem::take(&mut self.scratch);
430        // Each series is compared with its own base, then what it grew by adds into its subject.
431        for ((subject, labels), cell) in series {
432            if !fill(&cell, &places, self.bounds.len(), &mut counters) {
433                continue;
434            }
435            let column = self.column(subject);
436            let row = column * width..(column + 1) * width;
437            if self.totals.len() < row.end {
438                self.totals.resize(row.end, 0.0);
439            }
440            let totals = &mut self.totals[row];
441            let bases = &mut self.columns[column].bases;
442            match bases.get_mut(&labels) {
443                Some(base) => {
444                    // Only counters known in both reads are compared and added.
445                    let reset = counters
446                        .iter()
447                        .zip(&base.counters)
448                        .any(|(now, base)| now < base);
449                    // A stale base and a reset add nothing, and every counter is set. On the first
450                    // read of a run, every base is stale.
451                    if base.run == run && !reset {
452                        add(
453                            totals,
454                            counters
455                                .iter()
456                                .zip(&base.counters)
457                                .map(|(now, base)| or_zero(now - base)),
458                        );
459                        // An absent counter keeps its base.
460                        for (base, now) in base.counters.iter_mut().zip(&counters) {
461                            if !now.is_nan() {
462                                *base = *now;
463                            }
464                        }
465                    } else {
466                        base.counters.copy_from_slice(&counters);
467                    }
468                    base.run = run;
469                    base.seen = at;
470                }
471                None => {
472                    // A new series counts from zero, except on the first read of a run.
473                    if !first {
474                        add(totals, counters.iter().copied().map(or_zero));
475                    }
476                    bases.insert(
477                        labels,
478                        Base {
479                            counters: counters.clone(),
480                            run,
481                            seen: at,
482                        },
483                    );
484                }
485            }
486        }
487        self.scratch = counters;
488        let mut totals = if replaces {
489            self.fine.pop_back().map(|read| read.totals)
490        } else {
491            None
492        }
493        .unwrap_or_default();
494        totals.clone_from(&self.totals);
495        self.fine.push_back(Read {
496            at,
497            covered,
498            starts_run: first,
499            run,
500            totals,
501        });
502        self.latest = Some((at, covered));
503        Ok(())
504    }
505
506    /// `true` when a read taken at `now` would not start a run: the newest kept read is at most a
507    /// gap older. Before that, its rates are not the rates of now.
508    fn fresh(&self, now: Duration) -> bool {
509        self.latest
510            .is_some_and(|(newest, _)| now.saturating_sub(newest) <= self.every * GAP_PACES)
511    }
512
513    /// The bucket of `bound` in a row, after the fixed numbers.
514    fn bucket(&self, bound: f64) -> Option<usize> {
515        self.bounds
516            .binary_search_by(|kept| kept.total_cmp(&bound))
517            .ok()
518    }
519
520    /// `true` when a base of the series is kept.
521    fn holds(&self, subject: &Subject, labels: &str) -> bool {
522        self.index
523            .get(subject)
524            .is_some_and(|&column| self.columns[column].bases.contains_key(labels))
525    }
526
527    /// The series the store keeps, and the bytes of their identity: per series, its labels and
528    /// the strings of its subject.
529    fn retained(&self) -> (usize, usize) {
530        self.columns.iter().fold((0, 0), |(series, bytes), column| {
531            let labels: usize = column.bases.keys().map(String::len).sum();
532            (
533                series + column.bases.len(),
534                bytes + column.bases.len() * column.subject.bytes() + labels,
535            )
536        })
537    }
538
539    /// How many reads are kept.
540    #[cfg(test)]
541    pub(crate) fn len(&self) -> usize {
542        self.coarse.len() + self.fine.len()
543    }
544
545    /// The bytes of heap the store owns, by capacity, so slack from growth counts. A lower bound of
546    /// the real heap: what the allocator adds is not seen.
547    #[cfg(test)]
548    fn bytes_held(&self) -> usize {
549        let numbers = |values: &Vec<f64>| values.capacity() * size_of::<f64>();
550        let reads = |reads: &VecDeque<Read>| {
551            reads.capacity() * size_of::<Read>()
552                + reads
553                    .iter()
554                    .map(|read| numbers(&read.totals))
555                    .sum::<usize>()
556        };
557        let columns: usize = self
558            .columns
559            .iter()
560            .map(|column| {
561                let bases: usize = column
562                    .bases
563                    .iter()
564                    .map(|(labels, base)| labels.capacity() + numbers(&base.counters))
565                    .sum();
566                column.subject.held()
567                    + column.bases.capacity() * size_of::<(String, Base)>()
568                    + bases
569            })
570            .sum();
571        let index: usize = self.index.keys().map(Subject::held).sum();
572        numbers(&self.bounds)
573            + self.bound_seen.capacity() * size_of::<Duration>()
574            + self.columns.capacity() * size_of::<Column>()
575            + columns
576            + self.index.capacity() * size_of::<(Subject, usize)>()
577            + index
578            + reads(&self.coarse)
579            + reads(&self.fine)
580            + numbers(&self.totals)
581            + numbers(&self.scratch)
582    }
583
584    /// The kept reads from the oldest at most `span` before the newest, to the newest, oldest
585    /// first. Empty with no read.
586    fn since(&self, span: Duration) -> impl Iterator<Item = &Read> {
587        let from = self
588            .fine
589            .back()
590            .map_or(Duration::ZERO, |newest| newest.at.saturating_sub(span));
591        let coarse = self.coarse.partition_point(|read| read.at < from);
592        let fine = if coarse < self.coarse.len() {
593            0
594        } else {
595            self.fine.partition_point(|read| read.at < from)
596        };
597        self.coarse.range(coarse..).chain(self.fine.range(fine..))
598    }
599
600    /// The newest read against the oldest kept read at most `span` before it.
601    /// `None` when no time is covered between them, or when the newest read starts a run.
602    pub(crate) fn change(&self, span: Duration) -> Option<Change<'_>> {
603        let newest = self.fine.back()?;
604        if newest.starts_run {
605            return None;
606        }
607        let oldest = self.since(span).next()?;
608        let covered = newest
609            .covered
610            .checked_sub(oldest.covered)
611            .filter(|covered| !covered.is_zero())?;
612        let width = self.width();
613        let grew = |at: usize| newest.total(at) - oldest.total(at);
614        let cells = self
615            .columns
616            .iter()
617            .enumerate()
618            .map(|(column, kept)| {
619                let start = column * width;
620                let cell = Cell {
621                    count: grew(start),
622                    errors: grew(start + 1),
623                    sum: grew(start + 2),
624                    buckets: (start + FIXED..start + width).map(grew).collect(),
625                };
626                (&kept.subject, cell)
627            })
628            .collect();
629        Some(Change {
630            covered,
631            bounds: &self.bounds,
632            cells,
633        })
634    }
635
636    /// The steps between neighbouring kept reads from the oldest read that `change(span)` uses to
637    /// the newest. A pair whose two reads are of different runs, or that covers no time, is no step.
638    /// Thinning can drop the first read of a run, so the run number tells a gap, not `starts_run`.
639    pub(crate) fn steps(&self, span: Duration) -> Vec<Step> {
640        let width = self.width();
641        let mut steps = Vec::new();
642        let mut starts = true;
643        let mut reads = self.since(span);
644        let Some(mut before) = reads.next() else {
645            return steps;
646        };
647        for read in reads {
648            let covered = read.covered.saturating_sub(before.covered);
649            if read.run != before.run || covered.is_zero() {
650                starts = true;
651            } else {
652                let counts = (0..self.columns.len())
653                    .map(|column| read.total(column * width) - before.total(column * width))
654                    .collect();
655                steps.push(Step {
656                    at: read.at,
657                    covered,
658                    counts,
659                    starts,
660                });
661                starts = false;
662            }
663            before = read;
664        }
665        steps
666    }
667
668    /// Every kept subject, in the order of `Change::cells` and `Step::counts`.
669    pub(crate) fn subjects(&self) -> impl Iterator<Item = &Subject> {
670        self.columns.iter().map(|column| &column.subject)
671    }
672
673    /// The time of the newest read.
674    pub(crate) fn newest(&self) -> Option<Duration> {
675        self.latest.map(|(at, _)| at)
676    }
677
678    /// The numbers per subject in a row.
679    fn width(&self) -> usize {
680        FIXED + self.bounds.len()
681    }
682
683    /// The step of the fine part that `at` falls in: one per pace.
684    fn step(&self, at: Duration) -> u128 {
685        at.as_nanos()
686            .checked_div(self.every.as_nanos())
687            .unwrap_or(at.as_nanos())
688    }
689
690    /// Adds bounds the store does not hold, each in its place. Every row gets a zero bucket for
691    /// each, and every base an unknown one, so a subject read before them keeps its totals. Jobs
692    /// and database time come before the first request in a quiet app.
693    fn widen(&mut self, added: &[f64]) {
694        let narrow = self.width();
695        let mut bounds = self.bounds.clone();
696        bounds.extend_from_slice(added);
697        bounds.sort_by(f64::total_cmp);
698        let width = FIXED + bounds.len();
699        // Where each kept bucket goes.
700        let places: Vec<usize> = self
701            .bounds
702            .iter()
703            .map(|bound| bounds.partition_point(|wide| wide.total_cmp(bound).is_lt()))
704            .collect();
705        let spread = |row: &[f64], new: f64, into: &mut Vec<f64>| {
706            let start = into.len();
707            into.extend_from_slice(&row[..FIXED]);
708            into.resize(start + width, new);
709            for (value, place) in row[FIXED..].iter().zip(&places) {
710                into[start + FIXED + place] = *value;
711            }
712        };
713        for totals in self.all_totals() {
714            let mut wide = Vec::with_capacity(totals.len() / narrow * width);
715            for row in totals.chunks(narrow) {
716                spread(row, 0.0, &mut wide);
717            }
718            *totals = wide;
719        }
720        for base in self
721            .columns
722            .iter_mut()
723            .flat_map(|column| column.bases.values_mut())
724        {
725            let mut wide = Vec::with_capacity(width);
726            spread(&base.counters, f64::NAN, &mut wide);
727            base.counters = wide;
728        }
729        // An added bound is seen by the push that adds it.
730        let mut seen = vec![Duration::ZERO; bounds.len()];
731        for (&at, &place) in self.bound_seen.iter().zip(&places) {
732            seen[place] = at;
733        }
734        self.bounds = bounds;
735        self.bound_seen = seen;
736    }
737
738    /// The totals of each kept read, and the running totals.
739    fn all_totals(&mut self) -> impl Iterator<Item = &mut Vec<f64>> {
740        self.coarse
741            .iter_mut()
742            .chain(self.fine.iter_mut())
743            .map(|read| &mut read.totals)
744            .chain(std::iter::once(&mut self.totals))
745    }
746
747    /// The column of a subject. A new subject gets a new column, with no base.
748    fn column(&mut self, subject: Subject) -> usize {
749        if let Some(&column) = self.index.get(&subject) {
750            return column;
751        }
752        let column = self.columns.len();
753        self.index.insert(subject.clone(), column);
754        self.columns.push(Column {
755            subject,
756            bases: HashMap::new(),
757        });
758        column
759    }
760
761    /// Drops what a read at `newest`, later than every kept read, makes too old: reads, then the
762    /// series and the subjects that no kept read holds.
763    fn expire(&mut self, newest: Duration) {
764        self.thin(newest);
765        let oldest = self
766            .coarse
767            .front()
768            .or(self.fine.front())
769            .map_or(newest, |read| read.at);
770        self.drop_gone(oldest);
771        self.drop_bounds(oldest);
772    }
773
774    /// Moves reads out of the fine part, keeping the first of each step, and drops what is too old.
775    fn thin(&mut self, newest: Duration) {
776        let step = |at: Duration| at.as_secs() / STEP.as_secs();
777        while let Some(read) = self.fine.pop_front_if(|read| newest - read.at > FINE) {
778            if self
779                .coarse
780                .back()
781                .is_none_or(|last| step(last.at) != step(read.at))
782            {
783                self.coarse.push_back(read);
784            }
785        }
786        while self
787            .coarse
788            .pop_front_if(|read| newest - read.at > WINDOW)
789            .is_some()
790        {}
791    }
792
793    /// Drops the series last held by a read before `oldest`, the subjects left with none, and packs
794    /// the rows.
795    ///
796    /// Such a subject did not change in the kept window and is not in the newest read.
797    /// One that is in an older kept read stays, so it keeps its base (a load balancer can show
798    /// one server per read).
799    fn drop_gone(&mut self, oldest: Duration) {
800        for column in &mut self.columns {
801            column.bases.retain(|_, base| base.seen >= oldest);
802        }
803        let keep: Vec<bool> = self
804            .columns
805            .iter()
806            .map(|kept| !kept.bases.is_empty())
807            .collect();
808        if keep.iter().all(|&keep| keep) {
809            return;
810        }
811        let width = self.width();
812        for totals in self.all_totals() {
813            let rows = totals.len() / width;
814            let mut packed = 0;
815            for (column, _) in keep
816                .iter()
817                .enumerate()
818                .take(rows)
819                .filter(|(_, keep)| **keep)
820            {
821                let start = column * width;
822                totals.copy_within(start..start + width, packed * width);
823                packed += 1;
824            }
825            totals.truncate(packed * width);
826        }
827        let mut keep = keep.into_iter();
828        self.columns.retain(|_| keep.next() == Some(true));
829        self.index = self
830            .columns
831            .iter()
832            .enumerate()
833            .map(|(column, kept)| (kept.subject.clone(), column))
834            .collect();
835    }
836
837    /// Drops the bounds that no reading gave since `oldest`, and their bucket in every row and
838    /// every base.
839    ///
840    /// Such a bucket did not grow between any two kept reads, so no figure needs it. A base holds
841    /// its value from a read no newer than the last that gave the bound, so from before the kept
842    /// window, as a dropped series does. If the bound comes back, it widens the store again and
843    /// counts from that read.
844    fn drop_bounds(&mut self, oldest: Duration) {
845        let keep: Vec<bool> = self.bound_seen.iter().map(|&seen| seen >= oldest).collect();
846        if keep.iter().all(|&keep| keep) {
847            return;
848        }
849        let width = self.width();
850        let pack = |row: &[f64], into: &mut Vec<f64>| {
851            into.extend_from_slice(&row[..FIXED]);
852            into.extend(
853                row[FIXED..]
854                    .iter()
855                    .zip(&keep)
856                    .filter(|(_, keep)| **keep)
857                    .map(|(value, _)| *value),
858            );
859        };
860        for totals in self.all_totals() {
861            let mut narrow = Vec::with_capacity(totals.len());
862            for row in totals.chunks(width) {
863                pack(row, &mut narrow);
864            }
865            *totals = narrow;
866        }
867        for base in self
868            .columns
869            .iter_mut()
870            .flat_map(|column| column.bases.values_mut())
871        {
872            let mut narrow = Vec::with_capacity(width);
873            pack(&base.counters, &mut narrow);
874            base.counters = narrow;
875        }
876        let mut kept = keep.iter();
877        self.bounds.retain(|_| kept.next() == Some(&true));
878        let mut kept = keep.iter();
879        self.bound_seen.retain(|_| kept.next() == Some(&true));
880    }
881}
882
883/// Writes the counters of `cell` into `into`, one bucket per bound of the store. `places` gives
884/// the bucket of the store for each bound of the reading. A counter that is missing, negative or
885/// not finite is absent: NaN. `errors` is absent with `count`.
886/// `false` when every counter is absent: the store then ignores the series.
887fn fill(cell: &Cell, places: &[Option<usize>], bounds: usize, into: &mut Vec<f64>) -> bool {
888    let known = |value: f64| {
889        if value.is_finite() && value >= 0.0 {
890            value
891        } else {
892            f64::NAN
893        }
894    };
895    let count = known(cell.count);
896    let errors = if count.is_nan() {
897        f64::NAN
898    } else {
899        known(cell.errors)
900    };
901    into.clear();
902    into.extend([count, errors, known(cell.sum)]);
903    into.resize(FIXED + bounds, f64::NAN);
904    for (&value, place) in cell.buckets.iter().zip(places) {
905        if let Some(place) = place {
906            into[FIXED + place] = known(value);
907        }
908    }
909    into.iter().any(|value| !value.is_nan())
910}
911
912/// An absent counter adds nothing.
913fn or_zero(value: f64) -> f64 {
914    if value.is_nan() { 0.0 } else { value }
915}
916
917fn add(totals: &mut [f64], by: impl Iterator<Item = f64>) {
918    for (total, by) in totals.iter_mut().zip(by) {
919        *total += by;
920    }
921}
922
923/// The clock of the reads: the time since any fixed start.
924pub type MetricsClock = Arc<dyn Fn() -> Duration + Send + Sync>;
925
926/// Why a read added nothing to the store.
927#[derive(Debug, Clone, PartialEq, Eq)]
928pub enum NotKept {
929    /// The app gave no metrics.
930    NoMetrics(NoMetrics),
931    /// The answer has no `# TYPE` line, so it is not metrics: a sign-in page served with 200, say.
932    NotMetrics,
933    /// The answer has more series, or longer labels, than a read keeps. `limit` is the most numbers
934    /// a read keeps.
935    TooManySeries { limit: usize },
936}
937
938impl From<TooMany> for NotKept {
939    fn from(TooMany: TooMany) -> Self {
940        NotKept::TooManySeries { limit: MAX_ROW }
941    }
942}
943
944/// What the reads of an environment gave so far.
945#[derive(Debug, Clone, PartialEq, Eq, Default)]
946pub struct MetricsState {
947    /// What the last read gave. `None` before the first read ends, and while the newest kept read
948    /// is older than a gap (3 paces): its rates are not the rates of now (design D9).
949    pub last: Option<Result<(), NotKept>>,
950    /// Goes up by one when a read ends.
951    pub serial: u64,
952    /// The time from the newest kept read to now, by the clock of the reads. `Some` exactly when
953    /// `last` is `Some(Ok(()))`.
954    pub ago: Option<Duration>,
955}
956
957/// The reads of one environment, shared between the worker and the interface.
958#[derive(Clone)]
959pub struct LiveMetrics {
960    shared: Arc<Mutex<(MetricsStore, MetricsState)>>,
961    clock: MetricsClock,
962}
963
964impl Default for LiveMetrics {
965    fn default() -> Self {
966        Self::new()
967    }
968}
969
970impl LiveMetrics {
971    /// Reads timed by the clock of a real run.
972    pub fn new() -> Self {
973        Self::with_clock(real_clock())
974    }
975
976    /// Reads timed by `clock`. Tests pass a clock that steps.
977    pub fn with_clock(clock: MetricsClock) -> Self {
978        let store = MetricsStore::new(Pace::default().metrics);
979        Self {
980            shared: Arc::new(Mutex::new((store, MetricsState::default()))),
981            clock,
982        }
983    }
984
985    /// For `LiveRuntime::open_with_metrics`. The text is folded before the lock is taken.
986    /// A read that gave no metrics, text that is not metrics, or too many series adds nothing to
987    /// the store.
988    pub fn sink(&self) -> impl FnMut(Result<String, NoMetrics>) + Send + 'static {
989        let metrics = self.clone();
990        move |answer| {
991            let at = (metrics.clock)();
992            let reading = answer.map_err(NotKept::NoMetrics).and_then(|text| {
993                if !typed(&text) {
994                    return Err(NotKept::NotMetrics);
995                }
996                Reading::of(&text).map_err(NotKept::from)
997            });
998            let mut shared = metrics.lock();
999            let last =
1000                reading.and_then(|reading| shared.0.push(at, reading).map_err(NotKept::from));
1001            shared.1.last = Some(last);
1002            shared.1.serial += 1;
1003        }
1004    }
1005
1006    pub fn state(&self) -> MetricsState {
1007        let now = (self.clock)();
1008        let shared = self.lock();
1009        let mut state = shared.1.clone();
1010        if state.last == Some(Ok(())) && !shared.0.fresh(now) {
1011            state.last = None;
1012        }
1013        if state.last == Some(Ok(())) {
1014            state.ago = shared.0.newest().map(|newest| now.saturating_sub(newest));
1015        }
1016        state
1017    }
1018
1019    /// The figures of `scope` over `range`, placed by `app` and `routes`.
1020    /// `routes` is `None` when `mappings` is not exposed. The line over the range is built for the
1021    /// total and the `selected` row only.
1022    pub fn figures(
1023        &self,
1024        app: &AppSnapshot,
1025        routes: Option<&[Route]>,
1026        scope: Scope<'_>,
1027        range: Range,
1028        selected: Option<&RowOf>,
1029    ) -> Figures {
1030        let placing = Placing::new(app, routes);
1031        let shared = self.lock();
1032        Figures::of(app, &placing, scope, &shared.0, range, selected)
1033    }
1034
1035    fn lock(&self) -> MutexGuard<'_, (MetricsStore, MetricsState)> {
1036        self.shared.lock().unwrap_or_else(PoisonError::into_inner)
1037    }
1038}
1039
1040/// The clock of a real run: `Instant` since the start, plus the time the computer slept.
1041///
1042/// `Instant` does not move while macOS or Linux sleep. So each call compares it with the wall clock
1043/// and keeps the time the wall clock ran ahead. The result never goes back.
1044fn real_clock() -> MetricsClock {
1045    let start = Instant::now();
1046    let last = Mutex::new((Duration::ZERO, SystemTime::now(), Duration::ZERO));
1047    Arc::new(move || {
1048        let mut last = last.lock().unwrap_or_else(PoisonError::into_inner);
1049        let (instant, wall, offset) = *last;
1050        let (instant_now, wall_now) = (start.elapsed(), SystemTime::now());
1051        let offset = ahead(
1052            offset,
1053            instant_now.saturating_sub(instant),
1054            wall_now.duration_since(wall).unwrap_or_default(),
1055        );
1056        *last = (instant_now, wall_now, offset);
1057        instant_now + offset
1058    })
1059}
1060
1061/// The offset of the real clock after a call. It grows by the time the wall clock ran further than
1062/// `Instant` since the call before. A wall clock that was set back ran zero, so it never shrinks.
1063fn ahead(offset: Duration, instant_ran: Duration, wall_ran: Duration) -> Duration {
1064    offset + wall_ran.saturating_sub(instant_ran)
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069    use std::time::Instant;
1070
1071    use super::*;
1072
1073    const PACE: Duration = Duration::from_secs(15);
1074
1075    fn secs(seconds: u64) -> Duration {
1076        Duration::from_secs(seconds)
1077    }
1078
1079    fn route(path: &str) -> Subject {
1080        Subject::Request {
1081            module: None,
1082            route: Some(path.to_owned()),
1083            method: "GET".to_owned(),
1084        }
1085    }
1086
1087    fn count(count: f64) -> Cell {
1088        Cell {
1089            count,
1090            ..Cell::default()
1091        }
1092    }
1093
1094    /// A reading with one series per subject, with no label.
1095    fn reading(cells: &[(Subject, Cell)]) -> Reading {
1096        Reading {
1097            bounds: Vec::new(),
1098            series: cells
1099                .iter()
1100                .map(|(subject, cell)| ((subject.clone(), String::new()), cell.clone()))
1101                .collect(),
1102        }
1103    }
1104
1105    /// What `subject` grew by over `span`.
1106    fn grew(store: &MetricsStore, span: Duration, subject: &Subject) -> Option<Cell> {
1107        let change = store.change(span)?;
1108        change
1109            .cells
1110            .into_iter()
1111            .find(|(kept, _)| *kept == subject)
1112            .map(|(_, cell)| cell)
1113    }
1114
1115    #[test]
1116    fn the_first_read_gives_no_change() {
1117        let mut store = MetricsStore::new(PACE);
1118        store
1119            .push(secs(0), reading(&[(route("/"), count(7.0))]))
1120            .unwrap();
1121        store
1122            .push(secs(0), reading(&[(route("/"), count(9.0))]))
1123            .unwrap();
1124
1125        assert_eq!(store.len(), 1);
1126        assert!(store.change(WINDOW).is_none());
1127    }
1128
1129    #[test]
1130    fn a_reset_adds_nothing_and_the_next_read_counts() {
1131        let cell = |count, sum| Cell {
1132            count,
1133            sum,
1134            ..Cell::default()
1135        };
1136        let mut store = MetricsStore::new(PACE);
1137        store
1138            .push(secs(0), reading(&[(route("/"), cell(100.0, 50.0))]))
1139            .unwrap();
1140        store
1141            .push(secs(15), reading(&[(route("/"), cell(3.0, 1.0))]))
1142            .unwrap();
1143        assert_eq!(grew(&store, PACE, &route("/")), Some(cell(0.0, 0.0)));
1144
1145        store
1146            .push(secs(30), reading(&[(route("/"), cell(5.0, 2.0))]))
1147            .unwrap();
1148        assert_eq!(grew(&store, PACE, &route("/")), Some(cell(2.0, 1.0)));
1149        assert_eq!(grew(&store, WINDOW, &route("/")), Some(cell(2.0, 1.0)));
1150
1151        // Each label set is a series of its own: a reset on http does not hide the growth on https,
1152        // in whatever order a read writes the labels.
1153        let schemes = |http, https, labels: [&str; 2]| {
1154            let [first, second] = labels;
1155            Reading::of(&format!(
1156                "# TYPE {REQUESTS} histogram\n\
1157                 {REQUESTS}_count{{http_request_method=\"GET\",{first},{second}}} {https}\n\
1158                 {REQUESTS}_count{{http_request_method=\"GET\",http_route=\"/\",url_scheme=\"http\"}} {http}\n"
1159            ))
1160            .unwrap()
1161        };
1162        let https = ["http_route=\"/\"", "url_scheme=\"https\""];
1163        let [route_label, scheme_label] = https;
1164        let mut store = MetricsStore::new(PACE);
1165        store.push(secs(0), schemes(100, 100, https)).unwrap();
1166        store
1167            .push(secs(15), schemes(1, 110, [scheme_label, route_label]))
1168            .unwrap();
1169        assert_eq!(grew(&store, PACE, &route("/")), Some(count(10.0)));
1170
1171        // A counter missing from a read adds nothing and keeps its base. It is no reset: the count
1172        // still adds what it grew by.
1173        let timed = |count: u32, sum: Option<f64>| {
1174            let labels = "{http_request_method=\"GET\",http_route=\"/\"}";
1175            let mut text =
1176                format!("# TYPE {REQUESTS} histogram\n{REQUESTS}_count{labels} {count}\n");
1177            if let Some(sum) = sum {
1178                text.push_str(&format!("{REQUESTS}_sum{labels} {sum}\n"));
1179            }
1180            Reading::of(&text).unwrap()
1181        };
1182        let mut store = MetricsStore::new(PACE);
1183        store.push(secs(0), timed(10, Some(5.0))).unwrap();
1184        store.push(secs(15), timed(12, None)).unwrap();
1185        assert_eq!(grew(&store, PACE, &route("/")), Some(cell(2.0, 0.0)));
1186        store.push(secs(30), timed(14, Some(7.0))).unwrap();
1187        assert_eq!(grew(&store, WINDOW, &route("/")), Some(cell(4.0, 2.0)));
1188    }
1189
1190    #[test]
1191    fn a_subject_that_appears_in_a_run_counts_from_zero() {
1192        let failing = Cell {
1193            count: 4.0,
1194            errors: 1.0,
1195            sum: 0.5,
1196            buckets: Vec::new(),
1197        };
1198        let mut store = MetricsStore::new(PACE);
1199        store
1200            .push(secs(0), reading(&[(route("/"), count(10.0))]))
1201            .unwrap();
1202        store
1203            .push(
1204                secs(15),
1205                reading(&[(route("/"), count(10.0)), (route("/pay"), failing.clone())]),
1206            )
1207            .unwrap();
1208
1209        assert_eq!(grew(&store, WINDOW, &route("/pay")), Some(failing));
1210    }
1211
1212    #[test]
1213    fn a_missing_subject_keeps_its_totals_and_its_base() {
1214        let mut store = MetricsStore::new(PACE);
1215        store
1216            .push(secs(0), reading(&[(route("/"), count(10.0))]))
1217            .unwrap();
1218        store
1219            .push(secs(15), reading(&[(route("/"), count(15.0))]))
1220            .unwrap();
1221        store.push(secs(30), reading(&[])).unwrap();
1222        assert_eq!(grew(&store, WINDOW, &route("/")), Some(count(5.0)));
1223
1224        // A negative counter is ignored, as if the subject were missing.
1225        store
1226            .push(secs(45), reading(&[(route("/"), count(-1.0))]))
1227            .unwrap();
1228        store
1229            .push(secs(60), reading(&[(route("/"), count(18.0))]))
1230            .unwrap();
1231        assert_eq!(grew(&store, WINDOW, &route("/")), Some(count(8.0)));
1232    }
1233
1234    #[test]
1235    fn a_read_after_a_gap_starts_a_new_run() {
1236        let both = |home, blog| reading(&[(route("/"), count(home)), (route("/b"), count(blog))]);
1237        let mut store = MetricsStore::new(PACE);
1238        store.push(secs(0), both(10.0, 1.0)).unwrap();
1239        store.push(secs(15), both(12.0, 2.0)).unwrap();
1240        // The first read after a gap gives no rate, though the span reaches into the run before.
1241        store
1242            .push(secs(61), reading(&[(route("/"), count(20.0))]))
1243            .unwrap();
1244        assert!(store.change(WINDOW).is_none());
1245
1246        // `/b` was missing when the run started, so its return adds nothing.
1247        store.push(secs(76), both(25.0, 50.0)).unwrap();
1248        let change = store.change(WINDOW).expect("a change");
1249        assert_eq!(change.covered, secs(30));
1250        assert_eq!(grew(&store, WINDOW, &route("/")), Some(count(7.0)));
1251        assert_eq!(grew(&store, WINDOW, &route("/b")), Some(count(1.0)));
1252
1253        store.push(secs(91), both(25.0, 53.0)).unwrap();
1254        assert_eq!(grew(&store, PACE, &route("/b")), Some(count(3.0)));
1255
1256        // A gap longer than the fine part moves every read to the coarse part. The run after it
1257        // carries on from the totals and the covered time of the read before.
1258        let mut store = MetricsStore::new(PACE);
1259        for (at, total) in [(285, 1.0), (300, 3.0), (4_000, 100.0), (4_005, 104.0)] {
1260            store
1261                .push(secs(at), reading(&[(route("/"), count(total))]))
1262                .unwrap();
1263        }
1264        let change = store.change(secs(3_710)).expect("a change");
1265        assert_eq!(change.covered, secs(5));
1266        assert_eq!(change.cells, vec![(&route("/"), count(4.0))]);
1267        assert_eq!(grew(&store, WINDOW, &route("/")), Some(count(6.0)));
1268    }
1269
1270    #[test]
1271    fn a_rate_divides_by_the_covered_time() {
1272        let mut store = MetricsStore::new(PACE);
1273        for (at, total) in [(0, 0.0), (15, 6.0), (100, 50.0), (115, 56.0)] {
1274            store
1275                .push(secs(at), reading(&[(route("/"), count(total))]))
1276                .unwrap();
1277        }
1278
1279        let change = store.change(WINDOW).expect("a change");
1280        assert_eq!(change.covered, secs(30));
1281        assert_eq!(change.cells[0].1.count / change.covered.as_secs_f64(), 0.4);
1282    }
1283
1284    #[test]
1285    fn buckets_match_by_bound_and_new_bounds_widen_the_store() {
1286        let request = |count: f64, buckets: Vec<f64>| Cell {
1287            count,
1288            buckets,
1289            ..Cell::default()
1290        };
1291        let job = Subject::Job {
1292            module: None,
1293            class: String::new(),
1294        };
1295        let with_bounds = |bounds: Vec<f64>, cell: Cell| Reading {
1296            bounds,
1297            series: HashMap::from([((route("/"), String::new()), cell)]),
1298        };
1299        let mut store = MetricsStore::new(PACE);
1300        // A job comes before the first request, so before the first bounds.
1301        store
1302            .push(secs(0), reading(&[(job.clone(), count(1.0))]))
1303            .unwrap();
1304        store
1305            .push(
1306                secs(15),
1307                with_bounds(vec![0.1, 1.0], request(2.0, vec![1.0, 2.0])),
1308            )
1309            .unwrap();
1310        store
1311            .push(
1312                secs(30),
1313                with_bounds(vec![0.1, 1.0], request(4.0, vec![2.0, 4.0])),
1314            )
1315            .unwrap();
1316        store
1317            .push(secs(45), reading(&[(job.clone(), count(3.0))]))
1318            .unwrap();
1319        assert_eq!(store.len(), 4);
1320        assert_eq!(
1321            grew(&store, WINDOW, &route("/")),
1322            Some(request(4.0, vec![2.0, 4.0]))
1323        );
1324        assert_eq!(grew(&store, WINDOW, &job).map(|cell| cell.count), Some(2.0));
1325
1326        // The same bounds in another order.
1327        store
1328            .push(
1329                secs(60),
1330                with_bounds(vec![1.0, 0.1], request(5.0, vec![5.0, 3.0])),
1331            )
1332            .unwrap();
1333        assert_eq!(
1334            grew(&store, PACE, &route("/")),
1335            Some(request(1.0, vec![1.0, 1.0]))
1336        );
1337        // A bucket missing from a read adds nothing and keeps its base.
1338        store
1339            .push(secs(75), with_bounds(vec![1.0], request(6.0, vec![6.0])))
1340            .unwrap();
1341        assert_eq!(
1342            grew(&store, PACE, &route("/")),
1343            Some(request(1.0, vec![0.0, 1.0]))
1344        );
1345        // A new bound widens the store. Its bucket starts at the next read.
1346        store
1347            .push(
1348                secs(90),
1349                with_bounds(vec![0.1, 0.5, 1.0], request(7.0, vec![4.0, 5.0, 7.0])),
1350            )
1351            .unwrap();
1352        assert_eq!(store.bounds, [0.1, 0.5, 1.0]);
1353        assert_eq!(
1354            grew(&store, WINDOW, &route("/")),
1355            Some(request(7.0, vec![4.0, 0.0, 7.0]))
1356        );
1357        assert_eq!(grew(&store, WINDOW, &job).map(|cell| cell.count), Some(2.0));
1358
1359        // The app changes its bounds, in the next thinning step: the read at 300 s stays a day.
1360        // The old bounds go once no kept read gave them, though the route stays. So they no
1361        // longer count towards the caps.
1362        let two = |count: f64| with_bounds(vec![2.0], request(count, vec![count]));
1363        store.push(secs(300), two(8.0)).unwrap();
1364        store.push(secs(315), two(9.0)).unwrap();
1365        assert_eq!(store.bounds, [0.1, 0.5, 1.0, 2.0]);
1366        store.push(secs(91) + WINDOW, two(9.0)).unwrap();
1367        assert_eq!(store.bounds, [2.0]);
1368        // Every kept row lost the same buckets: from the read at 300 s, the route and its bucket
1369        // of 2 grew by what was pushed.
1370        store.push(secs(106) + WINDOW, two(10.0)).unwrap();
1371        assert_eq!(
1372            grew(&store, WINDOW, &route("/")),
1373            Some(request(2.0, vec![2.0]))
1374        );
1375    }
1376
1377    #[test]
1378    fn a_day_of_reads_is_thinned_and_keeps_its_figures() {
1379        let started = Instant::now();
1380        let gone = route("/old");
1381        let stays = |n: u64| (n % 5) as f64;
1382        let mut store = MetricsStore::new(PACE);
1383        let mut total = 0.0;
1384        let mut full = 0;
1385        for n in 0..7_000 {
1386            total += stays(n);
1387            // `/old` comes first, so dropping it moves the row of `/`.
1388            let mut cells = Vec::new();
1389            if n < 1_000 {
1390                cells.push((gone.clone(), count(n as f64)));
1391            }
1392            if n > 0 {
1393                cells.push((route("/"), count(total)));
1394            }
1395            store.push(PACE * n as u32, reading(&cells)).unwrap();
1396
1397            assert!(store.len() <= 520);
1398            match n + 1 {
1399                5_760 => full = store.len(),
1400                6_000 => assert!(grew(&store, WINDOW, &gone).is_some()),
1401                pushes if pushes > 5_760 => assert!(store.len() <= full),
1402                _ => {}
1403            }
1404        }
1405
1406        let change = store.change(WINDOW).expect("a change");
1407        // The span starts at a kept read at most a step inside it.
1408        assert!(change.covered >= WINDOW - STEP && change.covered <= WINDOW);
1409        let oldest = 6_999 - change.covered.as_secs() / PACE.as_secs();
1410        let pushed: f64 = (oldest + 1..7_000).map(stays).sum();
1411        assert_eq!(change.cells, vec![(&route("/"), count(pushed))]);
1412
1413        // "Try again" can read faster than the pace. Two hours of reads 1 s apart keep the bound,
1414        // and the figures.
1415        let burst = PACE * 7_000;
1416        for n in 0..7_200 {
1417            let reading = reading(&[(route("/"), count(total + n as f64))]);
1418            store.push(burst + secs(n), reading).unwrap();
1419            assert!(store.len() <= 520);
1420        }
1421        let change = store.change(secs(60)).expect("a change");
1422        assert_eq!(change.cells[0].1.count, change.covered.as_secs_f64());
1423
1424        // The read that starts a run is never replaced: after a gap, two reads 1 s apart, in one
1425        // step, give a rate.
1426        let after = burst + secs(7_300);
1427        for n in 0..2 {
1428            let reading = reading(&[(route("/"), count(total + 7_200.0 + n as f64))]);
1429            store.push(after + secs(n), reading).unwrap();
1430        }
1431        assert_eq!(
1432            store.change(secs(60)).map(|change| change.covered),
1433            Some(secs(1))
1434        );
1435        assert!(store.len() <= 520);
1436        assert!(started.elapsed() < secs(1), "took {:?}", started.elapsed());
1437    }
1438
1439    #[test]
1440    fn too_many_series_are_refused_as_a_whole() {
1441        let jobs = |range: std::ops::Range<usize>| {
1442            let mut text = format!("# TYPE {JOBS} histogram\n");
1443            for job in range {
1444                text.push_str(&format!("{JOBS}_count{{laravel_job_name=\"J{job}\"}} 1\n"));
1445            }
1446            text
1447        };
1448        // 3 numbers per job.
1449        let metrics = LiveMetrics::with_clock(Arc::new(|| Duration::ZERO));
1450        let mut sink = metrics.sink();
1451        sink(Ok(jobs(0..MAX_ROW / 3 + 1)));
1452        let too_many = Some(Err(NotKept::TooManySeries { limit: MAX_ROW }));
1453        assert_eq!(metrics.state().last, too_many);
1454        assert_eq!(metrics.lock().0.len(), 0);
1455
1456        // The store counts every series of its kept reads.
1457        let mut store = MetricsStore::new(PACE);
1458        let half = MAX_ROW / 6 + 1;
1459        store
1460            .push(secs(0), Reading::of(&jobs(0..half)).unwrap())
1461            .unwrap();
1462        let other = || Reading::of(&jobs(half..2 * half)).unwrap();
1463        assert_eq!(store.push(secs(15), other()), Err(TooMany));
1464        assert_eq!(store.len(), 1);
1465        // Series that no kept read holds count for nothing: once the read of the first half is a
1466        // day old, the other half fits.
1467        assert_eq!(store.push(WINDOW + secs(15), other()), Ok(()));
1468        assert_eq!(store.len(), 1);
1469
1470        // Long labels count too: the labels and the subject of each series.
1471        let named = |name: String| {
1472            Reading::of(&format!(
1473                "# TYPE {JOBS} histogram\n{JOBS}_count{{laravel_job_name=\"{name}\"}} 1\n"
1474            ))
1475        };
1476        assert_eq!(named("J".repeat(MAX_KEY_BYTES / 2)), Err(TooMany));
1477        let mut store = MetricsStore::new(PACE);
1478        let quarter = MAX_KEY_BYTES / 4;
1479        store
1480            .push(secs(0), named("A".repeat(quarter)).unwrap())
1481            .unwrap();
1482        let longer = named("B".repeat(quarter)).unwrap();
1483        assert_eq!(store.push(secs(15), longer), Err(TooMany));
1484    }
1485
1486    /// An answer of `modules` modules, each with 10 routes and one job, in the shape of the recorded
1487    /// lines. The last route of each module answers 500.
1488    fn large_answer(modules: usize) -> String {
1489        use std::fmt::Write;
1490        let histogram = |text: &mut String, family: &str, bounds: &[&str], labels: &str| {
1491            for (at, le) in bounds.iter().enumerate() {
1492                writeln!(text, "{family}_bucket{{{labels},le=\"{le}\"}} {at}").unwrap();
1493            }
1494            writeln!(text, "{family}_sum{{{labels}}} 0.25").unwrap();
1495            writeln!(text, "{family}_count{{{labels}}} {}", bounds.len() - 1).unwrap();
1496        };
1497        let seconds = [
1498            "0.005", "0.01", "0.025", "0.05", "0.075", "0.1", "0.25", "0.5", "0.75", "1", "2.5",
1499            "5", "7.5", "10", "+Inf",
1500        ];
1501        let queries = [
1502            "0", "1", "2", "5", "10", "25", "50", "100", "250", "500", "1000", "+Inf",
1503        ];
1504        let scope = r#"otel_scope_name="nwidart/laravel-metrics""#;
1505        let route = |module: usize, route: usize| format!("/module-{module}/route-{route}/{{id}}");
1506        let mut text = String::from("# TYPE http_server_request_duration_seconds histogram\n");
1507        for (module, at) in (0..modules).flat_map(|module| (0..10).map(move |at| (module, at))) {
1508            let status = if at == 9 { 500 } else { 200 };
1509            let labels = format!(
1510                r#"http_request_method="GET",http_response_status_code="{status}",http_route="{}",network_protocol_version="1.1",{scope},url_scheme="http""#,
1511                route(module, at)
1512            );
1513            histogram(&mut text, REQUESTS, &seconds, &labels);
1514        }
1515        text.push_str("# TYPE laravel_db_queries histogram\n");
1516        for (module, at) in (0..modules).flat_map(|module| (0..10).map(move |at| (module, at))) {
1517            let labels = format!(r#"http_route="{}",{scope}"#, route(module, at));
1518            histogram(&mut text, "laravel_db_queries", &queries, &labels);
1519        }
1520        text.push_str("# TYPE messaging_process_duration_seconds histogram\n");
1521        for module in 0..modules {
1522            let labels = format!(
1523                r#"laravel_job_name="Modules\\Module{module}\\Jobs\\Work",messaging_destination_name="default",messaging_operation_name="process",messaging_system="database",{scope}"#
1524            );
1525            histogram(&mut text, JOBS, &seconds, &labels);
1526        }
1527        text
1528    }
1529
1530    #[test]
1531    fn a_large_answer_is_folded_within_the_budget() {
1532        let text = large_answer(60);
1533        let started = Instant::now();
1534        let reading = Reading::of(&text).unwrap();
1535        let took = started.elapsed();
1536        println!("folded {} bytes in {took:?}", text.len());
1537
1538        assert_eq!(reading.series.len(), 660);
1539        assert_eq!(reading.bounds.len(), 14);
1540        let errors: f64 = reading.series.values().map(|cell| cell.errors).sum();
1541        assert_eq!(errors, 60.0 * 14.0);
1542        let job = Subject::Job {
1543            module: None,
1544            class: r"Modules\Module7\Jobs\Work".to_owned(),
1545        };
1546        let of = |subject: &Subject| {
1547            let mut cells = reading
1548                .series
1549                .iter()
1550                .filter(|((kept, _), _)| kept == subject);
1551            let (_, cell) = cells.next().unwrap();
1552            assert!(cells.next().is_none());
1553            cell
1554        };
1555        assert_eq!(of(&job).count, 14.0);
1556        let request = Subject::Request {
1557            module: None,
1558            route: Some("/module-7/route-0/{id}".to_owned()),
1559            method: "GET".to_owned(),
1560        };
1561        let folded = of(&request);
1562        assert_eq!((folded.count, folded.errors, folded.sum), (14.0, 0.0, 0.25));
1563        assert_eq!(folded.buckets, (0..14).map(f64::from).collect::<Vec<_>>());
1564        assert!(took < secs(1), "took {took:?}");
1565    }
1566
1567    /// 26 hours of reads of 8 modules of 10 routes and 8 jobs, 15 s apart (design D1 of the
1568    /// hardening change). 8 modules run in under 2 s in a debug build; the 60 of `large_answer`
1569    /// take 13 s.
1570    #[test]
1571    fn a_full_window_of_a_large_app_holds_its_bound_and_stays_flat() {
1572        let template = Reading::of(&large_answer(8)).unwrap();
1573        let subjects = template.series.len();
1574        let row = subjects * (FIXED + template.bounds.len()) * size_of::<f64>();
1575        // Each subject is held twice, in its column and in the index; its labels once.
1576        let identity: usize = template
1577            .series
1578            .keys()
1579            .map(|(subject, labels)| 2 * subject.bytes() + labels.len())
1580            .sum();
1581        // Per subject: its column, its entry in the index, its map of bases with room for 3 and
1582        // its one base. The two queues have room for 768 reads: 512 coarse and 256 fine.
1583        let per_subject = size_of::<Column>()
1584            + size_of::<(Subject, usize)>()
1585            + 3 * size_of::<(String, Base)>()
1586            + row / subjects;
1587        let maps = subjects * per_subject + 768 * size_of::<Read>();
1588        let bound = 520 * row + identity + maps;
1589        // Every counter grows by one each read.
1590        let read = |n: u32| {
1591            let mut reading = template.clone();
1592            for cell in reading.series.values_mut() {
1593                for counter in [&mut cell.count, &mut cell.errors, &mut cell.sum]
1594                    .into_iter()
1595                    .chain(&mut cell.buckets)
1596                {
1597                    *counter += f64::from(n);
1598                }
1599            }
1600            reading
1601        };
1602        let mut store = MetricsStore::new(PACE);
1603        let empty = store.bytes_held();
1604        let mut full = 0;
1605        for n in 0..6_240 {
1606            store.push(PACE * n, read(n)).unwrap();
1607            let held = store.bytes_held();
1608            assert!(held <= bound, "read {n} holds {held} bytes, over {bound}");
1609            match n + 1 {
1610                1 => assert!(empty < held),
1611                5_760 => full = held,
1612                pushes if pushes > 5_760 => assert!(held <= full + row, "read {n} holds {held}"),
1613                _ => {}
1614            }
1615        }
1616        println!("{subjects} subjects hold {full} bytes, under {bound}");
1617    }
1618
1619    #[test]
1620    fn the_real_clock_adds_the_time_asleep_and_never_goes_back() {
1621        // What `Instant` and the wall clock ran between calls: awake, a night asleep, the wall clock
1622        // set back an hour, awake.
1623        let calls = [(15, 15), (15, 8 * 3600), (15, 0), (15, 15)];
1624        let (mut instant, mut offset) = (Duration::ZERO, Duration::ZERO);
1625        let times: Vec<Duration> = calls
1626            .into_iter()
1627            .map(|(instant_ran, wall_ran)| {
1628                offset = ahead(offset, secs(instant_ran), secs(wall_ran));
1629                instant += secs(instant_ran);
1630                instant + offset
1631            })
1632            .collect();
1633
1634        let night = 8 * 3600 - 15;
1635        assert_eq!(
1636            times,
1637            [
1638                secs(15),
1639                secs(30 + night),
1640                secs(45 + night),
1641                secs(60 + night)
1642            ]
1643        );
1644    }
1645}