Rust

Cache

Key-value caching with expiring entries over memory, files, Redis, Redis Cluster, Memcached and Hazelcast, with sharding, pooling, circuit breaking and purge-safe leases.
Rust 5,238 lines (3,557 code)split
PartCodeCommentsBlankTotalFiles
Rust source3,5571,1994825,23820
Rust tests60136667037

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-cache = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with Cache, each a complete program you can copy and run.

A cache keeps the results of expensive work (a database read, a rendered page, a remote call) under a key, so the next request can reuse them. This library gives every backend the same small API: save a value, load it back while it is younger than a TTL, touch it to make it fresh again, and purge it when the source changes. Backends are adapters: memory, files, Redis (plain, multiplexed, cluster), Memcached and Hazelcast, and adapters that combine others. The cache is async, so the examples run it on a Tokio runtime. This guide covers the common tasks.

Cache a value for a while

Wrap an adapter in a Cache, then save and load values. A load takes a TTL in seconds: an entry saved longer ago than that is a miss (None). Values are PHP values (php_std::types::Value): strings, numbers, arrays.

Rust
use php_std::types::Value;
use utopia_cache::{Cache, Memory};

let cache = Cache::new(Memory::new());

tokio::runtime::Runtime::new()?.block_on(async {
    assert!(cache.save("greeting", &Value::from("hello"), "", 0).await?);
    assert_eq!(cache.load("greeting", 60, "").await?, Some(Value::from("hello")));

    // A TTL of 0 means "older than now": a miss.
    assert_eq!(cache.load("greeting", 0, "").await?, None);
    Ok::<_, utopia_cache::Error>(())
})?;

Purge an entry when its source changes

purge removes an entry; the next load misses and the caller rebuilds it. Keys are case-insensitive unless you ask otherwise, so User:1 and user:1 are the same entry.

Rust
use php_std::types::Value;
use utopia_cache::{Cache, Memory};

let cache = Cache::new(Memory::new());

tokio::runtime::Runtime::new()?.block_on(async {
    cache.save("User:1", &Value::from("Ada"), "", 0).await?;
    assert!(cache.purge("user:1", "").await?);
    assert_eq!(cache.load("User:1", 60, "").await?, None);

    cache.set_case_sensitivity(true);
    cache.save("Color", &Value::from("pink"), "", 0).await?;
    assert_eq!(cache.load("color", 60, "").await?, None);
    Ok::<_, utopia_cache::Error>(())
})?;

Keep entries on disk

Filesystem stores one file per key under a directory; keys with / become subdirectories. The size of this cache is the bytes it holds.

Rust
use php_std::types::Value;
use utopia_cache::{Cache, Filesystem};

let dir = std::env::temp_dir().join(format!("utopia-cache-guide-{}", std::process::id()));
let cache = Cache::new(Filesystem::new(&dir));

tokio::runtime::Runtime::new()?.block_on(async {
    cache.save("pages/home", &Value::from("<h1>Home</h1>"), "", 0).await?;
    assert_eq!(cache.load("pages/home", 3600, "").await?, Some(Value::from("<h1>Home</h1>")));
    assert_eq!(cache.size().await?, 13);
    Ok::<_, utopia_cache::Error>(())
})?;
std::fs::remove_dir_all(&dir)?;

Cache Rust-only data natively

A cache shared with a PHP runtime keeps PHP's codec; a cache only Rust reads uses the native codec. save_native and load_native store any serde type as a compact binary entry, with the same TTL, leases and purges as other entries, and without building PHP values. Keep such entries in fields PHP never reads (a purge of the key still drops them), and change the field when the type changes: the format carries no field names.

The native format is postcard behind a three-byte header (0xF5, N, the format version) and the save time. Postcard was picked on numbers: on a user document it encodes about six times and decodes about twice as fast as PHP's igbinary, and its entries are smaller. It is maintained, pure Rust, has a documented stable wire format, and fails cleanly on truncated or hostile input: every length is checked against the bytes left, so a corrupt entry is a miss, never a panic or an oversized allocation. bincode is no longer maintained, bitcode's derive cannot encode recursive types such as JSON trees, and rkyv needs its own derives and an aligned copy of each entry before reading it.

Rust
use serde::{Deserialize, Serialize};
use utopia_cache::{Cache, Memory};

#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct Events {
    names: Vec<String>,
}

let cache = Cache::new(Memory::new());

tokio::runtime::Runtime::new()?.block_on(async {
    let events = Events { names: vec!["users.*.create".into()] };
    let generation = cache.generation("project:1").await?;
    assert!(cache.save_native_with_lease("project:1", &events, "rust:events:v1", &generation).await?);
    assert_eq!(cache.load_native::<Events>("project:1", 3600, "rust:events:v1").await?, Some(events));
    Ok::<_, utopia_cache::Error>(())
})?;

