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. `secure_from_env` also reads decrypt-only rotation keys from
42//! `CACHEKIT_PREVIOUS_MASTER_KEYS`, validated as `from_env` validates them.
43//! A missing, non-hex or short key fails at construction, before any Redis
44//! I/O; `secure` never falls back to plaintext.
45//!
46//! **Which calls encrypt.** On a `secure` client — and on any client built
47//! with a builder encryption method, such as `io` plus
48//! [`.encryption()`](CacheKitBuilder::encryption) — every value read and
49//! write encrypts: plain [`get`](CacheKit::get), [`set`](CacheKit::set),
50//! [`set_with_ttl`](CacheKit::set_with_ttl),
51//! [`interop_get`](CacheKit::interop_get) and
52//! [`interop_get_swr`](CacheKit::interop_get_swr) behave exactly as the
53//! `SecureCache` handle from `cache.secure_cache()` does, and L1 holds
54//! ciphertext. The handle is optional: it fails on a client without
55//! encryption, for code that must never run unencrypted. A build without the
56//! `encryption` feature rejects every builder encryption call with
57//! [`CachekitError::Config`].
58//!
59//! ```no_run
60//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
61//! let cache = cachekit::CacheKit::io_from_env()?
62//! .namespace("myapp")
63//! .build()?;
64//!
65//! cache.set("greeting", &"Hello, world!").await?;
66//! let val: Option<String> = cache.get("greeting").await?;
67//! # Ok(())
68//! # }
69//! ```
70//!
71//! For full control, drop down to [`CacheKit::builder`] or
72//! [`CacheKit::from_env`].
73//!
74//! # Observability
75//!
76//! Every client counts its reads: [`CacheKit::stats`] answers "is my cache
77//! hitting?" (L1 hits / L2 hits / misses), [`CacheKit::l1_entry_count`]
78//! reports L1 occupancy, and with `reliability` on,
79//! [`CacheKit::circuit_state`] reports the breaker. The same counters feed the
80//! cachekit.io backends' `X-CacheKit-*` telemetry headers automatically. Enable
81//! the `tracing` cargo feature for a `debug` event per operation on the
82//! `cachekit` target (`op`, `outcome`, `key_hash` — never the key) and
83//! breaker transitions on `cachekit::reliability` — see [`metrics`].
84
85// Production code lints — these only fire in src/, not tests/
86#![warn(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
87#![warn(missing_docs)]
88
89// Mutually exclusive feature guards
90#[cfg(all(feature = "workers", feature = "redis"))]
91compile_error!(
92 "features `workers` and `redis` are mutually exclusive — Workers runtime cannot use fred"
93);
94
95#[cfg(all(feature = "workers", feature = "l1"))]
96compile_error!("features `workers` and `l1` are mutually exclusive — moka requires std threads unavailable in wasm32");
97
98#[cfg(all(feature = "workers", feature = "reliability"))]
99compile_error!("features `workers` and `reliability` are mutually exclusive — retry/breaker timers need tokio `time`, unavailable in wasm32");
100
101#[cfg(all(feature = "workers", feature = "memcached"))]
102compile_error!("features `workers` and `memcached` are mutually exclusive — Workers runtime has no TCP sockets");
103
104#[cfg(all(feature = "workers", feature = "file"))]
105compile_error!(
106 "features `workers` and `file` are mutually exclusive — Workers runtime has no filesystem"
107);
108
109// Target guard: moka reads `Instant::now()` for its clock origin when the cache is constructed.
110#[cfg(all(feature = "l1", target_arch = "wasm32", target_os = "unknown"))]
111compile_error!("feature `l1` is not supported on wasm32-unknown-unknown — std::time::Instant has no clock there, so building the client (and its L1 cache) would panic; set `default-features = false, features = [\"encryption\"]` plus your backend feature, leaving out `l1`");
112
113/// Pluggable cache backend trait and implementations (CachekitIO, Redis,
114/// Memcached, File, Workers).
115pub mod backend;
116/// High-level cache client with dual-layer (L1/L2) support.
117pub mod client;
118/// Configuration types and environment variable parsing.
119pub mod config;
120/// Error types for cache operations and backend communication.
121pub mod error;
122/// Cold-miss single-flight: dedup concurrent fills of the same key.
123pub mod flight;
124/// Interop mode (interop/v1): cross-SDK cache keys and plain-MessagePack values.
125pub mod interop;
126/// Live hit/miss counters, the SaaS telemetry headers built from them, and
127/// (feature `tracing`) structured events for cache operations.
128pub mod metrics;
129/// Serialization and deserialization of cached values via MessagePack.
130pub mod serializer;
131/// SDK session tracking (session ID and start timestamp).
132pub mod session;
133/// SSRF-safe URL validation for CachekitIO endpoints.
134pub mod url_validator;
135
136/// Intent-based cache presets (`CacheKit::minimal`, `::production`, `::secure`, `::io`).
137mod intents;
138
139/// Client-side AES-256-GCM encryption with HKDF key derivation.
140#[cfg(feature = "encryption")]
141pub mod encryption;
142
143/// In-process L1 cache backed by [`moka`] with per-entry TTL.
144#[cfg(feature = "l1")]
145pub mod l1;
146
147/// Reliability tier: retry with backoff + jitter, circuit breaker.
148#[cfg(all(feature = "reliability", not(target_arch = "wasm32")))]
149pub mod reliability;
150
151// Re-exports
152pub use client::{CacheKit, CacheKitBuilder, SharedBackend, SwrRead, SwrToken};
153pub use config::CachekitConfig;
154pub use error::{BackendError, BackendErrorKind, CachekitError};
155pub use metrics::L1Stats;
156
157#[cfg(feature = "encryption")]
158pub use client::SecureCache;
159#[cfg(feature = "encryption")]
160pub use encryption::EncryptionLayer;
161
162#[cfg(feature = "macros")]
163pub use cachekit_macros::cachekit;
164
165pub use flight::SingleFlight;
166
167#[cfg(all(feature = "reliability", not(target_arch = "wasm32")))]
168pub use reliability::{
169 BackpressureConfig, CircuitBreakerConfig, CircuitState, ReliabilityConfig, RetryConfig,
170};
171
172// ── Shared jitter source ─────────────────────────────────────────────────────
173
174/// Uniform random in `[0, 1)`. Used by retry backoff (`reliability`) and the
175/// L1 SWR freshness threshold at entry insertion (`l1`). Jitter needs
176/// decorrelation across clients, not crypto quality, so this is a per-thread
177/// SplitMix64 seeded from std's `RandomState` instead of a getrandom syscall
178/// per call; 53 bits is plenty. Native only: wasm32 has no process ids
179/// (`std::process::id()` panics there), and `RandomState` carries no entropy
180/// on wasm32-unknown-unknown.
181#[cfg(all(
182 any(feature = "l1", feature = "reliability"),
183 not(target_arch = "wasm32")
184))]
185pub(crate) fn random_unit() -> f64 {
186 thread_local! {
187 static STATE: JitterState = const { std::cell::Cell::new(None) };
188 }
189 let z = STATE.with(|state| next_jitter(state, std::process::id()));
190 ((z >> 11) as f64) / ((1u64 << 53) as f64)
191}
192
193/// wasm32 variant (`l1` without `workers`, e.g. on WASI): one host-RNG draw per
194/// call through UUID v4. Nothing forks there, so the per-call draw is safe.
195#[cfg(all(feature = "l1", target_arch = "wasm32"))]
196pub(crate) fn random_unit() -> f64 {
197 let bits = uuid::Uuid::new_v4().as_u128() & ((1u128 << 53) - 1);
198 (bits as f64) / ((1u64 << 53) as f64)
199}
200
201/// The owning process id and SplitMix64 state behind [`random_unit`].
202#[cfg(all(
203 any(feature = "l1", feature = "reliability"),
204 not(target_arch = "wasm32")
205))]
206type JitterState = std::cell::Cell<Option<(u32, u64)>>;
207
208/// One SplitMix64 step. The state reseeds whenever `pid` differs from the one
209/// it was seeded under: a forked child inherits its parent's thread-local
210/// state, and without the reseed every prefork worker would replay the
211/// parent's sequence and synchronise refreshes and backoffs. The pid is hashed
212/// into the seed because siblings forked from one parent also inherit the same
213/// `RandomState` keys.
214#[cfg(all(
215 any(feature = "l1", feature = "reliability"),
216 not(target_arch = "wasm32")
217))]
218fn next_jitter(state: &JitterState, pid: u32) -> u64 {
219 use std::hash::{BuildHasher, Hasher};
220
221 let current = match state.get() {
222 Some((owner, current)) if owner == pid => current,
223 _ => {
224 let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
225 hasher.write_u32(pid);
226 hasher.finish()
227 }
228 };
229 let next = current.wrapping_add(0x9E37_79B9_7F4A_7C15);
230 state.set(Some((pid, next)));
231 let mut z = next;
232 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
233 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
234 z ^ (z >> 31)
235}
236
237// ── SWR background-refresh spawn (macro plumbing) ───────────────────────────
238
239/// Spawn a stale-while-revalidate background refresh onto the ambient tokio
240/// runtime. Macro plumbing for `#[cachekit]` — not public API.
241///
242/// Without a tokio runtime on the current thread the refresh is skipped: the
243/// caller has already been served the stale value, and a later stale read
244/// simply retries. Panicking here would turn a cache optimisation into an
245/// availability bug on non-tokio executors.
246#[cfg(all(feature = "l1", not(feature = "unsync"), not(target_arch = "wasm32")))]
247#[doc(hidden)]
248pub fn __swr_spawn<F>(fut: F)
249where
250 F: std::future::Future<Output = ()> + Send + 'static,
251{
252 if let Ok(handle) = tokio::runtime::Handle::try_current() {
253 drop(handle.spawn(fut));
254 }
255}
256
257/// No-op variant: under `unsync`, on wasm32, or without the `l1` feature the
258/// client never classifies a hit as stale (`SwrRead::Stale` is unreachable),
259/// so the refresh future handed here is dead code by construction. The stub
260/// exists so `#[cachekit]`-generated code compiles under every configuration.
261#[cfg(not(all(feature = "l1", not(feature = "unsync"), not(target_arch = "wasm32"))))]
262#[doc(hidden)]
263pub fn __swr_spawn<F>(_fut: F)
264where
265 F: std::future::Future<Output = ()> + 'static,
266{
267}
268
269/// Convenient glob import for the most common types.
270pub mod prelude {
271 pub use crate::{
272 BackendError, BackendErrorKind, CacheKit, CacheKitBuilder, CachekitConfig, CachekitError,
273 SwrRead, SwrToken,
274 };
275
276 #[cfg(feature = "encryption")]
277 pub use crate::{EncryptionLayer, SecureCache};
278
279 #[cfg(feature = "macros")]
280 pub use crate::cachekit;
281}
282
283#[cfg(all(
284 test,
285 any(feature = "l1", feature = "reliability"),
286 not(target_arch = "wasm32")
287))]
288mod random_unit_tests {
289 use super::{next_jitter, random_unit, JitterState};
290
291 /// A forked child inherits the parent's thread-local state (simulated by
292 /// copying the cell). Under its own pid it must not replay the parent's
293 /// next draw, and two siblings must not match each other either.
294 #[test]
295 fn a_new_pid_reseeds_instead_of_replaying_the_parent() {
296 let parent = JitterState::new(None);
297 next_jitter(&parent, 100);
298 let child_a = JitterState::new(parent.get());
299 let child_b = JitterState::new(parent.get());
300 let from_parent = next_jitter(&parent, 100);
301 let from_a = next_jitter(&child_a, 101);
302 let from_b = next_jitter(&child_b, 102);
303 assert_ne!(from_parent, from_a);
304 assert_ne!(from_parent, from_b);
305 assert_ne!(from_a, from_b);
306 // Same pid: the sequence continues rather than reseeding each draw.
307 let replay = JitterState::new(child_a.get());
308 assert_eq!(next_jitter(&replay, 101), next_jitter(&child_a, 101));
309 }
310
311 #[test]
312 fn stays_in_unit_interval_and_spreads() {
313 let draws: Vec<f64> = (0..10_000).map(|_| random_unit()).collect();
314 assert!(draws.iter().all(|x| (0.0..1.0).contains(x)));
315 let mean = draws.iter().sum::<f64>() / draws.len() as f64;
316 assert!((mean - 0.5).abs() < 0.02, "mean {mean}");
317 let low = draws.iter().filter(|x| **x < 0.1).count();
318 let high = draws.iter().filter(|x| **x >= 0.9).count();
319 assert!(low > 800 && high > 800, "tails {low} / {high}");
320 }
321
322 /// Each thread seeds from its own `RandomState` key, so two threads (and
323 /// two processes) do not replay one sequence.
324 #[test]
325 #[allow(clippy::expect_used)]
326 fn threads_draw_different_sequences() {
327 let draw = || (0..4).map(|_| random_unit().to_bits()).collect::<Vec<_>>();
328 let a = std::thread::spawn(draw).join().expect("thread a");
329 let b = std::thread::spawn(draw).join().expect("thread b");
330 assert_ne!(a, b);
331 }
332}