Skip to main content

Crate feuer

Crate feuer 

Source
Expand description

Feuer — cost-aware tiered cache, with a flaming horse logo

Feuer caches immutable objects in memory and on disk.

On a cache miss, it calls your function to fetch or compute the object. Eviction considers how often an object is requested, its size, and the cost of fetching it again.

§Quick start

Create a memory-only cache and fetch an object. This example runs on every supported platform. Replace the callback body with your application’s source access.

use std::convert::Infallible;
use bytes::Bytes;
use feuer::Cache;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cache = Cache::builder()
        .memory_capacity(64 * 1024 * 1024)
        .open()?;

    let bytes = cache
        .get_or_fetch("object-v1", || async {
            Ok::<_, Infallible>(Bytes::from_static(b"hello world"))
        })
        .await?;

    assert_eq!(bytes.as_ref(), b"hello world");
    Ok(())
}

Capacities are in bytes. Memory capacity must be positive. Disk caching is disabled until you set a nonzero disk_capacity. The disk Cargo feature is enabled by default. Set default-features = false on your feuer dependency to exclude disk storage entirely, including on Linux.

§How lookups work

Cache::get_or_fetch checks memory first, then disk when enabled. A disk hit is checksum-verified and promoted to memory. On a miss, Feuer calls your callback, caches the result in memory, and queues a disk write when disk caching is enabled.

Use Cache::get to check the cache without fetching from the source. Use Cache::insert to supply immutable bytes synchronously without a lookup or runtime. It inserts into memory and attempts a best-effort disk write enqueue. Cloning a Cache shares its contents and in-flight work, so handles can be used across tasks. Callbacks that share a fetch must be interchangeable.

§Admission filters

Caller-supplied predicates control memory and disk admission separately. Both default to accepting all objects. Each receives the key hash, payload length, and request history.

let cache = feuer::Cache::builder()
    .memory_capacity(64 * 1024 * 1024)
    .with_memory_admission_filter(|_key, payload_len, _history| payload_len <= 1024 * 1024)
    .with_disk_admission_filter(|key, _payload_len, history| {
        history.decayed_request_count(key) > 1.5
    })
    .open()?;

This limits memory admission to objects up to 1 MiB. The disk predicate requires repeated recent demand and takes effect when disk caching is enabled. Rejected fetches still return bytes to callers and retain request history. Explicit inserts record no demand. Memory filtering also applies to disk-hit promotions. Existing cached entries remain readable. See CacheBuilder::with_memory_admission_filter and CacheBuilder::with_disk_admission_filter.

§Object identity and recovery

Lookups accept borrowed Hash keys, including strings, tuples, and derived structs. Feuer streams their hash input into SipHash-1-3-128 with a random secret 128-bit key per cache. Disk caches persist this key so identities survive reopening. Memory-only caches generate a new key on each open. Cloned handles share the same key. Keys do not need to implement Eq. Include every field that distinguishes objects and a namespace when key types share a cache. Use Cache::hash_key for scorer metadata and other integrations needing the same identity.

let key = ("split", 100u64, 200u64);
let bytes = cache.get_or_fetch(&key, || async {
    Ok::<_, std::convert::Infallible>(bytes::Bytes::from_static(b"payload"))
}).await?;
assert_eq!(cache.get(&key).await, Some(bytes));

Keep key hashing stable when reusing persistent entries. Rust’s Hash encoding can change across compiler versions and platforms. Change payload_version when key encoding or payload semantics change to clear old entries on reopen. Disk format 16 invalidates older caches when adopting per-cache SipHash identities.

Feuer stores only each key’s 128-bit hash and performs no full-key collision check. Colliding keys identify the same object, so a lookup can return another key’s payload. The secret key makes deliberately constructing collisions harder. Protect the backing file, which contains this key. Hashing does not authenticate cached payloads or anonymize traces.

Each key must identify one immutable payload. Use a new key when the content changes. Feuer has no invalidation API. Your application remains responsible for source retries and concurrency limits.

Treat cached data as disposable. Disk writes and recovery are best-effort, and your source must remain able to supply objects after eviction or a restart. Each disk cache needs its own backing file. See CacheConfig for capacity and payload-version rules.

§Disk caching and retention

To enable SSD caching, keep the disk feature enabled, configure a nonzero disk capacity, and open the cache on Linux with Tokio, io_uring, and direct-I/O support:

let cache = feuer::Cache::builder()
    .memory_capacity(64 * 1024 * 1024)
    .disk_capacity(1024 * 1024 * 1024)
    .directory("feuer_cache")
    .file_name("objects")
    .open()?;

This stores disk data in feuer_cache/objects. The directory defaults to feuer_cache and the filename to data. Opening blocks until disk metadata recovery completes. Disk caching requires an entered Tokio runtime for background workers. Memory-only operation works on every supported platform without a Tokio runtime. Access tracing through Cache::with_trace requires Tokio.

The default retention policy is FetchCostScorer. CacheReadSavingsScorer scores the cost saved by reading from cache instead of fetching from the fallback. For workload-specific decisions, implement RetentionScorer and configure each tier through CacheBuilder.

Structs§

AlignedBuffer
An owned, initialized, 4-KiB-aligned allocation with a separate exposed length. After conversion to Bytes, it returns to its pool only when the last owner drops it. Fixed buffers keep their capacity. Large buffers can resize and use anonymous mappings on Linux.
BytesAndMemoryCharge
Bytes and the amount charged toward the cache’s memory usage.
Cache
A cloneable handle to a Feuer cache.
CacheBuilder
Settings and optional resources used to open a Cache.
CacheConfig
Resolved settings for an open cache, available through crate::Cache::config. Configure a cache through crate::CacheBuilder.
CacheReadSavingsScorer
Scores objects by the cost saved by cache reads, weighted by demand and divided by payload size.
FetchCostScorer
Scores objects by fetch cost, weighted by demand and divided by payload size.
IoQueuesLinux and disk
One read queue and one write queue shared by independent caches on the same SSD.
IoQueuesConfigLinux and disk
Configuration for shared disk I/O queues.
ObjectAccessHistories
Request history shared by both cache tiers. Object keys select one of 64 independently locked history maps. The request clock remains global. Counters survive cache eviction. Every second, one background worker checks the entry limit and removes the least recently requested keys, targeting 90% of the limit. The limit is a soft threshold. A restart begins with empty history.
ObjectKeyHash
An immutable object’s identity, hashed with its cache’s SipHash-1-3-128 key.

Enums§

CacheConfigError
An invalid Feuer configuration.
CacheOpenError
An error configuring or opening a Cache.
DiskCacheErrorLinux and disk
An error opening or writing the disk cache. Read uncertainty becomes a miss.
GetOrFetchError
A failed cache lookup or download operation.

Traits§

RetentionScorer
Scores how valuable a cached object is to retain.

Type Aliases§

ObjectKey
An owned string key. Cache lookups also accept any borrowed Hash key.