Skip to main content

hopr_api/network/
types.rs

1/// Network health represented with colors, where green is the best and red
2/// is the worst possible observed network quality.
3#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, strum::Display, strum::EnumString)]
4pub enum Health {
5    /// Unknown health, on application startup
6    Unknown = 0,
7    /// No connection, default
8    Red = 1,
9    /// Low-quality connection to at least 1 public relay
10    Orange = 2,
11    /// High-quality connection to at least 1 public relay
12    Yellow = 3,
13    /// High-quality connection to at least 1 public relay and 1 NAT node
14    Green = 4,
15}
16
17pub trait Observable {
18    /// Record a new result of the probe towards the measured peer.
19    fn record_probe(&mut self, latency: std::result::Result<std::time::Duration, ()>);
20
21    /// The timestamp of the last update.
22    fn last_update(&self) -> std::time::Duration;
23
24    /// Return average latency observed for the measured peer.
25    fn average_latency(&self) -> Option<std::time::Duration>;
26
27    /// A value representing the average success rate of probes.
28    ///
29    /// It is from the range [0.0, 1.0]. The higher the value, the better the score.
30    fn average_probe_rate(&self) -> f64;
31
32    /// A value scoring the observed peer.
33    ///
34    /// It is from the range [0.0, 1.0]. The higher the value, the better the score.
35    fn score(&self) -> f64;
36}
37
38#[cfg(test)]
39mod tests {
40    use super::Health;
41
42    #[test]
43    fn network_health_should_be_ordered_numerically_for_hopr_metrics_output() {
44        assert_eq!(Health::Unknown as i32, 0);
45        assert_eq!(Health::Red as i32, 1);
46        assert_eq!(Health::Orange as i32, 2);
47        assert_eq!(Health::Yellow as i32, 3);
48        assert_eq!(Health::Green as i32, 4);
49    }
50
51    #[test]
52    fn network_health_should_serialize_to_a_proper_string() {
53        assert_eq!(format!("{}", Health::Orange), "Orange".to_owned())
54    }
55
56    #[test]
57    fn network_health_should_deserialize_from_proper_string() -> anyhow::Result<()> {
58        let parsed: Health = "Orange".parse()?;
59        assert_eq!(parsed, Health::Orange);
60
61        Ok(())
62    }
63}