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::cell::RefCell;
use std::collections::HashMap;
use std::io::Cursor;
use std::rc::Rc;

use blake2::{Blake2b, Digest};
use byteorder::{LittleEndian, ReadBytesExt};

#[derive(Debug)]
pub struct Host {
    name: String,
    load: u64,
}

#[derive(Debug)]
pub struct Config {
    pub replication_factor: u64,
    pub load: f64,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            replication_factor: 10,
            load: 1.25,
        }
    }
}

pub struct Ring {
    config: Config,

    hashes: Vec<u64>,                                 // hashes sorted ascendingly
    host_by_hash: HashMap<u64, Rc<RefCell<Host>>>,    // index host by hash
    host_by_name: HashMap<String, Rc<RefCell<Host>>>, // index host by name
    load: u64,                                        // the total load of ring
}

unsafe impl Send for Ring {}
unsafe impl Sync for Ring {}

impl Ring {
    pub fn new(config: Config) -> Self {
        Self {
            config: config,
            hashes: Default::default(),
            host_by_hash: Default::default(),
            host_by_name: Default::default(),
            load: 0,
        }
    }

    pub fn replication_factor(&self) -> u64 {
        self.config.replication_factor
    }

    /// Adds a new host to the ring.
    /// If the host already added, ignore.
    pub fn add(&mut self, hostname: &str) {
        if self.host_by_name.contains_key(hostname) {
            return;
        }

        let host = Rc::new(RefCell::new(Host {
            name: hostname.to_owned(),
            load: 0,
        }));

        self.host_by_name.insert(hostname.to_owned(), host.clone());

        for i in 0..self.replication_factor() {
            let hash = Self::hash(&format!("{}{}", hostname, i));
            self.host_by_hash.insert(hash, host.clone());
            self.hashes.push(hash);
        }

        self.hashes.sort();
    }

    /// Removes host from the ring.
    pub fn remove(&mut self, hostname: &str) {
        for i in 0..self.replication_factor() {
            let hash = Self::hash(&format!("{}{}", hostname, i));
            self.host_by_hash.remove(&hash);
            let idx = self.hashes.iter().position(|x| *x == hash).unwrap();
            self.hashes.remove(idx);
        }

        self.host_by_name.remove(hostname);
    }

    /// Locates a host for the key.
    pub fn get(&mut self, key: &str) -> Option<String> {
        if self.host_by_hash.is_empty() {
            return None;
        }

        let hash = Self::hash(key);
        let idx = self.search(hash);
        if let Some(host) = self.host_by_hash.get(&self.hashes[idx]) {
            Some(host.borrow().name.clone())
        } else {
            None
        }
    }

    /// Picks the least load host for the key.
    pub fn get_least(&mut self, key: &str) -> Option<String> {
        if self.host_by_hash.is_empty() {
            return None;
        }

        let hash = Self::hash(key);
        let avg_load = self.avg_load();

        let mut idx = self.search(hash);
        loop {
            let host = self.host_by_hash.get(&self.hashes[idx]).unwrap();
            if (host.borrow().load + 1) as f64 <= avg_load {
                return Some(host.borrow().name.clone());
            }
            idx += 1;
            if idx >= self.host_by_hash.len() {
                idx = 0;
            }
        }
    }

    /// Lists all hosts in the ring.
    pub fn hosts(&mut self) -> Vec<String> {
        self.host_by_name.keys().cloned().into_iter().collect()
    }

    /// Sets the load of host to the given value.
    pub fn set_load(&mut self, hostname: &str, load: u64) {
        if let Some(host) = self.host_by_name.get(hostname) {
            let mut host = host.borrow_mut();
            self.load -= host.load;
            host.load = load;
            self.load += load;
        }
    }

    /// Increments the load of host by 1.
    pub fn inc_load(&mut self, hostname: &str) {
        if let Some(host) = self.host_by_name.get(hostname) {
            self.load += 1;
            host.borrow_mut().load += 1;
        }
    }

    /// Decrements the load of host by 1.
    pub fn decr_load(&mut self, hostname: &str) {
        if let Some(host) = self.host_by_name.get(hostname) {
            self.load -= 1;
            host.borrow_mut().load -= 1;
        }
    }

    /// Gets the average load of ring.
    pub fn avg_load(&self) -> f64 {
        let mut load = (self.load + 1) as f64 / self.host_by_name.len() as f64;
        if load == 0.0 {
            load = 1.0;
        }
        (load * self.config.load).ceil()
    }

    fn search(&self, key: u64) -> usize {
        for i in 0..self.hashes.len() {
            let idx = self.hashes[i];
            if idx >= key {
                return i as usize;
            }
        }

        0
    }

    /// Hashes key.
    /// TODO(luncj): supports custom hasher.
    fn hash(key: &str) -> u64 {
        let hash = Blake2b::new().chain(key.as_bytes()).result();

        let mut rdr = Cursor::new(hash);

        rdr.read_u64::<LittleEndian>().unwrap()
    }
}

#[cfg(test)]
mod tests {
    use super::Ring;

    #[test]
    fn ring_add() {
        let mut r = Ring::new(Default::default());
        r.add("1.1.1.1");

        assert_eq!(r.replication_factor(), r.hashes.len() as u64);
    }

    #[test]
    fn ring_get() {
        let mut r = Ring::new(Default::default());
        r.add("1.1.1.1");
        let host = r.get("1.1.1.1");

        assert!(host.is_some());
        assert_eq!("1.1.1.1", host.unwrap());
    }

    #[test]
    fn ring_remove() {
        let mut r = Ring::new(Default::default());
        r.add("1.1.1.1");
        r.remove("1.1.1.1");

        assert!(r.hashes.is_empty());
        assert!(r.hosts().is_empty());
    }
}