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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
// Copyright 2018 Stefan Kroboth
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

//! Macros for persistently caching function calls
//!
//! The values are cached either in files or on Redis. Three storages, `FileStorage`,
//! `FileMemoryStorage` and `RedisStorage` are provided.
//! Caching is performed based on the function name and function parameters, meaning that for every
//! combination of function and parameters, the returned value is stored in a storage. Subsequent
//! calls of this function with the same parameters are not computed, but instead fetched from the
//! storage. This can lead to an decrease in computing time in case the function call is
//! computationally more expensive than fetching the value from the storage. The storages are
//! persistent (stored on disk) and can be shared between different threads and processes.
//! All parameters of the function to be cached need to be Hashable. The return value needs to be
//! serializeable by the crate `bincode`.
//!
//! There are two different ways of caching:
//!
//! 1) Caching individual function calls with the `cache!` macro. This way the function can still
//!    be used without caching if necessary.
//! 2) Caching every function call. For this, either the `cache_func!` macro or a procedural macro
//!    can be used. The latter is achieved with the compiler directive `#[persistent_cache]` of the
//!    subcrate `persistentcache_procmacro`.
//!
//! # Setup
//!
//! Add the following dependencies to your project:
//!
//! ```text
//! [dependencies]
//! lazy_static = "*"
//! persistentcache = "*"
//! persistentcache_procmacro = "*"  # Only needed for `#[peristent_cache]`
//! ```
//!
//! # Caching a function with `#[persistent_cache]`
//!
//! The easiest way to cache all calls to a function is by preceding it with the
//! `#[persistent_cache]` directive. This modifies the function such that values never computed
//! before are computed and cached in a storage. Already computed values are fetched from said
//! storage without computing. The return type needs to implement the `Serializable` trait.
//!
//! ## Example
//!
//! ```
//! #![feature(proc_macro)]
//! #![feature(proc_macro_gen)]
//! #[macro_use]
//! extern crate lazy_static;
//! #[macro_use]
//! extern crate persistentcache;
//! extern crate persistentcache_procmacro;
//! use persistentcache::*;
//! use persistentcache::storage::{FileStorage, FileMemoryStorage, RedisStorage};
//! use persistentcache_procmacro::persistent_cache;
//!
//! // Either store it in a `FileStorage`...
//! #[persistent_cache]
//! #[params(FileStorage, "test_dir")]
//! fn add_two_file(a: u64) -> u64 {
//!     println!("Calculating {} + 2...", a);
//!     a + 2
//! }
//!
//! // ... or in a `RedisStorage` ...
//! #[persistent_cache]
//! #[params(RedisStorage, "redis://127.0.0.1")]
//! fn add_two_redis(a: u64) -> u64 {
//!     println!("Calculating {} + 2...", a);
//!     a + 2
//! }
//!
//! // ... or in a `FileMemoryStorage` ...
//! #[persistent_cache]
//! #[params(FileMemoryStorage, "test_dir_mem")]
//! fn add_two_file_memory(a: u64) -> u64 {
//!     println!("Calculating {} + 2...", a);
//!     a + 2
//! }
//!
//! fn main() {
//!     // Function is called and will print "Calculating 2 + 2..." and "4"
//!     println!("{}", add_two_file(2));
//!     // Value will be cached from Redis, will only print "4"
//!     println!("{}", add_two_file(2));
//!     // Function is called and will print "Calculating 3 + 2..." and "5"
//!     println!("{}", add_two_redis(3));
//!     // Value will be cached from Redis, will only print "5"
//!     println!("{}", add_two_redis(3));
//!     // Function is called and will print "Calculating 4 + 2..." and "6"
//!     println!("{}", add_two_file_memory(4));
//!     // Value will be cached from Redis, will only print "6"
//!     println!("{}", add_two_file_memory(4));
//! }
//! ```
//!
//! This will print:
//!
//! ```text
//! Calculating 2 + 2...
//! 4
//! 4
//! Calculating 3 + 2...
//! 5
//! 5
//! ```
//!
//! # Caching a function with `cache_func!`
//!
//! The macro `cache_func!` is wrapped around a function definition and modifies the function such
//! that the function body is executed and the resulting value is both returned and stored in a
//! provided storage in case the given combination of parameters hasn't been evaluated before.
//! Subsequent calls to the function with already evaluated parameters are then fetched from the
//! storage.
//! The advantage of this approach over `cache!` is that the function is modified and hence every
//! call to the function will automatically take care of the caching. Furthermore it works with
//! recursive calls. However, caching cannot be disabled anymore.
//! The return value needs to implemend the `Serializable` trait.
//!
//! ## Example
//!
//! ```
//! #[macro_use] extern crate lazy_static;
//! #[macro_use] extern crate persistentcache;
//! use persistentcache::*;
//!
//! // Either store it in a `FileStorage`...
//! cache_func!(File, "test_dir",
//! fn add_two_file(a: u64) -> u64 {
//!     println!("Calculating {} + 2...", a);
//!     a + 2
//! });
//!
//! // ... or in a `RedisStorage`
//! cache_func!(Redis, "redis://127.0.0.1",
//! fn add_two_redis(a: u64) -> u64 {
//!     println!("Calculating {} + 2...", a);
//!     a + 2
//! });
//!
//! fn main() {
//!     // Function is called and will print "Calculating 2 + 2..." and "4"
//!     println!("{}", add_two_file(2));
//!     // Value will be cached from Redis, will only print "4"
//!     println!("{}", add_two_file(2));
//!     // Function is called and will print "Calculating 3 + 2..." and "5"
//!     println!("{}", add_two_redis(3));
//!     // Value will be cached from Redis, will only print "5"
//!     println!("{}", add_two_redis(3));
//! }
//! ```
//!
//! This will print:
//!
//! ```text
//! Calculating 2 + 2...
//! 4
//! 4
//! Calculating 3 + 2...
//! 5
//! 5
//! ```
//!
//!
//! # Caching function calls with `cache!`
//!
//! The macro `cache!` caches a function call. The advantage of this approach over the macro
//! `cache_func!` and the procedual macro `#[peristent_cache]` is that different storages can be
//! used for different calls. Furthermore the function can still be called without caching if
//! desired.
//! However, in case of recursive functions, this will most likely not work as expected because the
//! recursive calls will not be cached.
//! The macro expects the function to return a value of type `Result<T, Box<std::error::Error>>`.
//!
//! ## Example
//!
//! ```
//! #![allow(redundant_closure_call)]
//! #[macro_use]
//! extern crate persistentcache;
//! use persistentcache::*;
//!
//! fn add_two(a: u64) -> u64 {
//!     println!("Calculating {} + 2...", a);
//!     a + 2
//! }
//!
//! fn main() {
//!     let mut s = storage::redis::RedisStorage::new("redis://127.0.0.1").unwrap();
//!     // Function is called and will print "Calculating 2 + 2..." and "4"
//!     println!("{}", cache!(s, add_two(2)));
//!     // Value will be cached from Redis, will only print "4"
//!     println!("{}", cache!(s, add_two(2)));
//!     // Function is called and will print "Calculating 3 + 2..." and "5"
//!     println!("{}", cache!(s, add_two(3)));
//!     // Value will be cached from Redis, will only print "5"
//!     println!("{}", cache!(s, add_two(3)));
//! }
//! ```
//!
//! This will print:
//!
//! ```text
//! Calculating 2 + 2...
//! 4
//! 4
//! Calculating 3 + 2...
//! 5
//! 5
//! ```
//!
//!
//! # Implementing other storages
//!
//! Storages need to implement the `PersistentCache` trait.
//!
//! # Running the tests
//!
//! The tests should be run in a single thread because the Storages are regularly flushed.
//!
//! ```bash
//! cargo test -- --test-threads=1
//! ```
//!
//! A Redis server needs to be running and listening at `127.0.0.1` for the tests to work.
//!
//! # History
//!
//! This crate is inspired by [owls-cache](https://github.com/havoc-io/owls-cache) and its primary
//! goal is to teach myself Rust. While working on it, I realised that a similar crate already
//! exists: [cached-rs](https://github.com/jaemk/cached). I've borrowed a couple of ideas from
//! there.  I suggest you have a look at the cached-rs crate, too.  Unfortunately it lacks the
//! 'persistent' part and the caches cannot be shared between processes/threads, but it should be
//! fairly easy to extend it. Furthermore, the excellent
//! [accel](https://github.com/termoshtt/accell) has been very helpful. I shamelessly copied parts
//! of it for the `persistentcache_procmacro` crate.
//!
#![recursion_limit = "1024"]
#![allow(unused_imports)]
#![warn(missing_docs)]
#![feature(proc_macro)]
#![feature(proc_macro_gen)]
#[macro_use]
extern crate error_chain;
extern crate fs2;
#[macro_use]
extern crate lazy_static;
extern crate persistentcache_procmacro;
extern crate redis;
extern crate regex;