Store several fields under one key

Hash-based adapters keep many fields under one key. save_many writes them in one round trip and load_many reads some or all of them; a TTL greater than 0 also gives the whole key an expiry.

Rust
use php_std::types::Value;
use utopia_cache::{Cache, Fields, Redis};

tokio::runtime::Runtime::new()?.block_on(async {
    let client = redis::Client::open("redis://localhost:6379")?;
    let cache = Cache::new(Redis::new(client.get_connection_manager().await?));

    let mut topics = Fields::new();
    topics.insert("topica".into(), Value::Int(5));
    topics.insert("topicb".into(), Value::Int(9));
    cache.save_many("guide:sequences", &topics, 300).await?;

    let some = cache.load_many("guide:sequences", 3600, &["topica", "missing"]).await?;
    assert_eq!(some.len(), 1);
    cache.purge("guide:sequences", "").await?;
    Ok::<_, Box<dyn std::error::Error>>(())
})?;
Compiles in CI; needs a running service to execute.

Refuse stale writes after a purge

A reader that loads from the database while a writer purges the cache could put the old row back. Read the key's generation before the database read and save with save_with_lease: the save is refused when a purge happened in between.

Rust
use php_std::types::Value;
use utopia_cache::{Cache, Redis};

tokio::runtime::Runtime::new()?.block_on(async {
    let client = redis::Client::open("redis://localhost:6379")?;
    let cache = Cache::new(Redis::new(client.get_connection_manager().await?));

    let generation = cache.generation("guide:doc").await?;
    // ... read the document from the database, while a writer purges it ...
    cache.purge("guide:doc", "").await?;
    assert!(!cache.save_with_lease("guide:doc", &Value::from("stale"), "", &generation).await?);
    Ok::<_, Box<dyn std::error::Error>>(())
})?;
Compiles in CI; needs a running service to execute.

Spread keys over several backends

Sharding picks one adapter per key from a hash of the key, so each key always lives on the same shard. Flushes and sizes cover every shard.

Rust
use php_std::types::Value;
use utopia_cache::{Cache, Memory, Sharding};

let cache = Cache::new(Sharding::new(vec![Memory::new(), Memory::new()])?);

tokio::runtime::Runtime::new()?.block_on(async {
    for key in ["a", "b", "c"] {
        cache.save(key, &Value::from(key), "", 0).await?;
    }
    assert_eq!(cache.size().await?, 3);
    Ok::<_, utopia_cache::Error>(())
})?;

Keep serving when the cache is down

A CircuitBreaker adapter turns failures of the backend into misses and false, and stops calling a backend that keeps failing until it recovers. The circuit's settings decide how many failures open it.

Rust
use php_std::types::Value;
use utopia_cache::{Cache, CircuitBreaker, Memory};
use utopia_circuit_breaker::{CircuitBreaker as Breaker, Options};

let breaker = Breaker::new(Options { minimum_throughput: 5, ..Options::default() })?;
let cache = Cache::new(CircuitBreaker::new(Memory::new(), breaker));

tokio::runtime::Runtime::new()?.block_on(async {
    cache.save("key", &Value::from("value"), "", 0).await?;
    assert_eq!(cache.load("key", 60, "").await?, Some(Value::from("value")));
    Ok::<_, utopia_cache::Error>(())
})?;

Read the stored format

The hash-based adapters store an envelope: the value and the time it was written, encoded as JSON by default or igbinary. Envelope encodes and checks them directly, with the clock passed in.

Rust
use php_std::types::Value;
use utopia_cache::{Envelope, Igbinary, Json};

