1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use crate::common::Identify;
use std::time::{Duration, SystemTime};

/// Carries connection infromation (TCP, unix socket, ...) so that remaining code can abstract away from it as Io
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConnectionInfo {
    pub id: String,
    pub local_addr: String,
    pub peer_addr: String,
    pub established: SystemTime,
}

impl ConnectionInfo {
    pub fn new(local_addr: String, peer_addr: String) -> Self {
        ConnectionInfo {
            id: Identify::now().to_string(),
            local_addr,
            peer_addr,
            established: SystemTime::now(),
        }
    }
    pub fn age(&self) -> Duration {
        self.established.elapsed().unwrap_or(Duration::ZERO)
    }
}
impl Default for ConnectionInfo {
    fn default() -> Self {
        ConnectionInfo::new(String::default(), String::default())
    }
}

impl std::fmt::Display for ConnectionInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "connection id {} from peer ", self.id)?;
        if self.peer_addr.is_empty() {
            f.write_str("Unknown")?;
        } else {
            f.write_str(self.peer_addr.as_str())?;
        }
        write!(f, " to local ")?;
        if self.local_addr.is_empty() {
            f.write_str("Unknown")?;
        } else {
            f.write_str(self.local_addr.as_str())?;
        }
        write!(f, " established {}s ago", self.age().as_secs_f64())?;
        Ok(())
    }
}

#[cfg(test)]
mod store_tests {
    use regex::Regex;

    use super::*;

    #[test]
    pub fn display_connection_info() {
        let sut = ConnectionInfo {
            established: SystemTime::UNIX_EPOCH,
            ..Default::default()
        };
        let dump = sut.to_string();
        let dump = Regex::new("[0-9]+")
            .expect("regex")
            .replace_all(&dump, "--redaced--");
        insta::assert_display_snapshot!(dump, @"connection id --redaced-- from peer Unknown to local Unknown established --redaced--.--redaced--s ago");
    }

    #[test]
    pub fn timely_connection_info() {
        let sut = ConnectionInfo::default();
        assert!(sut.established.elapsed().expect("duration").as_secs() < 1)
    }

    #[test]
    pub fn unique_connection_info() {
        let sut1 = ConnectionInfo::default();
        let sut2 = ConnectionInfo::default();
        assert_ne!(sut1.id, sut2.id);
    }
}