Crate persistentcache [] [src]

Macros for persistently caching function calls

The values are cached either in files or on Redis. Two storages, FileStorage 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 to the function need to be Hashable. The return value needs to be serializeable by the crate bincode.

Setup

Add the following dependencies to your projet:

[dependencies]
lazy_static = "*"
bincode = "*"
persistentcache = "*"

Caching function calls with cache!

The macro cache! caches a function call. The advantage of this approach over the macro cache_func 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)]
extern crate bincode;
#[macro_use] extern crate persistentcache;
use persistentcache::*;

fn add_two(a: u64) -> Result<u64, Box<std::error::Error>> {
    println!("Calculating {} + 2...", a);
    Ok(a + 2)
}

fn main() {
    let 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)).unwrap());
    // Value will be cached from Redis, will only print "4"
    println!("{}", cache!(s, add_two(2)).unwrap());
    // Function is called and will print "Calculating 3 + 2..." and "5"
    println!("{}", cache!(s, add_two(3)).unwrap());
    // Value will be cached from Redis, will only print "5"
    println!("{}", cache!(s, add_two(3)).unwrap());
}

This will print:

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 'turned off' anymore. No assumption about the return type are made in this case. The function returns the same type as the initial function definition.

Example

#[macro_use] extern crate lazy_static;
#[macro_use] extern crate persistentcache;
extern crate bincode;
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!("{}", s, add_two_file(2));
    // Value will be cached from Redis, will only print "4"
    println!("{}", s, add_two_file(2));
    // Function is called and will print "Calculating 3 + 2..." and "5"
    println!("{}", s, add_two_redis(3));
    // Value will be cached from Redis, will only print "5"
    println!("{}", s, add_two_redis(3));*/
}

This will print:

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.

cargo test --features clippy -- --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 and its primary goal is to teach myself Rust. While working on it, I realised that a similar crate already exists: cached-rs. I've borrowed a couple of ideas from there. Have a look at it, it looks much more professional than this crate and almost certainly has better developers. Unfortunately it lacks the 'persistent' part and the caches cannot be shared between processes/threads, but it should be fairly easy to extend it.

Modules

persistentcache

Implementation of the macros cache! and cache_func!.

storage

Implementation of different persistent storages. Currently on disk (FileStorage) and in Redis (RedisStorage).

Macros

cache

Cache a single function call.

cache_func

Cache an entire function.

Constants

PREFIX

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.

Traits

PersistentCache

Traits which need to be implemented by any storage