oxistore_cache/lib.rs
1#![forbid(unsafe_code)]
2#![warn(missing_docs)]
3
4//! `oxistore-cache` — Pure-Rust LRU, ARC, LFU, and W-TinyLFU eviction primitives.
5//!
6//! This crate provides four cache implementations behind a unified [`Cache`]
7//! trait:
8//!
9//! - [`LruCache`] — classic Least-Recently-Used cache backed by a
10//! `hashlink::LinkedHashMap`. O(1) amortised operations.
11//!
12//! - [`ArcCache`] — Adaptive Replacement Cache (Megiddo & Modha, FAST'03),
13//! which balances recency and frequency by maintaining four lists (T1, T2,
14//! B1, B2) and an adaptive target `p`. ARC is scan-resistant.
15//!
16//! - [`LfuCache`] — Least-Frequently-Used cache with O(1) operations using
17//! the Shah, Mitra & Matani (2010) algorithm.
18//!
19//! - [`WTinyLfuCache`] — Window TinyLFU with Count-Min Sketch frequency
20//! estimation and a doorkeeper bloom filter, providing near-optimal hit rates
21//! on skewed (Zipfian) workloads.
22//!
23//! All cache implementations support per-entry TTL (time-to-live) via the
24//! [`Cache::put_with_ttl`] method. Expiry is checked lazily on access.
25//!
26//! # Example
27//!
28//! ```rust
29//! use oxistore_cache::{LruCache, ArcCache, LfuCache, WTinyLfuCache, Cache};
30//!
31//! let mut lru = LruCache::new(3);
32//! lru.put(1u32, "a");
33//! lru.put(2u32, "b");
34//! lru.put(3u32, "c");
35//! lru.put(4u32, "d"); // evicts 1 (LRU)
36//! assert!(lru.get(&1u32).is_none());
37//! assert_eq!(lru.get(&2u32), Some(&"b"));
38//!
39//! let mut arc = ArcCache::new(3);
40//! arc.put(1u32, "a");
41//! arc.put(2u32, "b");
42//! arc.put(3u32, "c");
43//!
44//! let mut lfu = LfuCache::new(3);
45//! lfu.put(1u32, "a");
46//! lfu.put(2u32, "b");
47//! lfu.put(3u32, "c");
48//!
49//! let mut wtlfu = WTinyLfuCache::new(3);
50//! wtlfu.put(1u32, "a");
51//! wtlfu.put(2u32, "b");
52//! wtlfu.put(3u32, "c");
53//! ```
54
55/// Adaptive Replacement Cache (ARC) — balances recency and frequency.
56pub mod arc;
57/// Bounded-memory cache wrapper — enforces a hard byte-budget cap.
58pub mod bounded;
59/// Cache builder — ergonomic constructor for all cache policies.
60pub mod builder;
61/// Least-Frequently-Used (LFU) cache — O(1) frequency-based eviction.
62pub mod lfu;
63/// Least-Recently-Used (LRU) cache — evicts the least recently accessed entry.
64pub mod lru;
65/// Sharded concurrent cache — N LRU shards behind a Mutex for low contention.
66pub mod sharded;
67/// Count-Min Sketch and Doorkeeper bloom filter for W-TinyLFU.
68pub mod sketch;
69/// Cache hit/miss statistics tracking.
70pub mod stats;
71/// Thread-safe cache wrapper — wraps any `Cache` impl behind a `Mutex`.
72pub mod sync;
73/// Window TinyLFU — state-of-the-art admission policy with CMS frequency estimator.
74pub mod tinylfu;
75/// Write-through and write-back cache adapters.
76pub mod write_adapter;
77
78/// Caching wrapper for `BlobStore` backends (see `oxistore_blob::BlobStore`).
79#[cfg(feature = "blob")]
80pub mod blob_cache;
81
82/// Caching adapter for hot Parquet row groups from `oxistore-columnar`.
83#[cfg(feature = "columnar")]
84pub mod columnar_cache;
85
86pub use arc::ArcCache;
87pub use bounded::BoundedCache;
88pub use builder::{CacheBuilder, CachePolicy};
89pub use lfu::LfuCache;
90pub use lru::LruCache;
91pub use sharded::ShardedCache;
92pub use stats::{CacheStats, StatsCache};
93pub use sync::SyncCache;
94pub use tinylfu::WTinyLfuCache;
95pub use write_adapter::{CacheableKvStore, WriteBackCache, WriteThroughCache};
96
97#[cfg(feature = "blob")]
98pub use blob_cache::BlobCache;
99
100#[cfg(feature = "columnar")]
101pub use columnar_cache::ColumnarRowGroupCache;
102
103/// A cache entry that optionally expires at a given instant.
104///
105/// Used internally by all cache implementations to support per-entry TTL.
106/// Callers interact with the value type `V` via the [`Cache`] trait methods;
107/// `CacheEntry` is exposed for advanced use cases (e.g. custom wrappers).
108pub struct CacheEntry<V> {
109 /// The stored value.
110 pub value: V,
111 /// Optional expiry time. `None` means the entry never expires.
112 pub expires_at: Option<std::time::Instant>,
113}
114
115impl<V> CacheEntry<V> {
116 /// Create a non-expiring entry.
117 #[must_use]
118 pub fn new(value: V) -> Self {
119 CacheEntry {
120 value,
121 expires_at: None,
122 }
123 }
124
125 /// Create an entry that expires after `ttl` from now.
126 #[must_use]
127 pub fn with_ttl(value: V, ttl: std::time::Duration) -> Self {
128 CacheEntry {
129 value,
130 expires_at: Some(std::time::Instant::now() + ttl),
131 }
132 }
133
134 /// Return `true` if this entry has expired (i.e. its deadline has passed).
135 #[must_use]
136 pub fn is_expired(&self) -> bool {
137 match self.expires_at {
138 Some(deadline) => std::time::Instant::now() >= deadline,
139 None => false,
140 }
141 }
142}
143
144/// Unified interface for key-value caches with bounded capacity.
145///
146/// All four implementations ([`LruCache`], [`ArcCache`], [`LfuCache`],
147/// [`WTinyLfuCache`]) implement this trait, allowing callers to write generic
148/// code against the cache interface.
149pub trait Cache<K, V> {
150 /// Look up `key`, returning a reference to the value if present.
151 ///
152 /// Implementations update internal bookkeeping (e.g. promoting the entry
153 /// to MRU or incrementing frequency counts) as a side effect.
154 ///
155 /// If the entry exists but has expired (TTL), it is removed and `None` is
156 /// returned without updating recency or frequency.
157 fn get(&mut self, key: &K) -> Option<&V>;
158
159 /// Insert or update `key` -> `value` without a TTL.
160 ///
161 /// If inserting a new key would exceed the cache's capacity, the
162 /// implementation evicts one entry (per its policy) and returns the
163 /// evicted value. On a key update, the old value is not returned.
164 fn put(&mut self, key: K, value: V) -> Option<V>;
165
166 /// Insert or update `key` -> `value` with a time-to-live.
167 ///
168 /// After `ttl` has elapsed, any access to `key` will treat it as a miss
169 /// and remove the entry lazily.
170 ///
171 /// Concrete implementations in this crate override this to actually store
172 /// the expiry. External impls that don't need TTL may rely on the default
173 /// which falls back to a plain `put` (no expiry).
174 fn put_with_ttl(&mut self, key: K, value: V, ttl: std::time::Duration) -> Option<V> {
175 let _ = ttl;
176 self.put(key, value)
177 }
178
179 /// Return the number of live entries currently in the cache.
180 fn len(&self) -> usize;
181
182 /// Return the maximum number of entries the cache can hold.
183 fn cap(&self) -> usize;
184
185 /// Return `true` if the cache holds no entries.
186 fn is_empty(&self) -> bool {
187 self.len() == 0
188 }
189
190 /// Remove the entry associated with `key`, returning its value if present.
191 ///
192 /// Unlike eviction, this is an explicit removal requested by the caller.
193 fn remove(&mut self, key: &K) -> Option<V>;
194
195 /// Remove all entries from the cache.
196 fn clear(&mut self);
197
198 /// Look up `key` without updating access metadata (no promotion).
199 ///
200 /// If the entry has expired (TTL), it is removed and `None` is returned.
201 /// Returns `None` if the key is not present or has expired.
202 fn peek(&self, key: &K) -> Option<&V>;
203
204 /// Return `true` if `key` is present in the cache (without promotion).
205 ///
206 /// Expired entries are treated as absent.
207 fn contains_key(&self, key: &K) -> bool;
208
209 /// Dynamically resize the cache capacity.
210 ///
211 /// If `new_cap` is smaller than the current length, excess entries are
212 /// evicted according to the cache's eviction policy.
213 fn resize(&mut self, new_cap: usize);
214
215 /// Return `&V` for `key`, inserting `default()` if the key is absent.
216 ///
217 /// The closure `default` is called at most once. If the key is already
218 /// present the closure is never invoked.
219 ///
220 /// Implementations may override this for efficiency (e.g. to avoid a
221 /// second hash lookup). The default implementation uses [`Cache::peek`]
222 /// after ensuring the key exists.
223 fn get_or_insert(&mut self, key: K, default: impl FnOnce() -> V) -> &V
224 where
225 K: Clone,
226 {
227 if !self.contains_key(&key) {
228 let v = default();
229 self.put(key.clone(), v);
230 }
231 // peek is &self and won't panic since we just ensured the key exists.
232 self.peek(&key).expect("key was just inserted")
233 }
234
235 /// Return all live (non-expired) values currently stored in the cache.
236 ///
237 /// The default implementation returns an empty `Vec`. Concrete
238 /// implementations override this to return actual values.
239 fn values(&self) -> Vec<&V> {
240 Vec::new()
241 }
242
243 /// Pre-populate the cache with `(key, value)` pairs from an iterator.
244 ///
245 /// Each pair is inserted via [`Cache::put`], respecting the cache's
246 /// eviction policy. Pairs that exceed capacity cause earlier entries to
247 /// be evicted according to the policy.
248 fn warm(&mut self, iter: impl IntoIterator<Item = (K, V)>) {
249 for (k, v) in iter {
250 self.put(k, v);
251 }
252 }
253}
254
255// ── Async helper ─────────────────────────────────────────────────────────────
256
257/// Look up `key` in `cache`, returning the cached value if present.
258///
259/// If the key is absent, the async closure `loader` is awaited to produce
260/// a value, which is then inserted into the cache and returned.
261///
262/// The closure is invoked **at most once** per call. If the key is already
263/// present it is never called.
264///
265/// # Example
266///
267/// ```rust
268/// use oxistore_cache::{LruCache, Cache, get_or_insert_async};
269/// use std::sync::Mutex;
270///
271/// # async fn example() {
272/// let cache = Mutex::new(LruCache::<u32, String>::new(4));
273/// let val = get_or_insert_async(
274/// &cache,
275/// 42u32,
276/// || async { "computed".to_string() },
277/// ).await;
278/// assert_eq!(val, "computed");
279/// # }
280/// ```
281pub async fn get_or_insert_async<K, V, C, F, Fut>(
282 cache: &std::sync::Mutex<C>,
283 key: K,
284 loader: F,
285) -> V
286where
287 K: Eq + std::hash::Hash + Clone,
288 V: Clone,
289 C: Cache<K, V>,
290 F: FnOnce() -> Fut,
291 Fut: std::future::Future<Output = V>,
292{
293 // Fast path: key already in cache.
294 {
295 let mut guard = cache.lock().expect("cache mutex poisoned");
296 if let Some(v) = guard.get(&key) {
297 return v.clone();
298 }
299 }
300 // Slow path: key absent — await the loader outside the lock.
301 let value = loader().await;
302 {
303 let mut guard = cache.lock().expect("cache mutex poisoned");
304 // Double-check in case another task inserted the key while we waited.
305 if let Some(existing) = guard.peek(&key) {
306 return existing.clone();
307 }
308 guard.put(key, value.clone());
309 }
310 value
311}
312
313/// Look up `key` in a `tokio::sync::Mutex`-wrapped cache asynchronously.
314///
315/// Identical semantics to [`get_or_insert_async`] but uses an async
316/// `tokio::sync::Mutex` instead of `std::sync::Mutex`.
317///
318/// This variant is suitable when the cache is shared across `tokio` tasks
319/// that run on a multi-threaded executor and cannot use a synchronous lock.
320///
321/// Requires the `async-helpers` feature flag.
322#[cfg(feature = "async-helpers")]
323pub async fn get_or_insert_async_tokio<K, V, C, F, Fut>(
324 cache: &tokio::sync::Mutex<C>,
325 key: K,
326 loader: F,
327) -> V
328where
329 K: Eq + std::hash::Hash + Clone,
330 V: Clone,
331 C: Cache<K, V>,
332 F: FnOnce() -> Fut,
333 Fut: std::future::Future<Output = V>,
334{
335 // Fast path: key already in cache (async lock, no blocking).
336 {
337 let mut guard = cache.lock().await;
338 if let Some(v) = guard.get(&key) {
339 return v.clone();
340 }
341 }
342 // Slow path: await the loader without holding the lock.
343 let value = loader().await;
344 {
345 let mut guard = cache.lock().await;
346 if let Some(existing) = guard.peek(&key) {
347 return existing.clone();
348 }
349 guard.put(key, value.clone());
350 }
351 value
352}