use persistentcache_procmacro::persistent_cache;

mod errors {
    error_chain!{
        foreign_links {
            Redis(::redis::RedisError);
            Regex(::regex::Error);
            IO(::std::io::Error);
        }
    }
}

use errors::*;

#[macro_use]
pub mod persistentcache;
pub mod storage;

/// Every stored variable is prefixed by this string. Currently, the flush functions depend on this
/// in order to decide which variable to flush from the storage. Keeping track of the used variable
/// internally is not an option because they are persistent and may come from another process.
pub const PREFIX: &str = "pc";

/// Traits which need to be implemented by any storage
pub trait PersistentCache {
    /// Return serialized value of variable
    fn get(&mut self, &str) -> Result<Vec<u8>>;
    /// Set serialized value of variable
    fn set(&mut self, &str, &[u8]) -> Result<()>;
    /// Flush storage
    fn flush(&mut self) -> Result<()>;
}

#[cfg(test)]
mod tests {
    extern crate num;
    use self::num::{Num, NumCast};
    use super::*;
    use persistentcache_procmacro::persistent_cache;
    use std;
    use storage::{FileMemoryStorage, FileStorage, RedisStorage};

    fn test_func_1<T: Num + NumCast>(a: T, counter: &mut i64) -> T {
        *counter += 1;
        let ten: T = NumCast::from(10_i64).unwrap();
        a * ten
    }

