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
use std::iter::Iterator;
use query::QueryBuilder;
use client::{CDRS, Session};
use error::{Error as CError, Result as CResult};
use authenticators::Authenticator;
use compression::Compression;
use r2d2;
use transport::CDRSTransport;
use rand;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(PartialEq)]
pub enum LoadBalancingStrategy {
RoundRobin,
Random,
}
impl LoadBalancingStrategy {
pub fn next<'a, N>(&'a self, nodes: &'a Vec<N>, i: usize) -> Option<&N> {
match *self {
LoadBalancingStrategy::Random => nodes.get(self.rnd_idx((0, Some(nodes.len())))),
LoadBalancingStrategy::RoundRobin => {
let mut cycle = nodes.iter().cycle().skip(i);
cycle.next()
}
}
}
fn rnd_idx(&self, bounds: (usize, Option<usize>)) -> usize {
let min = bounds.0;
let max = bounds.1.unwrap_or(u8::max_value() as usize);
let rnd = rand::random::<usize>();
min + rnd * (max - min) / (u8::max_value() as usize)
}
}
pub struct LoadBalancer<T> {
strategy: LoadBalancingStrategy,
nodes: Vec<T>,
i: AtomicUsize,
}
impl<T> LoadBalancer<T> {
pub fn new(nodes: Vec<T>, strategy: LoadBalancingStrategy) -> LoadBalancer<T> {
LoadBalancer {
nodes: nodes,
strategy: strategy,
i: AtomicUsize::new(0),
}
}
pub fn next(&self) -> Option<&T> {
let next = self.strategy
.next(&self.nodes, self.i.load(Ordering::Relaxed) as usize);
if self.strategy == LoadBalancingStrategy::RoundRobin {
self.i.fetch_add(1, Ordering::Relaxed);
let i = self.i.load(Ordering::Relaxed);
match i.checked_rem(self.nodes.len() as usize) {
Some(rem) => self.i.store(rem, Ordering::Relaxed),
None => return None,
}
}
next
}
}
pub struct ClusterConnectionManager<T, X> {
load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression,
}
impl<T, X> ClusterConnectionManager<T, X>
where T: Authenticator + Send + Sync + 'static
{
pub fn new(load_balancer: LoadBalancer<X>,
authenticator: T,
compression: Compression)
-> ClusterConnectionManager<T, X> {
ClusterConnectionManager {
load_balancer: load_balancer,
authenticator: authenticator,
compression: compression,
}
}
}
impl<T: Authenticator + Send + Sync + 'static,
X: CDRSTransport + Send + Sync + 'static> r2d2::ManageConnection
for ClusterConnectionManager<T, X> {
type Connection = Session<T, X>;
type Error = CError;
fn connect(&self) -> Result<Self::Connection, Self::Error> {
let transport_res: CResult<X> = self.load_balancer
.next()
.ok_or_else(|| "Cannot get next node".into())
.and_then(|x| x.try_clone().map_err(|e| e.into()));
let transport = try!(transport_res);
let compression = self.compression;
let cdrs = CDRS::new(transport, self.authenticator.clone());
cdrs.start(compression)
}
fn is_valid(&self, connection: &mut Self::Connection) -> Result<(), Self::Error> {
let query = QueryBuilder::new("SELECT * FROM system.peers;").finalize();
connection.query(query, false, false).map(|_| ())
}
fn has_broken(&self, _connection: &mut Self::Connection) -> bool {
false
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_robin() {
let nodes = vec!["a", "b", "c"];
let nodes_c = nodes.clone();
let load_balancer = LoadBalancer::new(nodes, LoadBalancingStrategy::RoundRobin);
for i in 0..10 {
assert_eq!(&nodes_c[i % 3], load_balancer.next().unwrap());
}
}
}