redis 2.0.0-rc.2

Redis driver for Rust.
Documentation
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use crate::Value;
use crate::caching::statistics::Statistics;
use crate::cmd::Arg;
use lru::LruCache;
use std::collections::hash_map::DefaultHasher;
use std::hash::Hasher;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;

type RedisCmd = Vec<u8>;
// Offsets marking the end of each argument in RedisCmd (relative to its start), so that argument boundaries
// are part of the cache key (`HMGET h a b` must not match `HMGET h ab`).
type RedisCmdArgs = Vec<Arg<usize>>;
type RedisKey = Vec<u8>;

/// Borrowed end offsets of each argument in a command key. Commands inside a pipeline keep
/// offsets into the pipeline's shared buffer, so `base` is where the command key starts in it.
#[derive(Clone, Copy, Debug)]
pub(crate) struct CmdArgs<'a> {
    offsets: &'a [Arg<usize>],
    base: usize,
}

impl<'a> CmdArgs<'a> {
    pub(crate) const fn new(offsets: &'a [Arg<usize>], base: usize) -> Self {
        CmdArgs { offsets, base }
    }

    fn relative(self) -> impl Iterator<Item = Arg<usize>> + 'a {
        self.offsets.iter().map(move |arg| match *arg {
            Arg::Simple(end) => Arg::Simple(end - self.base),
            Arg::Cursor => Arg::Cursor,
        })
    }

    fn matches(self, stored: &[Arg<usize>]) -> bool {
        stored.iter().cloned().eq(self.relative())
    }
}

pub(crate) struct CacheCmdEntry {
    cmd: RedisCmd,
    cmd_args: RedisCmdArgs,
    value: Value,
}

/// CacheItem keeps information about a key's expiry time and cached response for each key, command pair.
pub(crate) struct CacheItem {
    expire_time: Instant,
    epoch: usize,
    value_list: Vec<CacheCmdEntry>,
}

pub(crate) struct LRUCacheShard {
    lru: LruCache<RedisKey, CacheItem>,
    // Number of invalidations applied to this shard.
    invalidations: usize,
}

pub(crate) struct ShardedLRU {
    shards: Vec<std::sync::Mutex<LRUCacheShard>>,
    pub(crate) statistics: Arc<Statistics>,
    last_epoch: AtomicUsize,
}

impl ShardedLRU {
    const MAX_SHARD_COUNT: usize = 32;

    pub(crate) fn new(total_key_size: NonZeroUsize) -> Self {
        // If total cache size is smaller than max shard size then it won't use sharding.
        let (shard_count, shard_size) = if total_key_size.get() >= Self::MAX_SHARD_COUNT {
            (
                Self::MAX_SHARD_COUNT,
                total_key_size.get() / Self::MAX_SHARD_COUNT,
            )
        } else {
            (1, total_key_size.get())
        };

        let mut shards = Vec::with_capacity(shard_count);
        for _ in 0..shard_count {
            let shard = LRUCacheShard {
                lru: LruCache::new(NonZeroUsize::new(shard_size).unwrap()),
                invalidations: 0,
            };
            shards.push(std::sync::Mutex::new(shard));
        }
        let statistics = Arc::new(Statistics::default());
        Self {
            shards,
            statistics,
            last_epoch: AtomicUsize::new(0),
        }
    }

    /// get_shard will get MutexGuard for a shard determined by key, if lock is poisoned it'll be recovered.
    pub(crate) fn get_shard(&self, key: &[u8]) -> std::sync::MutexGuard<'_, LRUCacheShard> {
        let mut s = DefaultHasher::new();
        s.write(key);
        let lock = &self.shards[s.finish() as usize % self.shards.len()];
        lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    /// Returns the number of invalidations applied so far to the shard of `key`. It must be read
    /// before the command is sent and passed to `insert` along with the command's reply.
    pub(crate) fn invalidation_count(&self, key: &[u8]) -> usize {
        self.get_shard(key).invalidations
    }

