gur/
metrics.rs

1//! Metrics of commands
2use std::time::Duration;
3
4/// Metrics of commands.
5///
6/// A trigger function is called for each command with this type of object.
7/// The trigger makes decisions whether a snapshot should be taken or not
8/// using the information in this type.
9/// See [Snapshot trigger](crate::triggers#snapshot-trigger) for more details.
10#[derive(Clone, Debug)]
11pub struct Metrics {
12    elapsed: Duration,
13    elapsed_from_snapshot: Duration,
14    distance: usize,
15}
16
17impl Metrics {
18    pub(crate) fn zero() -> Self {
19        Self {
20            elapsed: Duration::ZERO,
21            elapsed_from_snapshot: Duration::ZERO,
22            distance: 0,
23        }
24    }
25
26    /// Elapsed time of one command.
27    ///
28    /// ```txt
29    /// c: command
30    /// s: snapshot
31    ///
32    /// c1    <-->
33    /// c2          <-->
34    /// c3                <-->
35    /// c4                      <-->
36    /// /--\  +--+  +--+  +--+  +--+
37    /// |s0|--|c1|--|c2|--|c3|--|c4|
38    /// \--/  +--+  +--+  +--+  +--+
39    /// ```
40    pub fn elapsed(&self) -> Duration {
41        self.elapsed
42    }
43
44    /// Total elapsed time of commands from last snapshot.
45    ///
46    /// ```txt
47    /// c: command
48    /// s: snapshot
49    ///
50    /// c1    <-->
51    /// c2    <-------->
52    /// c3    <-------------->
53    /// c4    <-------------------->
54    /// /--\  +--+  +--+  +--+  +--+
55    /// |s0|--|c1|--|c2|--|c3|--|c4|
56    /// \--/  +--+  +--+  +--+  +--+
57    /// ```
58    pub fn elapsed_from_snapshot(&self) -> Duration {
59        self.elapsed_from_snapshot
60    }
61
62    /// Distance (number of commands) from last snapshot.
63    ///
64    /// ```txt
65    /// c: command
66    /// s: snapshot
67    ///
68    /// c1    1 command
69    /// c2    2 commands
70    /// c3    3 commands
71    /// c4    4 commands
72    /// /--\  +--+  +--+  +--+  +--+
73    /// |s0|--|c1|--|c2|--|c3|--|c4|
74    /// \--/  +--+  +--+  +--+  +--+
75    /// ```
76    pub fn distance_from_snapshot(&self) -> usize {
77        self.distance
78    }
79
80    pub(crate) fn make_next(&self, next_duration: Duration) -> Self {
81        let accumulated = next_duration + self.elapsed_from_snapshot();
82        Self {
83            elapsed: next_duration,
84            elapsed_from_snapshot: accumulated,
85            distance: 1 + self.distance_from_snapshot(),
86        }
87    }
88}