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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use std::net::SocketAddr;
use super::builder::Port;
use super::{Chart, Entry};

impl<const N: usize> Chart<N, Port> {
    /// Returns an vector with each discovered node's socketadresses.
    /// # Note 
    /// - vector order is random
    /// - only availible for Chart configured with 
    /// [`ChartBuilder::with_service_ports`](crate::ChartBuilder::with_service_ports) 
    /// and build using [`ChartBuilder::finish`](crate::ChartBuilder::finish).
    /// ```rust
    /// # use std::error::Error;
    /// # use instance_chart::{discovery, ChartBuilder};
    /// # 
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn Error>> {
    /// let chart = ChartBuilder::new()
    ///     .with_id(1)
    /// #   .with_discovery_port(43785) 
    ///     .with_service_ports([8042, 8043, 8044])
    ///     .finish()?;
    /// let maintain = discovery::maintain(chart.clone());
    /// let _ = tokio::spawn(maintain); // maintain task will run forever
    /// let port_lists = chart.addr_lists_vec();
    /// #   Ok(())
    /// # }
    /// ```

    // lock poisoning happens only on crash in another thread, in which 
    // case panicing here is expected
    #[allow(clippy::missing_panics_doc)] 
    #[must_use]
    pub fn addr_lists_vec(&self) -> Vec<[SocketAddr; N]> {
        self.map
            .lock()
            .unwrap()
            .iter()
            .map(|(_, entry)| {
                let Entry { ip, msg: ports } = entry;
                ports.map(|p| SocketAddr::new(*ip, p))
            })
            .collect()
    }
}

impl<const N: usize> Chart<N, Port> {
    /// Returns a vector over each discoverd node's nth-socketadress
    /// # Note 
    /// - vector order is random
    /// - only availible for Chart configured with 
    /// [`ChartBuilder::with_service_ports`](crate::ChartBuilder::with_service_ports) 
    /// and build using [`ChartBuilder::finish`](crate::ChartBuilder::finish).
    ///
    /// # Examples 
    /// ```rust
    /// # use std::error::Error;
    /// # use instance_chart::{discovery, ChartBuilder};
    /// # 
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn Error>> {
    /// let web_server_port = 8043;
    /// let chart = ChartBuilder::new()
    ///     .with_id(1)
    /// #   .with_discovery_port(43784) 
    ///     .with_service_ports([8042, web_server_port, 8044])
    ///     .finish()?;
    /// let maintain = discovery::maintain(chart.clone());
    /// let _ = tokio::spawn(maintain); // maintain task will run forever
    /// let web_server_ports = chart.nth_addr_vec::<2>();
    /// #   Ok(())
    /// # }
    /// ```

    // lock poisoning happens only on crash in another thread, in which 
    // case panicing here is expected
    #[allow(clippy::missing_panics_doc)] 
    #[must_use]
    pub fn nth_addr_vec<const IDX: usize>(&self) -> Vec<SocketAddr> {
        self.map
            .lock()
            .unwrap()
            .iter()
            .map(|(_, entry)| {
                let Entry { ip, msg: ports } = entry;
                let port = ports[IDX];
                SocketAddr::new(*ip, port)
            })
            .collect()
    }
}

impl<'a> Chart<1, Port> {
    /// Returns a vector over each discoverd nodes's socketadress
    /// # Note 
    /// - vector order is random
    /// - only availible for Chart configured with 
    /// [`ChartBuilder::with_service_port`](crate::ChartBuilder::with_service_port) 
    /// and build using [`ChartBuilder::finish`](crate::ChartBuilder::finish).
    /// ```rust
    /// # use std::error::Error;
    /// # use instance_chart::{discovery, ChartBuilder};
    /// # 
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn Error>> {
    /// let chart = ChartBuilder::new()
    ///     .with_id(1)
    /// #   .with_discovery_port(43782) 
    ///     .with_service_port(8042)
    ///     .finish()?;
    /// let maintain = discovery::maintain(chart.clone());
    /// let _ = tokio::spawn(maintain); // maintain task will run forever
    /// let ports = chart.addr_vec();
    /// #   Ok(())
    /// # }
    /// ```

    // lock poisoning happens only on crash in another thread, in which 
    // case panicing here is expected
    #[allow(clippy::missing_panics_doc)] 
    #[must_use]
    pub fn addr_vec(&'a self) -> Vec<SocketAddr> {
        self.map
            .lock()
            .unwrap()
            .iter()
            .map(|(_, entry)| {
                let Entry { ip, msg: [port] } = entry;
                SocketAddr::new(*ip, *port)
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use crate::chart::{Entry, Interval};
    use crate::{Chart, Id};
    use serde::Serialize;
    use std::collections::{HashMap, HashSet};
    use std::fmt::Debug;
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};
    use std::sync::{Arc, Mutex};
    use tokio::net::UdpSocket;

    impl<const N: usize, T: Serialize + Debug + Clone> Chart<N, T> {
        async fn test<F>(mut gen_kv: F) -> Self
        where
            F: FnMut(u8) -> (Id, Entry<[T; N]>) + Copy,
        {
            let msg = gen_kv(0).1.msg;
            let map: HashMap<Id, Entry<_>> = (1..10).map(gen_kv).collect();
            Self {
                header: 0,
                service_id: 0,
                msg,
                sock: Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()),
                interval: Interval::test(),
                map: Arc::new(Mutex::new(map)),
                broadcast: tokio::sync::broadcast::channel(1).0,
            }
        }
    }

    #[tokio::test]
    async fn iter_ports() {
        fn test_kv(n: u8) -> (Id, Entry<[u16; 1]>) {
            let ip = IpAddr::V4(Ipv4Addr::new(n, 0, 0, 1));
            let port = 8000 + n as u16;
            (n as u64, Entry { ip, msg: [port] })
        }

        let chart = Chart::test(test_kv).await;
        let iter: HashSet<_> = chart.addr_vec().into_iter().collect();
        let correct: HashSet<_> = (1..10)
            .map(test_kv)
            .map(|(_, e)| e)
            .map(|e| (e.ip, e.msg[0]))
            .map(SocketAddr::from)
            .collect();

        assert_eq!(iter, correct)
    }

    fn entry_3ports(n: u8) -> (Id, Entry<[u16; 3]>) {
        let ip = IpAddr::V4(Ipv4Addr::new(n, 0, 0, 1));
        let port1 = 8000 + n as u16;
        let port2 = 7000 + n as u16;
        let port3 = 6000 + n as u16;
        (
            n as u64,
            Entry {
                ip,
                msg: [port1, port2, port3],
            },
        )
    }

    #[tokio::test]
    async fn iter_addr_lists() {
        let chart = Chart::test(entry_3ports).await;
        let iter: HashSet<_> = chart.addr_lists_vec().into_iter().collect();
        let correct: HashSet<_> = (1..10)
            .map(entry_3ports)
            .map(|(_, e)| e)
            .map(|e| e.msg.map(|p| (e.ip, p)).map(SocketAddr::from))
            .collect();
        assert_eq!(iter, correct)
    }
    #[tokio::test]
    async fn iter_nth_port() {
        let chart = Chart::test(entry_3ports).await;
        let iter: HashSet<_> = chart.nth_addr_vec::<1>().into_iter().collect();
        let correct: HashSet<_> = (1..10)
            .map(entry_3ports)
            .map(|(_, e)| e)
            .map(|e| (e.ip, e.msg[1]))
            .map(SocketAddr::from)
            .collect();
        assert_eq!(iter, correct)
    }
}