    pub(crate) fn get<'a>(
        &self,
        redis_key: &'a [u8],
        redis_cmd: &'a [u8],
        redis_cmd_args: CmdArgs<'a>,
        epoch: usize,
    ) -> Option<Value> {
        let mut shard = self.get_shard(redis_key);
        let lru_cache = &mut shard.lru;
        if let Some(cache_item) = lru_cache.get_mut(redis_key) {
            // If one of following conditions are true, cache item is invalid and can't be trusted to use:
            // Epoch of client is not same, it means cache item is created by another redis connection.
            // Expire time of key has been passed, value could be stale.
            let cache_item_is_invalid =
                cache_item.epoch != epoch || Instant::now() > cache_item.expire_time;
            if cache_item_is_invalid {
                self.statistics
                    .increase_invalidate(cache_item.value_list.len());
                self.statistics.increase_miss(1);
                lru_cache.pop(redis_key);
                return None;
            }
            // Found redis key in cache, but KEY,CMD combination also must be in the cache otherwise, it will be fetched from server.
            for entry in &cache_item.value_list {
                if entry.cmd == redis_cmd && redis_cmd_args.matches(&entry.cmd_args) {
                    self.statistics.increase_hit(1);
                    return Some(entry.value.clone());
                }
            }
        }
        drop(shard);
        self.statistics.increase_miss(1);
        None
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn insert(
        &self,
        redis_key: &[u8],
        cmd_key: &[u8],
        cmd_args: CmdArgs<'_>,
        value: Value,
        expire_time: Instant,
        epoch: usize,
        invalidation_count: usize,
    ) {
        let mut shard = self.get_shard(redis_key);
        // The invalidation for a write made while the command was in flight can be received before
        // its reply is inserted, in which case the reply is already stale and must not be cached.
        if shard.invalidations != invalidation_count {
            return;
        }
        let lru_cache = &mut shard.lru;
        if let Some(ch) = lru_cache.peek_mut(redis_key)
            && ch.epoch == epoch
        {
            for entry in &mut ch.value_list {
                if entry.cmd == cmd_key && cmd_args.matches(&entry.cmd_args) {
                    entry.value = value;
                    ch.expire_time = expire_time;
                    return;
                }
            }
            ch.value_list.push(CacheCmdEntry {
                cmd: cmd_key.to_vec(),
                cmd_args: cmd_args.relative().collect(),
                value,
            });
            ch.expire_time = expire_time;
            return;
        }
        let _ = lru_cache.push(
            redis_key.to_vec(),
            CacheItem {
                expire_time,
                value_list: vec![CacheCmdEntry {
                    cmd: cmd_key.to_vec(),
                    cmd_args: cmd_args.relative().collect(),
                    value,
                }],
                epoch,
            },
        );
    }

    pub(crate) fn invalidate(&self, cache_key: &Vec<u8>) {
        // Use a separate binding for this to release the lock guard before calling increase_invalidate.
        let maybe_cache_holder = {
            let mut shard = self.get_shard(cache_key);
            shard.invalidations = shard.invalidations.wrapping_add(1);
            shard.lru.pop(cache_key)
        };
        if let Some(cache_holder) = maybe_cache_holder {
            self.statistics
                .increase_invalidate(cache_holder.value_list.len());
        }
    }

    pub(crate) fn invalidate_all(&self) {
        for shard in &self.shards {
            let mut lru_cache = shard
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            let invalidated = lru_cache
                .lru
                .iter()
                .map(|(_, cache_item)| cache_item.value_list.len())
                .sum();
            lru_cache.lru.clear();
            drop(lru_cache);
            self.statistics.increase_invalidate(invalidated);
        }
    }

    pub(crate) fn increase_epoch(&self) -> usize {
        self.last_epoch.fetch_add(1, Ordering::Relaxed)
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use std::ops::Add;
    use std::time::Duration;
    static CMD_KEY: &[u8] = b"test_cmd_key".as_slice();
    static CMD_KEY_2: &[u8] = b"test_cmd_key_2".as_slice();
    static CMD_ARGS: CmdArgs<'static> = CmdArgs::new(&[], 0);
    static REDIS_KEY: &[u8] = b"test_redis_key".as_slice();

    #[test]
    fn test_expire() {
        let sharded_lru = ShardedLRU::new(NonZeroUsize::new(64).unwrap());

        sharded_lru.insert(
            REDIS_KEY,
            CMD_KEY,
            CMD_ARGS,
            Value::Boolean(true),
            Instant::now().add(Duration::from_secs(10)),
            0,
            0,
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            Some(Value::Boolean(true))
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY_2, CMD_ARGS, 0),
            None,
            "Using different cmd key must result in cache miss"
        );

        sharded_lru.insert(
            REDIS_KEY,
            CMD_KEY,
            CMD_ARGS,
            Value::Boolean(false),
            Instant::now().add(Duration::from_millis(5)),
            0,
            0,
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            Some(Value::Boolean(false)),
            "Old value must be overwritten"
        );
        std::thread::sleep(Duration::from_millis(6));
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            None,
            "Cache must be expired"
        );
    }

    #[test]
    fn test_different_cmd_keys() {
        let sharded_lru = ShardedLRU::new(NonZeroUsize::new(64).unwrap());

        sharded_lru.insert(
            REDIS_KEY,
            CMD_KEY,
            CMD_ARGS,
            Value::Int(1),
            Instant::now().add(Duration::from_secs(10)),
            0,
            0,
        );
        // Second insert must override expire of the redis key.
        sharded_lru.insert(
            REDIS_KEY,
            CMD_KEY_2,
            CMD_ARGS,
            Value::Int(2),
            Instant::now().add(Duration::from_millis(5)),
            0,
            0,
        );

        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            Some(Value::Int(1))
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY_2, CMD_ARGS, 0),
            Some(Value::Int(2))
        );

        std::thread::sleep(Duration::from_millis(6));
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            None,
            "Cache must be expired"
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY_2, CMD_ARGS, 0),
            None,
            "Cache must be expired"
        );
    }

    #[test]
    fn test_invalidate() {
        let sharded_lru = ShardedLRU::new(NonZeroUsize::new(64).unwrap());

        sharded_lru.insert(
            REDIS_KEY,
            CMD_KEY,
            CMD_ARGS,
            Value::Boolean(true),
            Instant::now().add(Duration::from_secs(10)),
            0,
            0,
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            Some(Value::Boolean(true))
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY_2, CMD_ARGS, 0),
            None,
            "Using different cmd key must result in cache miss"
        );

        sharded_lru.invalidate(&REDIS_KEY.to_vec());
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            None,
            "Cache must be invalidated"
        );
    }

    #[test]
    fn test_insert_is_ignored_after_invalidation() {
        let sharded_lru = ShardedLRU::new(NonZeroUsize::new(64).unwrap());

        let invalidation_count = sharded_lru.invalidation_count(REDIS_KEY);
        // The invalidation is received while the command is in flight, before its reply is inserted.
        sharded_lru.invalidate(&REDIS_KEY.to_vec());
        sharded_lru.insert(
            REDIS_KEY,
            CMD_KEY,
            CMD_ARGS,
            Value::Boolean(true),
            Instant::now().add(Duration::from_secs(10)),
            0,
            invalidation_count,
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            None,
            "Reply must not be cached"
        );

        let invalidation_count = sharded_lru.invalidation_count(REDIS_KEY);
        sharded_lru.insert(
            REDIS_KEY,
            CMD_KEY,
            CMD_ARGS,
            Value::Boolean(true),
            Instant::now().add(Duration::from_secs(10)),
            0,
            invalidation_count,
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            Some(Value::Boolean(true))
        );
    }

    #[test]
    fn test_epoch_change() {
        let sharded_lru = ShardedLRU::new(NonZeroUsize::new(64).unwrap());

        let another_key = "foobar";

        sharded_lru.insert(
            REDIS_KEY,
            CMD_KEY,
            CMD_ARGS,
            Value::Boolean(true),
            Instant::now().add(Duration::from_secs(10)),
            0,
            0,
        );
        sharded_lru.insert(
            another_key.as_bytes(),
            CMD_KEY,
            CMD_ARGS,
            Value::Boolean(true),
            Instant::now().add(Duration::from_secs(10)),
            0,
            0,
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 0),
            Some(Value::Boolean(true))
        );
        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY_2, CMD_ARGS, 0),
            None,
            "Using different cmd key must result in cache miss"
        );

        assert_eq!(
            sharded_lru.get(REDIS_KEY, CMD_KEY, CMD_ARGS, 1),
            None,
            "Cache must be invalidated"
        );
        assert_eq!(
            sharded_lru.get(another_key.as_bytes(), CMD_KEY, CMD_ARGS, 1),
            None,
            "Cache must be invalidated"
        );
    }
}