feuer 0.1.0

A restart-recoverable tiered cache for immutable objects
Documentation
//! ![Feuer — cost-aware tiered cache, with a flaming horse logo](https://raw.githubusercontent.com/PSeitz/feuer/main/full_logo.svg?v=cfeda6a)
//!
//! 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`](CacheBuilder::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.
//!
//! ```
//! # fn example() -> Result<(), feuer::CacheOpenError> {
//! 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()?;
//! # Ok(())
//! # }
//! ```
//!
//! 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`](std::hash::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.
//!
//! ```
//! # async fn example(cache: &feuer::Cache) -> Result<(), Box<dyn std::error::Error>> {
//! 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));
//! # Ok(())
//! # }
//! ```
//!
//! Keep key hashing stable when reusing persistent entries. Rust's `Hash` encoding can change across
//! compiler versions and platforms. Change [`payload_version`](CacheBuilder::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:
//!
//! ```no_run
//! # fn example() -> Result<(), feuer::CacheOpenError> {
//! let cache = feuer::Cache::builder()
//!     .memory_capacity(64 * 1024 * 1024)
//!     .disk_capacity(1024 * 1024 * 1024)
//!     .directory("feuer_cache")
//!     .file_name("objects")
//!     .open()?;
//! # Ok(())
//! # }
//! ```
//!
//! 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`].

#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(html_logo_url = "https://raw.githubusercontent.com/PSeitz/feuer/main/horse_logo_outline.svg")]
#![doc(html_favicon_url = "https://raw.githubusercontent.com/PSeitz/feuer/main/horse_logo_outline.svg")]

mod access_trace;
mod cache;
mod config;
mod metrics;
#[cfg(test)]
#[path = "../../test_support/metrics.rs"]
mod test_metrics;

pub use cache::{BytesAndMemoryCharge, Cache, CacheBuilder, CacheOpenError, GetOrFetchError};
pub use config::{CacheConfig, CacheConfigError};
pub use feuer_historian::ObjectAccessHistories;
pub use feuer_memory::{
    AlignedBuffer,
    retention::{CacheReadSavingsScorer, FetchCostScorer, RetentionScorer},
};
#[cfg(all(target_os = "linux", feature = "disk"))]
pub use feuer_storage::{DiskCacheError, IoQueues, IoQueuesConfig};
pub use feuer_utils::ObjectKeyHash;

/// An error opening the disk cache in a build without disk caching support.
#[cfg(not(all(target_os = "linux", feature = "disk")))]
#[derive(Debug, thiserror::Error)]
pub enum DiskCacheError {
    /// Disk caching requires Linux and the `disk` feature. Set disk capacity to zero for memory-only operation.
    #[error("disk caching requires Linux and the disk feature; set disk capacity to zero for memory-only operation")]
    UnsupportedPlatform,
}

/// I/O queues require Linux and the `disk` feature. Omit queue configuration in builds without disk support.
#[cfg(not(all(target_os = "linux", feature = "disk")))]
#[derive(Clone, Debug)]
pub enum IoQueues {}

/// An owned string key. Cache lookups also accept any borrowed [`Hash`](std::hash::Hash) key.
///
/// Only the SipHash-1-3-128 identity is stored, using a random secret key per cache.
/// Full keys are not checked for collisions. Colliding keys identify the same object,
/// so a lookup can return another key's payload. See [`Cache::hash_key`].
pub type ObjectKey = String;