1use 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
21const WINDOW: Duration = Duration::from_secs(24 * 60 * 60);
23const FINE: Duration = Duration::from_secs(60 * 60);
25const STEP: Duration = Duration::from_secs(5 * 60);
27const GAP_PACES: u32 = 3;
29const REQUESTS: &str = "http_server_request_duration_seconds";
31const JOBS: &str = "messaging_process_duration_seconds";
32const DATABASE: &str = "db_client_operation_duration_seconds";
33const FIXED: usize = 3;
35const MAX_ROW: usize = 32_768;
38const MAX_KEY_BYTES: usize = 4 * 1024 * 1024;
41
42#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub(crate) enum Subject {
45 Request {
47 module: Option<String>,
48 route: Option<String>,
49 method: String,
50 },
51 Job {
53 module: Option<String>,
54 class: String,
55 },
56 Database { module: String },
58}
59
60impl Subject {
61 #[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 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#[derive(Debug, Clone, PartialEq, Default)]
94pub(crate) struct Cell {
95 pub count: f64,
97 pub errors: f64,
99 pub sum: f64,
101 pub buckets: Vec<f64>,
104}
105
106#[derive(Debug, Clone, PartialEq, Default)]
108pub(crate) struct Reading {
109 pub bounds: Vec<f64>,
112 pub series: HashMap<(Subject, String), Cell>,
114}
115
116impl Cell {
117 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub(crate) struct TooMany;
131
132fn 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 let _ = write!(key, "{name}={value:?},");
141 }
142 key
143}
144
145fn over(series: usize, bounds: usize, bytes: usize) -> bool {
148 series.saturating_mul(FIXED + bounds) > MAX_ROW || bytes > MAX_KEY_BYTES
149}
150
151fn 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 pub(crate) fn of(text: &str) -> Result<Reading, TooMany> {
168 let mut reading = Reading::default();
169 let mut bytes = 0;
170 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#[derive(Debug)]
261pub(crate) struct Change<'a> {
262 pub covered: Duration,
264 pub bounds: &'a [f64],
266 pub cells: Vec<(&'a Subject, Cell)>,
269}
270
271#[derive(Debug, Clone, PartialEq)]
273pub(crate) struct Step {
274 pub at: Duration,
276 pub covered: Duration,
278 pub counts: Vec<f64>,
280 pub starts: bool,
282}
283
284#[derive(Debug)]
286struct Read {
287 at: Duration,
288 covered: Duration,
290 starts_run: bool,
292 run: u64,
294 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#[derive(Debug)]
307struct Base {
308 counters: Vec<f64>,
311 run: u64,
314 seen: Duration,
316}
317
318#[derive(Debug)]
320struct Column {
321 subject: Subject,
322 bases: HashMap<String, Base>,
324}
325
326#[derive(Debug)]
328pub(crate) struct MetricsStore {
329 every: Duration,
330 bounds: Vec<f64>,
331 bound_seen: Vec<Duration>,
333 columns: Vec<Column>,
334 index: HashMap<Subject, usize>,
335 run: u64,
337 coarse: VecDeque<Read>,
339 fine: VecDeque<Read>,
342 latest: Option<(Duration, Duration)>,
345 totals: Vec<f64>,
348 scratch: Vec<f64>,
350}
351
352impl MetricsStore {
353 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 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 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 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 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 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 let reset = counters
446 .iter()
447 .zip(&base.counters)
448 .any(|(now, base)| now < base);
449 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 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 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 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 fn bucket(&self, bound: f64) -> Option<usize> {
515 self.bounds
516 .binary_search_by(|kept| kept.total_cmp(&bound))
517 .ok()
518 }
519
520 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 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 #[cfg(test)]
541 pub(crate) fn len(&self) -> usize {
542 self.coarse.len() + self.fine.len()
543 }
544
545 #[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 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 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 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 pub(crate) fn subjects(&self) -> impl Iterator<Item = &Subject> {
670 self.columns.iter().map(|column| &column.subject)
671 }
672
673 pub(crate) fn newest(&self) -> Option<Duration> {
675 self.latest.map(|(at, _)| at)
676 }
677
678 fn width(&self) -> usize {
680 FIXED + self.bounds.len()
681 }
682
683 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 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 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 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 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 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 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 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 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 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
883fn 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
912fn 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
923pub type MetricsClock = Arc<dyn Fn() -> Duration + Send + Sync>;
925
926#[derive(Debug, Clone, PartialEq, Eq)]
928pub enum NotKept {
929 NoMetrics(NoMetrics),
931 NotMetrics,
933 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
946pub struct MetricsState {
947 pub last: Option<Result<(), NotKept>>,
950 pub serial: u64,
952 pub ago: Option<Duration>,
955}
956
957#[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 pub fn new() -> Self {
973 Self::with_clock(real_clock())
974 }
975
976 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 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 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
1040fn 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
1061fn 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 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 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 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 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 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 store
1242 .push(secs(61), reading(&[(route("/"), count(20.0))]))
1243 .unwrap();
1244 assert!(store.change(WINDOW).is_none());
1245
1246 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 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 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(store.push(WINDOW + secs(15), other()), Ok(()));
1468 assert_eq!(store.len(), 1);
1469
1470 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 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 #[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 let identity: usize = template
1577 .series
1578 .keys()
1579 .map(|(subject, labels)| 2 * subject.bytes() + labels.len())
1580 .sum();
1581 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 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 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}