Skip to main content

cachekit/
lib.rs

1//! CacheKit — caching for Rust.
2//!
3//! Supports cachekit.io SaaS, Redis, Memcached, local File, and Cloudflare
4//! Workers backends. Zero-knowledge encryption via AES-256-GCM with HKDF key
5//! derivation.
6//!
7//! # Getting started: intent presets
8//!
9//! The intent presets are the primary entry point — one call that names your
10//! use case and returns a pre-configured [`CacheKitBuilder`] you can still
11//! override before [`build()`](CacheKitBuilder::build):
12//!
13//! | Intent | Backend | L1 | Encryption | Auto-reconnect² | Reliability¹ | Default TTL |
14//! |------------|-----------|------|------------|-----------------|--------------|-------------|
15//! | `CacheKit::minimal`³ | Redis | On (no SWR) | No | No | Off | 300 s |
16//! | `CacheKit::production`³ | Redis | On | No | Yes | On | 600 s |
17//! | `CacheKit::secure`³ ⁵ | Redis | On | AES-256-GCM | Yes | On | 600 s |
18//! | [`io`](CacheKit::io)⁴ | cachekit.io | On | No | n/a (HTTP) | On | 3 600 s |
19//!
20//! ¹ Retry with backoff + jitter, a circuit breaker, and backpressure around
21//! backend ops — see [`reliability`]. Requires the default-on `reliability`
22//! cargo feature.
23//! ² `production`/`secure` re-establish a dropped Redis connection with
24//! exponential backoff (100 ms → 30 s, retrying indefinitely); `minimal` is
25//! fail-fast (a dropped connection stays dead). **Initial** connections fail
26//! fast for every Redis preset — `io` opens no connection at construction: an
27//! empty API key fails at construction, while an invalid key or unreachable
28//! endpoint surfaces at the first request.
29//! Auto-reconnect is connection-level repair, distinct from the per-operation
30//! reliability stack.
31//! ³ Requires the `redis` cargo feature; `secure` also needs the
32//! default-on `encryption` feature.
33//! ⁴ API key by argument, or from `CACHEKIT_API_KEY` via
34//! [`io_from_env`](CacheKit::io_from_env). Neither reads
35//! `CACHEKIT_MASTER_KEY`; unlike [`from_env`](CacheKit::from_env), the `io`
36//! preset never activates encryption from the environment.
37//! ⁵ Master key as a hex string, `secure(url, master_key_hex)`, or from
38//! `CACHEKIT_MASTER_KEY` via `secure_from_env(url)` — the same hex decoding
39//! either way, so one key value derives the same key bytes in every CacheKit
40//! SDK. Use exactly 32 bytes (64 hex chars), the only length every SDK
41//! accepts. A missing, non-hex or short key fails at construction, before
42//! any Redis I/O; `secure` never falls back to plaintext.
43//!
44//! ```no_run
45//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
46//! let cache = cachekit::CacheKit::io_from_env()?
47//!     .namespace("myapp")
48//!     .build()?;
49//!
50//! cache.set("greeting", &"Hello, world!").await?;
51//! let val: Option<String> = cache.get("greeting").await?;
52//! # Ok(())
53//! # }
54//! ```
55//!
56//! For full control, drop down to [`CacheKit::builder`] or
57//! [`CacheKit::from_env`].
58//!
59//! # Observability
60//!
61//! Every client counts its reads: [`CacheKit::stats`] answers "is my cache
62//! hitting?" (L1 hits / L2 hits / misses), [`CacheKit::l1_entry_count`]
63//! reports L1 occupancy, and with `reliability` on,
64//! [`CacheKit::circuit_state`] reports the breaker. The same counters feed the
65//! cachekit.io backends' `X-CacheKit-*` telemetry headers automatically. Enable
66//! the `tracing` cargo feature for a `debug` event per operation on the
67//! `cachekit` target (`op`, `outcome`, `key_hash` — never the key) and
68//! breaker transitions on `cachekit::reliability` — see [`metrics`].
69
70// Production code lints — these only fire in src/, not tests/
71#![warn(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
72#![warn(missing_docs)]
73
74// Mutually exclusive feature guards
75#[cfg(all(feature = "workers", feature = "redis"))]
76compile_error!(
77    "features `workers` and `redis` are mutually exclusive — Workers runtime cannot use fred"
78);
79
80#[cfg(all(feature = "workers", feature = "l1"))]
81compile_error!("features `workers` and `l1` are mutually exclusive — moka requires std threads unavailable in wasm32");
82
83#[cfg(all(feature = "workers", feature = "reliability"))]
84compile_error!("features `workers` and `reliability` are mutually exclusive — retry/breaker timers need tokio `time`, unavailable in wasm32");
85
86#[cfg(all(feature = "workers", feature = "memcached"))]
87compile_error!("features `workers` and `memcached` are mutually exclusive — Workers runtime has no TCP sockets");
88
89#[cfg(all(feature = "workers", feature = "file"))]
90compile_error!(
91    "features `workers` and `file` are mutually exclusive — Workers runtime has no filesystem"
92);
93
94/// Pluggable cache backend trait and implementations (CachekitIO, Redis,
95/// Memcached, File, Workers).
96pub mod backend;
97/// High-level cache client with dual-layer (L1/L2) support.
98pub mod client;
99/// Configuration types and environment variable parsing.
100pub mod config;
101/// Error types for cache operations and backend communication.
102pub mod error;
103/// Cold-miss single-flight: dedup concurrent fills of the same key.
104pub mod flight;
105/// Interop mode (interop/v1): cross-SDK cache keys and plain-MessagePack values.
106pub mod interop;
107/// Live hit/miss counters, the SaaS telemetry headers built from them, and
108/// (feature `tracing`) structured events for cache operations.
109pub mod metrics;
110/// Serialization and deserialization of cached values via MessagePack.
111pub mod serializer;
112/// SDK session tracking (session ID and start timestamp).
113pub mod session;
114/// SSRF-safe URL validation for CachekitIO endpoints.
115pub mod url_validator;
116
117/// Intent-based cache presets (`CacheKit::minimal`, `::production`, `::secure`, `::io`).
118mod intents;
119
120/// Client-side AES-256-GCM encryption with HKDF key derivation.
121#[cfg(feature = "encryption")]
122pub mod encryption;
123
124/// In-process L1 cache backed by [`moka`] with per-entry TTL.
125#[cfg(feature = "l1")]
126pub mod l1;
127
128/// Reliability tier: retry with backoff + jitter, circuit breaker.
129#[cfg(all(feature = "reliability", not(target_arch = "wasm32")))]
130pub mod reliability;
131
132// Re-exports
133pub use client::{CacheKit, CacheKitBuilder, SharedBackend, SwrRead, SwrToken};
134pub use config::CachekitConfig;
135pub use error::{BackendError, BackendErrorKind, CachekitError};
136pub use metrics::L1Stats;
137
138#[cfg(feature = "encryption")]
139pub use client::SecureCache;
140#[cfg(feature = "encryption")]
141pub use encryption::EncryptionLayer;
142
143#[cfg(feature = "macros")]
144pub use cachekit_macros::cachekit;
145
146pub use flight::SingleFlight;
147
148#[cfg(all(feature = "reliability", not(target_arch = "wasm32")))]
149pub use reliability::{
150    BackpressureConfig, CircuitBreakerConfig, CircuitState, ReliabilityConfig, RetryConfig,
151};
152
153// ── Shared jitter source ─────────────────────────────────────────────────────
154
155/// Uniform random in `[0, 1)`. uuid v4 is the crate's existing entropy source
156/// (getrandom-backed); jitter needs decorrelation across clients, not crypto
157/// quality — 53 bits is plenty. Used by retry backoff (`reliability`) and the
158/// L1 SWR freshness threshold at entry insertion (`l1`).
159#[cfg(any(
160    feature = "l1",
161    all(feature = "reliability", not(target_arch = "wasm32"))
162))]
163pub(crate) fn random_unit() -> f64 {
164    let bits = uuid::Uuid::new_v4().as_u128() & ((1u128 << 53) - 1);
165    (bits as f64) / ((1u64 << 53) as f64)
166}
167
168// ── SWR background-refresh spawn (macro plumbing) ───────────────────────────
169
170/// Spawn a stale-while-revalidate background refresh onto the ambient tokio
171/// runtime. Macro plumbing for `#[cachekit]` — not public API.
172///
173/// Without a tokio runtime on the current thread the refresh is skipped: the
174/// caller has already been served the stale value, and a later stale read
175/// simply retries. Panicking here would turn a cache optimisation into an
176/// availability bug on non-tokio executors.
177#[cfg(all(feature = "l1", not(feature = "unsync"), not(target_arch = "wasm32")))]
178#[doc(hidden)]
179pub fn __swr_spawn<F>(fut: F)
180where
181    F: std::future::Future<Output = ()> + Send + 'static,
182{
183    if let Ok(handle) = tokio::runtime::Handle::try_current() {
184        drop(handle.spawn(fut));
185    }
186}
187
188/// No-op variant: under `unsync`, on wasm32, or without the `l1` feature the
189/// client never classifies a hit as stale (`SwrRead::Stale` is unreachable),
190/// so the refresh future handed here is dead code by construction. The stub
191/// exists so `#[cachekit]`-generated code compiles under every configuration.
192#[cfg(not(all(feature = "l1", not(feature = "unsync"), not(target_arch = "wasm32"))))]
193#[doc(hidden)]
194pub fn __swr_spawn<F>(_fut: F)
195where
196    F: std::future::Future<Output = ()> + 'static,
197{
198}
199
200/// Convenient glob import for the most common types.
201pub mod prelude {
202    pub use crate::{
203        BackendError, BackendErrorKind, CacheKit, CacheKitBuilder, CachekitConfig, CachekitError,
204        SwrRead, SwrToken,
205    };
206
207    #[cfg(feature = "encryption")]
208    pub use crate::{EncryptionLayer, SecureCache};
209
210    #[cfg(feature = "macros")]
211    pub use crate::cachekit;
212}