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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use super::LoadBalancingStrategy;
use super::WorkerConfig;
use crate::leak;
use crate::{client::Client, error::FaucetResult};
use std::hash::{Hash, Hasher};
use std::net::IpAddr;
use std::time::Duration;

struct Targets {
    targets: &'static [Client],
}

impl Targets {
    fn new(configs: &[WorkerConfig]) -> FaucetResult<Self> {
        let mut targets = Vec::new();
        for state in configs {
            let client = Client::builder(*state).build()?;
            targets.push(client);
        }
        let targets = leak!(targets);
        Ok(Targets { targets })
    }
}

pub struct IpHash {
    targets: Targets,
    targets_len: usize,
}

impl IpHash {
    pub(crate) fn new(targets: &[WorkerConfig]) -> FaucetResult<Self> {
        Ok(Self {
            targets_len: targets.as_ref().len(),
            targets: Targets::new(targets)?,
        })
    }
}

fn calculate_hash(ip: IpAddr) -> u64 {
    let mut hash_value = match ip {
        IpAddr::V4(ip) => ip.to_bits() as u64,
        IpAddr::V6(ip) => ip.to_bits() as u64,
    };
    hash_value ^= hash_value >> 33;
    hash_value = hash_value.wrapping_mul(0xff51afd7ed558ccd);
    hash_value ^= hash_value >> 33;
    hash_value = hash_value.wrapping_mul(0xc4ceb9fe1a85ec53);
    hash_value ^= hash_value >> 33;

    hash_value
}

fn hash_to_index(value: IpAddr, length: usize) -> usize {
    let hash = calculate_hash(value);
    (hash % length as u64) as usize
}

// 50ms is the minimum backoff time for exponential backoff
const BASE_BACKOFF: Duration = Duration::from_millis(50);

fn calculate_exponential_backoff(retries: u32) -> Duration {
    BASE_BACKOFF * 2u32.pow(retries)
}

impl LoadBalancingStrategy for IpHash {
    async fn entry(&self, ip: IpAddr) -> Client {
        let mut retries = 0;
        let index = hash_to_index(ip, self.targets_len);
        let client = self.targets.targets[index].clone();
        loop {
            if client.is_online() {
                break client;
            }

            let backoff = calculate_exponential_backoff(retries);

            log::debug!(
                target: "faucet",
                "IP {} tried to connect to offline {}, retrying in {:?}",
                ip,
                client.config.target,
                backoff
            );

            tokio::time::sleep(backoff).await;
            retries += 1;
        }
    }
}

#[cfg(test)]
mod tests {

    use std::sync::{atomic::AtomicBool, Arc};

    use super::*;

    #[test]
    fn ip_v4_test_distribution_of_hash_function_len_4() {
        const N_IP: usize = 100_000;

        // Generate 10_000 ip address and see the
        // distribution over diferent lengths
        let ips: Vec<IpAddr> = (0..N_IP)
            .map(|_| IpAddr::V4(std::net::Ipv4Addr::from_bits(rand::random::<u32>())))
            .collect();

        // Counts when length == 4
        let mut counts = [0; 4];

        ips.iter().for_each(|ip| {
            let index = hash_to_index(*ip, 4);
            counts[index] += 1;
        });

        let percent_0 = counts[0] as f64 / N_IP as f64;
        let percent_1 = counts[1] as f64 / N_IP as f64;
        let percent_2 = counts[2] as f64 / N_IP as f64;
        let percent_3 = counts[3] as f64 / N_IP as f64;
        assert!((0.24..=0.26).contains(&percent_0));
        assert!((0.24..=0.26).contains(&percent_1));
        assert!((0.24..=0.26).contains(&percent_2));
        assert!((0.24..=0.26).contains(&percent_3));
    }

    #[test]
    fn ip_v4_test_distribution_of_hash_function_len_3() {
        const N_IP: usize = 100_000;

        // Generate 10_000 ip address and see the
        // distribution over diferent lengths
        let ips: Vec<IpAddr> = (0..N_IP)
            .map(|_| IpAddr::V4(std::net::Ipv4Addr::from_bits(rand::random::<u32>())))
            .collect();

        // Counts when length == 4
        let mut counts = [0; 3];

        ips.iter().for_each(|ip| {
            let index = hash_to_index(*ip, 3);
            counts[index] += 1;
        });

        let percent_0 = counts[0] as f64 / N_IP as f64;
        let percent_1 = counts[1] as f64 / N_IP as f64;
        let percent_2 = counts[2] as f64 / N_IP as f64;
        assert!((0.32..=0.34).contains(&percent_0));
        assert!((0.32..=0.34).contains(&percent_1));
        assert!((0.32..=0.34).contains(&percent_2));
    }

    #[test]
    fn ip_v4_test_distribution_of_hash_function_len_2() {
        const N_IP: usize = 100_000;

        // Generate 10_000 ip address and see the
        // distribution over diferent lengths
        let ips: Vec<IpAddr> = (0..N_IP)
            .map(|_| IpAddr::V4(std::net::Ipv4Addr::from_bits(rand::random::<u32>())))
            .collect();

        // Counts when length == 4
        let mut counts = [0; 2];

        ips.iter().for_each(|ip| {
            let index = hash_to_index(*ip, 2);
            counts[index] += 1;
        });

        let percent_0 = counts[0] as f64 / N_IP as f64;
        let percent_1 = counts[1] as f64 / N_IP as f64;
        assert!((0.49..=0.51).contains(&percent_0));
        assert!((0.49..=0.51).contains(&percent_1));
    }