    fn test_func_2<T: Num>(a: T, b: T, counter: &mut i64) -> T {
        *counter += 1;
        a * b
    }

    fn test_func_3<T: Copy>(a: &[T], counter: &mut i64) -> Vec<T> {
        *counter += 1;
        vec![a[1], a[0]]
    }

    fn panic() -> () {
        panic!("nothing");
    }

    #[test]
    fn test_fib() {
        let mut s = RedisStorage::new("redis://127.0.0.1").unwrap();
        s.flush().unwrap();
        cache_func!(
            Redis,
            "redis://127.0.0.1",
            fn fib(n: u64) -> u64 {
                if n == 0 || n == 1 {
                    return n;
                }
                fib(n - 1) + fib(n - 2)
            }
        );
        assert_eq!(fib(10), 55);
        s.flush().unwrap();
    }

    #[test]
    fn test_func() {
        let mut s = FileStorage::new("file_test").unwrap();
        s.flush().unwrap();
        cache_func!(
            File,
            "test",
            fn add_two(n: u64) -> u64 {
                n + 2
            }
        );
        assert_eq!(12, add_two(10));
        s.flush().unwrap();
    }

    #[test]
    fn test_func_procmacro() {
        let mut s = FileStorage::new("file_test").unwrap();
        s.flush().unwrap();

        #[persistent_cache]
        #[params(FileStorage, "file_test")]
        fn add_two(n: u64) -> u64 {
            n + 2
        }

        assert_eq!(12, add_two(10));
        s.flush().unwrap();
    }

