cachelito_core/lib.rs
1//! # Cachelito Core
2//!
3//! Core traits and utilities for the Cachelito caching library.
4//!
5//! This module provides the fundamental building blocks for cache key generation,
6//! thread-local cache management, global cache management, eviction policies,
7//! invalidation strategies, and memory management.
8//!
9//! ## Features
10//!
11//! - **Cache Key Generation**: Flexible traits for custom or default cache keys
12//! - **Thread-Local Storage**: Safe, lock-free caching using `thread_local!`
13//! - **Global Cache**: Thread-safe cache shared across all threads using `parking_lot::RwLock`
14//! - **Async Cache**: Lock-free async cache using `DashMap` for concurrent async operations
15//! - **Eviction Policies**: Support for FIFO, LRU (default), LFU, ARC, Random, and TLRU
16//! - **FIFO**: First In, First Out - simple and predictable
17//! - **LRU**: Least Recently Used - evicts least recently accessed entries
18//! - **LFU**: Least Frequently Used - evicts least frequently accessed entries
19//! - **ARC**: Adaptive Replacement Cache - self-tuning policy combining recency and frequency
20//! - **Random**: Random replacement - O(1) eviction with minimal overhead
21//! - **TLRU**: Time-aware LRU - combines recency, frequency, and time-based expiration
22//! - Customizable with `frequency_weight` parameter to control recency vs frequency balance
23//! - Formula: `score = frequency^weight × position × age_factor`
24//! - `frequency_weight < 1.0`: Emphasize recency (good for time-sensitive data)
25//! - `frequency_weight > 1.0`: Emphasize frequency (good for popular content)
26//! - **Cache Limits**: Control cache size with entry count limits (`limit`) or memory limits (`max_memory`)
27//! - **Memory Estimation**: `MemoryEstimator` trait for accurate memory usage tracking
28//! - **TTL Support**: Time-to-live expiration for automatic cache invalidation
29//! - **Result-Aware Caching**: Smart handling of `Result<T, E>` types
30//! - **Smart Invalidation**: Tag-based, event-driven, and dependency-based cache invalidation
31//! - **Conditional Invalidation**: Runtime invalidation with custom check functions
32//! - **Statistics Tracking**: Optional hit/miss rate monitoring (requires `stats` feature)
33//!
34//! ## Module Organization
35//!
36//! The library is organized into focused modules:
37//!
38//! - [`cache_entry`] - Entry wrapper with timestamp and frequency tracking for TTL and LFU support
39//! - [`eviction_policy`] - Eviction strategies: FIFO, LRU, LFU, ARC, and Random
40//! - [`keys`] - Cache key generation traits and implementations
41//! - [`thread_local_cache`] - Thread-local caching with zero synchronization overhead
42//! - [`global_cache`] - Thread-safe global cache with `parking_lot::RwLock` for concurrent reads
43//! - [`async_global_cache`] - Lock-free async cache using `DashMap`
44//! - [`memory_estimator`] - Trait for estimating memory usage of cached values
45//! - [`invalidation`] - Cache invalidation registry and strategies
46//! - [`utils`] - Common utility functions for cache operations
47//! - [`stats`] - Cache statistics tracking (optional, requires `stats` feature)
48//! - [`stats_registry`] - Global statistics registry for querying cache metrics
49//!
50//! ## Invalidation Strategies
51//!
52//! The invalidation module provides multiple strategies for cache invalidation:
53//!
54//! - **Tag-based**: `invalidate_by_tag("user_data")` - Invalidate all caches with a specific tag
55//! - **Event-driven**: `invalidate_by_event("user_updated")` - Invalidate based on application events
56//! - **Dependency-based**: `invalidate_by_dependency("get_user")` - Cascade invalidation to dependent caches
57//! - **Manual**: `invalidate_cache("cache_name")` - Direct cache invalidation
58//! - **Conditional**: `invalidate_with("cache_name", |key| predicate)` - Selective invalidation with custom logic
59//! - **Global conditional**: `invalidate_all_with(|cache_name, key| predicate)` - Apply check function across all caches
60//!
61//! ## Memory Management
62//!
63//! Cachelito supports both entry-count and memory-based limits:
64//!
65//! - **Entry limit**: `limit = 1000` - Maximum number of entries
66//! - **Memory limit**: `max_memory = "100MB"` - Maximum memory usage
67//! - **Custom estimators**: Implement `MemoryEstimator` for user-defined types
68//!
69//! ## Statistics (Optional)
70//!
71//! When compiled with the `stats` feature, cachelito tracks cache performance:
72//!
73//! - Hit/miss counts
74//! - Hit rate percentage
75//! - Total access count
76//! - Per-cache statistics via `stats_registry::get("cache_name")`
77//!
78mod async_global_cache;
79mod cache_entry;
80mod eviction_policy;
81mod global_cache;
82mod keys;
83mod memory_estimator;
84mod thread_local_cache;
85
86pub mod invalidation;
87pub mod utils;
88
89#[cfg(feature = "stats")]
90mod stats;
91
92#[cfg(feature = "stats")]
93pub mod stats_registry;
94
95pub mod count_min_sketch;
96
97pub mod w_tinylfu;
98
99pub use async_global_cache::AsyncGlobalCache;
100pub use cache_entry::CacheEntry;
101pub use count_min_sketch::CountMinSketch;
102pub use eviction_policy::EvictionPolicy;
103pub use global_cache::GlobalCache;
104pub use invalidation::{
105 invalidate_all_with, invalidate_by_dependency, invalidate_by_event, invalidate_by_tag,
106 invalidate_cache, invalidate_with, InvalidationMetadata, InvalidationRegistry,
107 InvalidationStrategy,
108};
109pub use keys::{CacheableKey, DefaultCacheableKey};
110pub use memory_estimator::MemoryEstimator;
111pub use thread_local_cache::ThreadLocalCache;
112pub use w_tinylfu::WTinyLFUConfig;
113
114#[cfg(feature = "stats")]
115pub use stats::CacheStats;
116/// Cache scope: thread-local or global
117///
118/// This enum determines whether a cache is stored in thread-local storage
119/// or in global static storage accessible by all threads.
120///
121/// # Variants
122///
123/// * `ThreadLocal` - Each thread has its own independent cache
124/// * `Global` - Cache is shared across all threads with mutex protection
125///
126/// # Examples
127///
128/// ```
129/// use cachelito_core::CacheScope;
130///
131/// let scope = CacheScope::ThreadLocal;
132/// assert_eq!(scope, CacheScope::ThreadLocal);
133///
134/// let global = CacheScope::Global;
135/// assert_eq!(global, CacheScope::Global);
136/// ```
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum CacheScope {
139 ThreadLocal,
140 Global,
141}