    #[test]
    fn ip_v6_test_distribution_of_hash_function_len_4() {
        const N_IP: usize = 100_000;

        // Generate 10_000 ip address and see the
        // distribution over diferent lengths
        let ips: Vec<IpAddr> = (0..N_IP)
            .map(|_| IpAddr::V6(std::net::Ipv6Addr::from_bits(rand::random::<u128>())))
            .collect();

        // Counts when length == 4
        let mut counts = [0; 4];

        ips.iter().for_each(|ip| {
            let index = hash_to_index(*ip, 4);
            counts[index] += 1;
        });

        let percent_0 = counts[0] as f64 / N_IP as f64;
        let percent_1 = counts[1] as f64 / N_IP as f64;
        let percent_2 = counts[2] as f64 / N_IP as f64;
        let percent_3 = counts[3] as f64 / N_IP as f64;
        assert!((0.24..=0.26).contains(&percent_0));
        assert!((0.24..=0.26).contains(&percent_1));
        assert!((0.24..=0.26).contains(&percent_2));
        assert!((0.24..=0.26).contains(&percent_3));
    }

    #[test]
    fn ip_v6_test_distribution_of_hash_function_len_3() {
        const N_IP: usize = 100_000;

        // Generate 10_000 ip address and see the
        // distribution over diferent lengths
        let ips: Vec<IpAddr> = (0..N_IP)
            .map(|_| IpAddr::V6(std::net::Ipv6Addr::from_bits(rand::random::<u128>())))
            .collect();

        // Counts when length == 4
        let mut counts = [0; 3];

        ips.iter().for_each(|ip| {
            let index = hash_to_index(*ip, 3);
            counts[index] += 1;
        });

        let percent_0 = counts[0] as f64 / N_IP as f64;
        let percent_1 = counts[1] as f64 / N_IP as f64;
        let percent_2 = counts[2] as f64 / N_IP as f64;
        assert!((0.32..=0.34).contains(&percent_0));
        assert!((0.32..=0.34).contains(&percent_1));
        assert!((0.32..=0.34).contains(&percent_2));
    }

    #[test]
    fn ip_v6_test_distribution_of_hash_function_len_2() {
        const N_IP: usize = 100_000;

        // Generate 10_000 ip address and see the
        // distribution over diferent lengths
        let ips: Vec<IpAddr> = (0..N_IP)
            .map(|_| IpAddr::V6(std::net::Ipv6Addr::from_bits(rand::random::<u128>())))
            .collect();

        // Counts when length == 4
        let mut counts = [0; 2];

        ips.iter().for_each(|ip| {
            let index = hash_to_index(*ip, 2);
            counts[index] += 1;
        });

        let percent_0 = counts[0] as f64 / N_IP as f64;
        let percent_1 = counts[1] as f64 / N_IP as f64;
        assert!((0.49..=0.51).contains(&percent_0));
        assert!((0.49..=0.51).contains(&percent_1));
    }

    #[test]
    fn test_new_targets() {
        let worker_state = WorkerConfig::dummy("test", "127.0.0.1:9999", true);
        let Targets { targets } = Targets::new(&[worker_state]).unwrap();

        assert_eq!(targets.len(), 1);
    }

    #[test]
    fn test_new_ip_hash() {
        let worker_state = WorkerConfig::dummy("test", "127.0.0.1:9999", true);
        let IpHash {
            targets,
            targets_len,
        } = IpHash::new(&[worker_state]).unwrap();

        assert_eq!(targets.targets.len(), 1);
        assert_eq!(targets_len, 1);
    }

    #[test]
    fn test_calculate_exponential_backoff() {
        assert_eq!(calculate_exponential_backoff(0), BASE_BACKOFF);
        assert_eq!(calculate_exponential_backoff(1), BASE_BACKOFF * 2);
        assert_eq!(calculate_exponential_backoff(2), BASE_BACKOFF * 4);
        assert_eq!(calculate_exponential_backoff(3), BASE_BACKOFF * 8);
    }

    #[tokio::test]
    async fn test_load_balancing_strategy() {
        use crate::client::ExtractSocketAddr;
        let workers = [
            WorkerConfig::dummy("test", "127.0.0.1:9999", true),
            WorkerConfig::dummy("test", "127.0.0.1:8888", true),
        ];
        let ip_hash = IpHash::new(&workers).unwrap();
        let client1 = ip_hash.entry("192.168.0.1".parse().unwrap()).await;
        let client2 = ip_hash.entry("192.168.0.1".parse().unwrap()).await;
        assert_eq!(client1.socket_addr(), client2.socket_addr());

        // This IP address should hash to a different index
        let client3 = ip_hash.entry("192.168.0.10".parse().unwrap()).await;
        let client4 = ip_hash.entry("192.168.0.10".parse().unwrap()).await;

        assert_eq!(client3.socket_addr(), client4.socket_addr());
        assert_eq!(client1.socket_addr(), client2.socket_addr());

        assert_ne!(client1.socket_addr(), client3.socket_addr());
    }

    #[tokio::test]
    async fn test_load_balancing_strategy_offline() {
        use crate::client::ExtractSocketAddr;

        let online = Arc::new(AtomicBool::new(false));
        let worker = WorkerConfig::dummy("test", "127.0.0.1:9999", true);

        let ip_hash = IpHash::new(&[worker]).unwrap();

        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            online.store(true, std::sync::atomic::Ordering::SeqCst);
        });

        let entry = ip_hash.entry("192.168.0.1".parse().unwrap()).await;

        assert_eq!(entry.socket_addr(), "127.0.0.1:9999".parse().unwrap());
    }
}