    #[test]
    fn test_func_procmacro2() {
        let mut s = FileStorage::new("file_test").unwrap();
        s.flush().unwrap();
        let mut counter: i64 = 0;

        #[persistent_cache]
        #[params(FileStorage, "file_test")]
        fn test_func_proc(a: &Vec<i64>, counter: &mut i64) -> Vec<i64> {
            *counter += 1;
            vec![a[1], a[0]]
        }

        assert_eq!(vec![1, 2], test_func_proc(&vec![2, 1], &mut counter));
        assert_eq!(counter, 1);
        assert_eq!(vec![1, 2], test_func_proc(&vec![2, 1], &mut counter));
        assert_eq!(counter, 2);
        s.flush().unwrap();
    }

    #[test]
    fn test_func_procmacro3() {
        let mut s = FileMemoryStorage::new("file_test").unwrap();
        s.flush().unwrap();
        let mut counter: i64 = 0;

        #[persistent_cache]
        #[params(FileMemoryStorage, "file_test")]
        fn test_func_proc(a: &Vec<i64>, counter: &mut i64) -> Vec<i64> {
            *counter += 1;
            vec![a[1], a[0]]
        }

        assert_eq!(vec![1, 2], test_func_proc(&vec![2, 1], &mut counter));
        assert_eq!(counter, 1);
        assert_eq!(vec![1, 2], test_func_proc(&vec![2, 1], &mut counter));
        assert_eq!(counter, 2);
        s.flush().unwrap();
    }

    #[test]
    fn test_redis_storage() {
        let a: i64 = 6;
        let mut counter: i64 = 0;
        let mut s = RedisStorage::new("redis://127.0.0.1").unwrap();
        s.flush().unwrap();
        assert_eq!(a * 10, test_func_1(a, &mut counter));
        assert_eq!(counter, 1);
        assert_eq!(a * 10, cache!(s, test_func_1(a, &mut counter)));
        assert_eq!(counter, 2);
        let mut counter: i64 = 1;
        assert_eq!(a * 10, cache!(s, test_func_1(a, &mut counter)));
        assert_eq!(counter, 1);
        s.flush().unwrap();
    }

    #[test]
    fn test_file_storage() {
        let a: i64 = 6;
        let mut counter: i64 = 0;
        let mut s = FileStorage::new("file_test").unwrap();
        s.flush().unwrap();
        assert_eq!(a * 10, test_func_1(a, &mut counter));
        assert_eq!(counter, 1);
        assert_eq!(a * 10, cache!(s, test_func_1(a, &mut counter)));
        assert_eq!(counter, 2);
        let mut counter: i64 = 1;
        assert_eq!(a * 10, cache!(s, test_func_1(a, &mut counter)));
        assert_eq!(counter, 1);
        s.flush().unwrap();
    }

    #[test]
    fn test_hashing() {
        // swapping the indices should change the hashes!
        let a: i64 = 6;
        let b: i64 = 2;
        let mut counter: i64 = 0;
        let mut s = FileStorage::new("file_test").unwrap();
        s.flush().unwrap();
        assert_eq!(a * b, cache!(s, test_func_2(a, b, &mut counter)));
        assert_eq!(counter, 1);
        let mut counter: i64 = 0;
        assert_eq!(a * b, cache!(s, test_func_2(b, a, &mut counter)));
        assert_eq!(counter, 1);
    }

    #[test]
    fn test_vectors() {
        let a: Vec<i64> = vec![1, 2, 3];
        let mut counter: i64 = 0;
        let mut s = FileStorage::new("file_test").unwrap();
        s.flush().unwrap();
        assert_eq!(vec![2, 1], test_func_3(&a, &mut counter));
        assert_eq!(counter, 1);
        assert_eq!(vec![2, 1], cache!(s, test_func_3(&a, &mut counter)));
        assert_eq!(counter, 2);
        let mut counter: i64 = 1;
        assert_eq!(vec![2, 1], cache!(s, test_func_3(&a, &mut counter)));
        assert_eq!(counter, 1);
        s.flush().unwrap();
    }

    #[test]
    #[should_panic]
    fn failing_function() {
        let mut s = FileStorage::new("file_test").unwrap();
        s.flush().unwrap();
        cache!(s, panic());
    }
}