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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use std::ops::{Add, Sub};
use std::time::{Duration, SystemTime};
use std::default::Default;
use std::thread;
use redis;
use rand::{thread_rng, Rng};
use scripts::{LOCK, UNLOCK, EXTEND};
use errors::{RedlockResult, RedlockError};
use util;

#[derive(Debug)]
enum RequestInfo<'a> {
    Lock,
    Extend { resource_value: &'a str },
}

// Lock represents a acquired lock for specified resource.
#[derive(Debug)]
pub struct Lock<'a> {
    redlock: &'a Redlock,
    resource_name: String,
    value: String,
    expiration: SystemTime,
}

impl<'a> Lock<'a> {
    // Release the acquired lock.
    pub fn unlock(&self) -> RedlockResult<()> {
        self.redlock.unlock(&self.resource_name, &self.value)
    }

    // Extend the TTL of acquired lock.
    pub fn extend(&self, ttl: Duration) -> RedlockResult<Lock> {
        if self.expiration < SystemTime::now() {
            return Err(RedlockError::LockExpired);
        }

        Ok(self.redlock.extend(&self.resource_name, &self.value, ttl)?)
    }
}

// Configuration of Redlock
pub struct Config<T>
    where T: redis::IntoConnectionInfo
{
    pub addrs: Vec<T>,
    pub retry_count: u32,
    pub retry_delay: Duration,
    pub retry_jitter: u32,
    pub drift_factor: f32,
}

impl Default for Config<&'static str> {
    fn default() -> Self {
        Config {
            addrs: vec!["redis://127.0.0.1"],
            retry_count: 10,
            retry_delay: Duration::from_millis(400),
            retry_jitter: 400,
            drift_factor: 0.01,
        }
    }
}

#[derive(Debug)]
pub struct Redlock {
    clients: Vec<redis::Client>,
    retry_count: u32,
    retry_delay: Duration,
    retry_jitter: u32,
    drift_factor: f32,
    quorum: usize,
}

impl Redlock {
    // Create a new redlock instance.
    pub fn new<T: redis::IntoConnectionInfo>(config: Config<T>) -> RedlockResult<Redlock> {
        if config.addrs.is_empty() {
            return Err(RedlockError::NoServerError);
        }
        let mut clients = Vec::with_capacity(config.addrs.len());
        for addr in config.addrs {
            clients.push(redis::Client::open(addr)?)
        }

        let quorum = (clients.len() as f64 / 2_f64).floor() as usize + 1;

        Ok(Redlock {
               clients: clients,
               retry_count: config.retry_count,
               retry_delay: config.retry_delay,
               retry_jitter: config.retry_jitter,
               drift_factor: config.drift_factor,
               quorum: quorum,
           })
    }

    // Locks the given resource using the Redlock algorithm.
    pub fn lock(&self, resource_name: &str, ttl: Duration) -> RedlockResult<Lock> {
        self.request(RequestInfo::Lock, resource_name, ttl)
    }

    fn extend(&self, resource_name: &str, value: &str, ttl: Duration) -> RedlockResult<Lock> {
        self.request(RequestInfo::Extend { resource_value: value },
                     resource_name,
                     ttl)
    }

    fn request(&self,
               info: RequestInfo,
               resource_name: &str,
               ttl: Duration)
               -> RedlockResult<(Lock)> {
        let mut attempts = 0;
        let drift = Duration::from_millis((self.drift_factor as f64 *
                                           util::num_milliseconds(ttl) as f64)
                                                  .round() as
                                          u64 + 2);

        'attempts: while attempts < self.retry_count {
            attempts += 1;

            // Start time of this attempt
            let start = SystemTime::now();

            let mut waitings = self.clients.len();
            let mut votes = 0;
            let mut errors = 0;

            let value: String = match info {
                RequestInfo::Lock => util::get_random_string(32),
                RequestInfo::Extend { resource_value } => String::from(resource_value),
            };

            for client in &self.clients {
                let request_result = match info {
                    RequestInfo::Lock => lock(client, resource_name, &value, ttl),
                    RequestInfo::Extend { .. } => extend(client, resource_name, &value, ttl),
                };

                let lock = Lock {
                    redlock: self,
                    resource_name: String::from(resource_name),
                    value: value.clone(),
                    expiration: start + ttl - drift,
                };

                match request_result {
                    Ok(_) => {
                        waitings -= 1;
                        if waitings > 0 {
                            continue;
                        }

                        votes += 1;
                        // suceess: aquire the lock
                        if votes >= self.quorum && lock.expiration > SystemTime::now() {
                            return Ok(lock);
                        }

                        // fail: releases all aquired locks and retry
                        lock.unlock().is_ok(); // Just ingore the result
                        thread::sleep(self.get_retry_timeout());
                        continue 'attempts;
                    }
                    Err(_) => {
                        errors += 1;
                        // This attempt is doomed to fail, will retry after
                        // the timeout
                        if errors > self.quorum {
                            lock.unlock().is_ok(); // Just ingore the result
                            thread::sleep(self.get_retry_timeout());
                            continue 'attempts;
                        }
                    }
                }
            }
        }

