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
/*! Multiple static nodes that can be load balanced by some strategy. */

use client::sender::{
    NextParams,
    NodeAddress,
    PreRequestParams,
    RequestParams,
};
use error::{
    self,
    Error,
};
use private;
use std::sync::atomic::{
    AtomicUsize,
    Ordering,
};
use std::sync::Arc;

/** Select a base address for a given request using some strategy. */
#[derive(Clone)]
pub struct StaticNodes<TStrategy = RoundRobin> {
    nodes: Vec<NodeAddress>,
    strategy: TStrategy,
    params: PreRequestParams,
}

impl<TStrategy> NextParams for StaticNodes<TStrategy>
where
    TStrategy: Strategy + Clone,
{
    type Params = Result<RequestParams, Error>;

    fn next(&self) -> Self::Params {
        self.strategy
            .try_next(&self.nodes)
            .map(|address| RequestParams::from_parts(address, self.params.clone()))
            .map_err(error::request)
    }
}

impl<TStrategy> private::Sealed for StaticNodes<TStrategy> {}

impl<TStrategy> StaticNodes<TStrategy> {
    pub(crate) fn set(&mut self, nodes: Vec<NodeAddress>) -> Result<(), Error> {
        if nodes.len() == 0 {
            Err(error::request(error::message(
                "the number of node addresses must be greater than 0",
            )))?
        }

        self.nodes = nodes;

        Ok(())
    }

    #[cfg(test)]
    pub(crate) fn get(&self) -> &[NodeAddress] {
        &self.nodes
    }
}

impl StaticNodes<RoundRobin> {
    /** Use a round-robin strategy for balancing traffic over the given set of nodes. */
    pub fn round_robin<I, S>(nodes: I, params: PreRequestParams) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<NodeAddress>,
    {
        let nodes: Vec<_> = nodes.into_iter().map(Into::into).collect();

        let strategy = RoundRobin::default();

        StaticNodes {
            nodes: nodes,
            strategy: strategy,
            params: params,
        }
    }
}

/** The strategy selects an address from a given collection. */
pub trait Strategy: Send + Sync {
    /** Try get the next address. */
    fn try_next(&self, nodes: &[NodeAddress]) -> Result<NodeAddress, StrategyError>;
}

/**
An error attempting to get an address using a strategy.
*/
quick_error! {
    #[derive(Debug)]
    pub enum StrategyError {
        Empty {
            description("the list of addresses was empty")
        }
        /** A different kind of error */
        Other(err: String) {
            description("an error occurred while getting an address")
            display("an error occurred while getting an address. Caused by: {}", err)
        }
        #[doc(hidden)]
        __NonExhaustive
    }
}

/** A round-robin strategy cycles through nodes sequentially. */
#[derive(Clone)]
pub struct RoundRobin {
    index: Arc<AtomicUsize>,
}

impl Default for RoundRobin {
    fn default() -> Self {
        RoundRobin {
            index: Arc::new(AtomicUsize::new(0)),
        }
    }
}

impl Strategy for RoundRobin {
    fn try_next(&self, nodes: &[NodeAddress]) -> Result<NodeAddress, StrategyError> {
        if nodes.len() == 0 {
            Err(StrategyError::Empty)
        } else {
            let i = self.index.fetch_add(1, Ordering::Relaxed) % nodes.len();
            Ok(nodes[i].clone())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use client::sender::NextParams;

    fn round_robin(addresses: Vec<&'static str>) -> StaticNodes<RoundRobin> {
        StaticNodes::round_robin(addresses, PreRequestParams::default())
    }

    fn expected_addresses() -> Vec<&'static str> {
        vec!["http://a:9200", "http://b:9200", "http://c:9200"]
    }

    #[test]
    fn round_robin_next_multi() {
        let nodes = round_robin(expected_addresses());

        for _ in 0..10 {
            for expected in expected_addresses() {
                let actual = nodes.next().unwrap();

                assert_eq!(expected, actual.get_base_url());
            }
        }
    }

    #[test]
    fn round_robin_next_single() {
        let expected = "http://a:9200";
        let nodes = round_robin(vec![expected]);

        for _ in 0..10 {
            let actual = nodes.next().unwrap();

            assert_eq!(expected, actual.get_base_url());
        }
    }

    #[test]
    fn round_robin_next_empty_fails() {
        let nodes = round_robin(vec![]);

        assert!(nodes.next().is_err());
    }
}