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
use super::LoadBalancingStrategy;
use async_trait::async_trait;

use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};

use std::sync::atomic::AtomicUsize;

use tokio::sync::Mutex;

struct Targets {
    targets: Box<[SocketAddr]>,
    index: AtomicUsize,
}

impl Targets {
    fn new(targets: impl AsRef<[SocketAddr]>) -> Self {
        Targets {
            targets: targets.as_ref().into(),
            index: AtomicUsize::new(0),
        }
    }
    fn next(&self) -> SocketAddr {
        let index = self
            .index
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        self.targets[index % self.targets.len()]
    }
}

pub struct RoundRobinSimple {
    targets: Targets,
}

impl RoundRobinSimple {
    pub(crate) fn new(targets: impl AsRef<[SocketAddr]>) -> Self {
        Self {
            targets: Targets::new(targets),
        }
    }
}

#[async_trait]
impl LoadBalancingStrategy for RoundRobinSimple {
    async fn entry(&self, _ip: IpAddr) -> SocketAddr {
        self.targets.next()
    }
}

pub struct RoundRobinIpHash {
    targets: Targets,
    table: Mutex<HashMap<IpAddr, SocketAddr>>,
}

impl RoundRobinIpHash {
    pub(crate) fn new(targets: impl AsRef<[SocketAddr]>) -> Self {
        Self {
            targets: Targets::new(targets),
            table: Mutex::new(HashMap::new()),
        }
    }
    async fn entry(&self, ip: IpAddr) -> SocketAddr {
        let mut table = self.table.lock().await;
        *table.entry(ip).or_insert_with(|| self.targets.next())
    }
}

#[async_trait]
impl LoadBalancingStrategy for RoundRobinIpHash {
    async fn entry(&self, ip: IpAddr) -> SocketAddr {
        self.entry(ip).await
    }
}