        // Exceed the retry count, return the error
        match info {
            RequestInfo::Lock => Err(RedlockError::UnableToLock),
            RequestInfo::Extend { .. } => Err(RedlockError::UnableToExtend),
        }
    }

    fn unlock(&self, resource_name: &str, value: &str) -> RedlockResult<()> {
        let mut attempts = 0;

        'attempts: while attempts < self.retry_count {
            attempts += 1;

            let mut waitings = self.clients.len();
            let mut votes = 0;
            let mut errors = 0;

            for client in &self.clients {
                match unlock(client, resource_name, value) {
                    Ok(_) => {
                        waitings -= 1;
                        if waitings > 0 {
                            continue;
                        }
                        votes += 1;
                        if votes >= self.quorum {
                            return Ok(());
                        }
                    }
                    Err(_) => {
                        errors += 1;
                        // This attempt is doomed to fail, will retry after
                        // the timeout
                        if errors >= self.quorum {
                            thread::sleep(self.get_retry_timeout());
                            continue 'attempts;
                        }
                    }
                }
            }
        }

        // Exceed the retry count, return the error
        Err(RedlockError::UnableToUnlock)
    }

    fn get_retry_timeout(&self) -> Duration {
        let jitter = self.retry_jitter as i32 * thread_rng().gen_range(-1, 1);
        if jitter >= 0 {
            self.retry_delay.add(Duration::from_millis(jitter as u64))
        } else {
            self.retry_delay.sub(Duration::from_millis(-jitter as u64))
        }
    }
}

fn lock(client: &redis::Client,
        resource_name: &str,
        value: &str,
        ttl: Duration)
        -> RedlockResult<()> {
    LOCK.key(String::from(resource_name))
        .arg(String::from(value))
        .arg(util::num_milliseconds(ttl))
        .invoke::<()>(&client.get_connection()?)?;

    Ok(())
}

fn unlock(client: &redis::Client, resource_name: &str, value: &str) -> RedlockResult<()> {
    UNLOCK
        .key(resource_name)
        .arg(value)
        .invoke::<()>(&client.get_connection()?)?;

    Ok(())
}

fn extend(client: &redis::Client,
          resource_name: &str,
          value: &str,
          ttl: Duration)
          -> RedlockResult<()> {
    EXTEND
        .key(resource_name)
        .arg(value)
        .arg(util::num_milliseconds(ttl))
        .invoke::<()>(&client.get_connection()?)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use redis::Commands;

    fn get_local_redis_conn() -> redis::Connection {
        redis::Client::open("redis://127.0.0.1")
            .unwrap()
            .get_connection()
            .unwrap()
    }

    #[test]
    fn test_config_default() {
        let default_config = Config::default();
        assert_eq!(default_config.addrs, vec!["redis://127.0.0.1"]);
        assert_eq!(default_config.retry_count, 10);
        assert_eq!(default_config.retry_delay, Duration::from_millis(400));
    }

    #[test]
    #[should_panic]
    fn test_new_with_no_server() {
        Redlock::new::<&str>(Config {
                                 addrs: vec![],
                                 retry_count: 10,
                                 retry_delay: Duration::from_millis(400),
                                 retry_jitter: 400,
                                 drift_factor: 0.01,
                             })
                .unwrap();
    }

    #[test]
    fn test_new() {
        let redlock = Redlock::new(Config::default()).unwrap();
        assert_eq!(redlock.clients.len(), 1);
        assert_eq!(redlock.retry_count, 10);
        assert_eq!(redlock.retry_delay, Duration::from_millis(400));
    }

    #[test]
    fn test_lock() {
        let redlock = Redlock::new(Config::default()).unwrap();
        let resource_name = "test_lock";
        let lock = redlock
            .lock(resource_name, Duration::from_millis(2000))
            .unwrap();
        assert!(lock.expiration < SystemTime::now().add(Duration::from_millis(2000)));
    }

    #[test]
    fn test_unlock() {
        let redlock = Redlock::new(Config::default()).unwrap();
        let resource_name = "test_unlock";
        let lock = redlock
            .lock(resource_name, Duration::from_millis(2000))
            .unwrap();

        let conn = get_local_redis_conn();
        let value: String = conn.get(resource_name).unwrap();
        assert_eq!(value.len(), 32);

        lock.unlock().unwrap();
        let res: Option<String> = conn.get(resource_name).unwrap();
        assert!(res.is_none());
    }

    #[test]
    fn test_extend() {
        let redlock = Redlock::new(Config::default()).unwrap();
        let resource_name = "test_extend";
        let lock = redlock
            .lock(resource_name, Duration::from_millis(2000))
            .unwrap();
        let lock_extended = lock.extend(Duration::from_millis(2000)).unwrap();

        assert!(lock_extended.expiration < SystemTime::now().add(Duration::from_millis(2000)));
    }
}