let json = Envelope::new(Json);
let stored = json.encode(&Value::from("hello"), 100)?;
assert_eq!(stored, br#"{"time":100,"data":"hello"}"#);
assert_eq!(json.decode(&stored, 60, 159), Some(Value::from("hello")));
assert_eq!(json.decode(&stored, 60, 160), None);

// Another codec's bytes are a miss, never an error.
assert_eq!(Envelope::new(Igbinary).decode(&stored, 60, 130), None);

Reference#

Caching with expiring entries.

A Cache stores values under keys through an [Adapter]: in process (Memory), on disk (Filesystem), in Redis (Redis, Multiplexing, RedisCluster) or Memcached (Memcached, Hazelcast). Adapters compose: Sharding spreads keys over several, Pool borrows one per operation, CircuitBreaker falls back while a backend fails. Every load takes a TTL: an entry older than it is a miss.

Values are php_std::types::Values: the Redis-protocol and Hazelcast adapters store them in an Envelope encoded with a Codec (Json by default, or Igbinary). Leases (lease) keep a stale reader from re-caching data a concurrent writer just purged.

A load returns None on a miss; a save returns whether it stored.

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

adapterinternal
`Adapter`: where a cache keeps its entries, and the dynamic form `DynAdapter` for adapters chosen at run time.
breakerinternal
`CircuitBreaker`: an adapter whose failures fall back instead of failing, behind a `utopia_circuit_breaker::CircuitBreaker` that stops calling a failing backend.
cacheinternal
`Cache`: the facade over an `Adapter`.
codecinternal
`Codec`: how a cache value becomes the bytes an adapter stores.
envelopeinternal
`Envelope`: the timestamped record the hash-based adapters store.
errorinternal
The errors cache operations fail with.
fastlzinternal
FastLZ (0.1), the compression the Memcached extension applies to large values: level 1 below 64 KiB, level 2 above, byte for byte.
filesysteminternal
`Filesystem`: one file per key under a directory.
lease7 items
Generation leases and purge tombstones, shared by the Redis-protocol adapters (`crate::Redis`, `crate::Multiplexing`).
memcachedinternal
Cache adapters over the Memcached text protocol: `Memcached` and `Hazelcast`.
memoryinternal
`Memory` and `None`: in-process adapters.
multiplexinginternal
`Multiplexing`: many tasks over one Redis connection.
nativeinternal
`Native`: the codec of entries only Rust reads and writes.
noneinternal
`None`: the adapter that stores nothing.
poolinternal
`Pool`: every operation on an adapter borrowed from a `utopia_pools::Pool`.
redis_adapterinternal
`Redis`: entries as fields of Redis hashes, over a redis-rs connection.
redis_clusterinternal
`RedisCluster`: entries as fields of hashes in a Redis Cluster.
resp6 items
RESP2, the Redis wire protocol: commands out (`encode`), replies in (`parse`), and server errors raised (`unwrap`).
shardinginternal
`Sharding`: keys spread over several adapters.

API#

What utopia_cache exports at its root.

Structs

CacheThe cache: keys (lower-cased unless case-sensitive), an `Adapter` that stores the entries, and metrics on every operation (`cache.operation.duration`, and `cache.load.total` by hit or miss).CircuitBreakerAn adapter behind a circuit breaker: while the backend fails, operations return a fallback (a miss, `false`, an empty list, `0`) instead of an error, and an open circuit skips the backend entirely.EnvelopeThe `{"time": <unix>, "data": <value>}` record the Redis, Redis Cluster and Hazelcast adapters store, run through a `Codec`. Encoding adds the timestamp; decoding enforces the TTL against a caller-supplied `now`.FilesystemOne file per key under a directory: the file's content is the value (strings as they are, arrays as their items' strings joined) and its modification time is the entry's timestamp. Keys containing `/` live in subdirectories. Hashes are ignored.HazelcastEntries in Hazelcast through its Memcached endpoint: one item per key holding an `Envelope` (JSON by default), as the Redis adapters store it. Hazelcast cannot flush, so `Adapter::flush` returns `false`.IgbinaryBinary igbinary payloads: smaller and faster than JSON, and a lossless round trip for every value, including empty objects.JsonJSON, the format every adapter has always written.MemcachedEntries in Memcached: one item per key holding the entry's data and the time it was written. Hashes are ignored.MemcachedClientA connection to one Memcached-protocol server (Memcached, or Hazelcast with its Memcached endpoint), reconnecting after a failure.MemoryEntries in this process, gone when it exits. Hashes are ignored: one entry per key.MultiplexingMany tasks sharing one Redis connection: each command is queued and written under a send lock, so the queue's order is the wire order, and one reader task hands every reply to the next caller in the queue (Redis answers in order). Entries are stored like `crate::Redis` stores them, with the same leases.MultiplexingOptionsSettings of a `Multiplexing` connection; defaults in parentheses.NativeTyped Rust values as compact binary entries, for caches only Rust reads and writes.NoneStores nothing: every load misses, every save fails, purges and flushes succeed.PoolRuns every operation on an adapter borrowed from a `utopia_pools::Pool`, returning it afterwards (or discarding it when the operation failed), so concurrent tasks never share one connection.RedisEntries as fields of Redis hashes: `key` names the hash and `hash` the field (the key itself by default), each value an `Envelope`. Supports batches of fields, generation leases (`crate::lease`) and retries of commands that failed on the connection.RedisClusterEntries as fields of hashes in a Redis Cluster, stored like `crate::Redis` stores them (an `Envelope` per field) but without leases or reserved fields. Flush, ping and size cover every primary.RetryRetries of a networked adapter: how many times a command that failed on the connection is retried, and the pause between attempts.ShardingSpreads keys over several adapters: `crc32(key) % shards` picks the one that stores a key, so each key always lives on the same shard until the shard list changes (adding a shard moves keys, and the hit rate drops until they are cached again). Flush, ping and size cover every shard.