cachekit 0.1.0-alpha

High-performance, policy-driven cache primitives for Rust systems (FIFO/LRU/ARC) with optional metrics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Handle-based store for zero-copy policy metadata.
//!
//! ## Architecture
//! - Stores values keyed by compact handles (e.g., interner IDs).
//! - A `HashMap<Handle, Arc<V>>` provides O(1) access.
//! - Policies operate on handles; the interner maps handles back to keys.
//!
//! ```text
//! key -> KeyInterner -> handle -> policy/DS -> eviction -> handle -> KeyInterner -> key
//! ```
//!
//! ## Key Components
//! - `HandleStore`: single-threaded handle-backed store.
//! - `ConcurrentHandleStore`: thread-safe wrapper using `RwLock`.
//! - Metrics counters for hits/misses/updates/evictions.
//!
//! ## Core Operations
//! - `try_insert`: insert or update by handle.
//! - `get`: fetch by handle (updates hit/miss metrics).
//! - `remove`: delete by handle.
//! - `clear`: drop all entries.
//!
//! ## Performance Trade-offs
//! - Avoids cloning large keys by storing handles only.
//! - Extra indirection requires a separate interner for key lookup.
//! - Uses `Arc<V>` values; cloning is cheap but still allocates on insert.
//!
//! ## When to Use
//! - You already use a `KeyInterner` or stable handle IDs.
//! - You want to minimize key cloning for large keys.
//! - Policy metadata is keyed by handle rather than full keys.
//!
//! ## Example Usage
//! ```rust
//! use std::sync::Arc;
//!
//! use cachekit::ds::KeyInterner;
//! use cachekit::store::handle::HandleStore;
//! use cachekit::store::traits::StoreMut;
//!
//! let mut interner = KeyInterner::new();
//! let handle = interner.intern("alpha".to_string());
//! let mut store: HandleStore<_, String> = HandleStore::new(2);
//! store
//!     .try_insert(handle, Arc::new("value".to_string()))
//!     .unwrap();
//! ```
//!
//! ## Type Constraints
//! - `H: Copy + Eq + Hash` for handle lookup.
//! - Values are stored as `Arc<V>`.
//!
//! ## Thread Safety
//! - `HandleStore` is single-threaded.
//! - `ConcurrentHandleStore` is `Send + Sync` via `RwLock`.
//!
//! ## Implementation Notes
//! - Handles must remain stable for the lifetime of stored entries.
//! - Metrics are stored separately to keep the hot path simple.
use std::cell::Cell;
use std::collections::HashMap;
use std::hash::Hash;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use parking_lot::RwLock;

use crate::store::traits::{
    ConcurrentStore, StoreCore, StoreFactory, StoreFull, StoreMetrics, StoreMut,
};

/// Store metrics counters for single-threaded handle stores.
#[derive(Debug, Default)]
struct StoreCounters {
    hits: Cell<u64>,
    misses: Cell<u64>,
    inserts: Cell<u64>,
    updates: Cell<u64>,
    removes: Cell<u64>,
    evictions: Cell<u64>,
}

impl StoreCounters {
    /// Snapshot current store metrics.
    fn snapshot(&self) -> StoreMetrics {
        StoreMetrics {
            hits: self.hits.get(),
            misses: self.misses.get(),
            inserts: self.inserts.get(),
            updates: self.updates.get(),
            removes: self.removes.get(),
            evictions: self.evictions.get(),
        }
    }

    /// Increment hit counter.
    fn inc_hit(&self) {
        self.hits.set(self.hits.get() + 1);
    }

    /// Increment miss counter.
    fn inc_miss(&self) {
        self.misses.set(self.misses.get() + 1);
    }

    /// Increment insert counter.
    fn inc_insert(&self) {
        self.inserts.set(self.inserts.get() + 1);
    }

    /// Increment update counter.
    fn inc_update(&self) {
        self.updates.set(self.updates.get() + 1);
    }

    /// Increment remove counter.
    fn inc_remove(&self) {
        self.removes.set(self.removes.get() + 1);
    }

    /// Increment eviction counter.
    fn inc_eviction(&self) {
        self.evictions.set(self.evictions.get() + 1);
    }
}

/// Store metrics counters for concurrent handle stores.
#[derive(Debug, Default)]
struct ConcurrentStoreCounters {
    hits: AtomicU64,
    misses: AtomicU64,
    inserts: AtomicU64,
    updates: AtomicU64,
    removes: AtomicU64,
    evictions: AtomicU64,
}

impl ConcurrentStoreCounters {
    /// Snapshot current store metrics.
    fn snapshot(&self) -> StoreMetrics {
        StoreMetrics {
            hits: self.hits.load(Ordering::Relaxed),
            misses: self.misses.load(Ordering::Relaxed),
            inserts: self.inserts.load(Ordering::Relaxed),
            updates: self.updates.load(Ordering::Relaxed),
            removes: self.removes.load(Ordering::Relaxed),
            evictions: self.evictions.load(Ordering::Relaxed),
        }
    }

    /// Increment hit counter.
    fn inc_hit(&self) {
        self.hits.fetch_add(1, Ordering::Relaxed);
    }

    /// Increment miss counter.
    fn inc_miss(&self) {
        self.misses.fetch_add(1, Ordering::Relaxed);
    }

    /// Increment insert counter.
    fn inc_insert(&self) {
        self.inserts.fetch_add(1, Ordering::Relaxed);
    }

    /// Increment update counter.
    fn inc_update(&self) {
        self.updates.fetch_add(1, Ordering::Relaxed);
    }

    /// Increment remove counter.
    fn inc_remove(&self) {
        self.removes.fetch_add(1, Ordering::Relaxed);
    }

    /// Increment eviction counter.
    fn inc_eviction(&self) {
        self.evictions.fetch_add(1, Ordering::Relaxed);
    }
}

/// Store keyed by compact handles (IDs) instead of full keys.
#[derive(Debug)]
pub struct HandleStore<H, V> {
    map: HashMap<H, Arc<V>>,
    capacity: usize,
    metrics: StoreCounters,
}

impl<H, V> HandleStore<H, V>
where
    H: Copy + Eq + Hash,
{
    /// Create a handle store with a fixed capacity.
    pub fn new(capacity: usize) -> Self {
        Self {
            map: HashMap::new(),
            capacity,
            metrics: StoreCounters::default(),
        }
    }

    /// Fetch a value by handle without updating metrics.
    pub fn peek_by_handle(&self, handle: &H) -> Option<&Arc<V>> {
        self.map.get(handle)
    }
}

impl<H, V> StoreCore<H, V> for HandleStore<H, V>
where
    H: Copy + Eq + Hash,
{
    /// Fetch a value by handle.
    fn get(&self, key: &H) -> Option<Arc<V>> {
        match self.map.get(key).cloned() {
            Some(value) => {
                self.metrics.inc_hit();
                Some(value)
            },
            None => {
                self.metrics.inc_miss();
                None
            },
        }
    }

    /// Check whether a handle exists.
    fn contains(&self, key: &H) -> bool {
        self.map.contains_key(key)
    }

    /// Return the number of entries.
    fn len(&self) -> usize {
        self.map.len()
    }

    /// Return the maximum capacity.
    fn capacity(&self) -> usize {
        self.capacity
    }

    /// Snapshot store metrics.
    fn metrics(&self) -> StoreMetrics {
        self.metrics.snapshot()
    }

    /// Record an eviction.
    fn record_eviction(&self) {
        self.metrics.inc_eviction();
    }
}

impl<H, V> StoreMut<H, V> for HandleStore<H, V>
where
    H: Copy + Eq + Hash,
{
    /// Insert or update an entry.
    fn try_insert(&mut self, key: H, value: Arc<V>) -> Result<Option<Arc<V>>, StoreFull> {
        if !self.map.contains_key(&key) && self.map.len() >= self.capacity {
            return Err(StoreFull);
        }
        let previous = self.map.insert(key, value);
        if previous.is_some() {
            self.metrics.inc_update();
        } else {
            self.metrics.inc_insert();
        }
        Ok(previous)
    }

    /// Remove a value by handle.
    fn remove(&mut self, key: &H) -> Option<Arc<V>> {
        let removed = self.map.remove(key);
        if removed.is_some() {
            self.metrics.inc_remove();
        }
        removed
    }

    /// Clear all entries.
    fn clear(&mut self) {
        self.map.clear();
    }
}

impl<H, V> StoreFactory<H, V> for HandleStore<H, V>
where
    H: Copy + Eq + Hash + Send,
{
    type Store = HandleStore<H, V>;

    /// Create a new store with the given capacity.
    fn create(capacity: usize) -> Self::Store {
        Self::new(capacity)
    }
}

/// Concurrent handle store using a `parking_lot::RwLock`.
#[derive(Debug)]
pub struct ConcurrentHandleStore<H, V> {
    map: RwLock<HashMap<H, Arc<V>>>,
    capacity: usize,
    metrics: ConcurrentStoreCounters,
}

impl<H, V> ConcurrentHandleStore<H, V>
where
    H: Copy + Eq + Hash + Send + Sync,
{
    /// Create a concurrent handle store with a fixed capacity.
    pub fn new(capacity: usize) -> Self {
        Self {
            map: RwLock::new(HashMap::new()),
            capacity,
            metrics: ConcurrentStoreCounters::default(),
        }
    }
}

impl<H, V> StoreCore<H, V> for ConcurrentHandleStore<H, V>
where
    H: Copy + Eq + Hash + Send + Sync,
{
    /// Fetch a value by handle.
    fn get(&self, key: &H) -> Option<Arc<V>> {
        match self.map.read().get(key).cloned() {
            Some(value) => {
                self.metrics.inc_hit();
                Some(value)
            },
            None => {
                self.metrics.inc_miss();
                None
            },
        }
    }

    /// Check whether a handle exists.
    fn contains(&self, key: &H) -> bool {
        self.map.read().contains_key(key)
    }

    /// Return the number of entries.
    fn len(&self) -> usize {
        self.map.read().len()
    }

    /// Return the maximum capacity.
    fn capacity(&self) -> usize {
        self.capacity
    }

    /// Snapshot store metrics.
    fn metrics(&self) -> StoreMetrics {
        self.metrics.snapshot()
    }

    /// Record an eviction.
    fn record_eviction(&self) {
        self.metrics.inc_eviction();
    }
}

impl<H, V> ConcurrentStore<H, V> for ConcurrentHandleStore<H, V>
where
    H: Copy + Eq + Hash + Send + Sync,
    V: Send + Sync,
{
    /// Insert or update an entry.
    fn try_insert(&self, key: H, value: Arc<V>) -> Result<Option<Arc<V>>, StoreFull> {
        let mut map = self.map.write();
        if !map.contains_key(&key) && map.len() >= self.capacity {
            return Err(StoreFull);
        }
        let previous = map.insert(key, value);
        if previous.is_some() {
            self.metrics.inc_update();
        } else {
            self.metrics.inc_insert();
        }
        Ok(previous)
    }

    /// Remove a value by handle.
    fn remove(&self, key: &H) -> Option<Arc<V>> {
        let removed = self.map.write().remove(key);
        if removed.is_some() {
            self.metrics.inc_remove();
        }
        removed
    }

    /// Clear all entries.
    fn clear(&self) {
        self.map.write().clear();
    }
}

impl<H, V> StoreFactory<H, V> for ConcurrentHandleStore<H, V>
where
    H: Copy + Eq + Hash + Send + Sync,
{
    type Store = ConcurrentHandleStore<H, V>;

    /// Create a new store with the given capacity.
    fn create(capacity: usize) -> Self::Store {
        Self::new(capacity)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn handle_store_basic_ops() {
        let mut store = HandleStore::new(2);
        let value = Arc::new("v1".to_string());
        assert_eq!(store.try_insert(1u64, value.clone()), Ok(None));
        assert_eq!(store.get(&1u64), Some(value.clone()));
        assert!(store.contains(&1u64));
        assert_eq!(store.len(), 1);
        assert_eq!(store.capacity(), 2);
        assert_eq!(store.remove(&1u64), Some(value));
        assert!(!store.contains(&1u64));
    }

    #[test]
    fn handle_store_capacity_enforced() {
        let mut store = HandleStore::new(1);
        assert_eq!(store.try_insert(1u64, Arc::new("v1".to_string())), Ok(None));
        assert_eq!(
            store.try_insert(2u64, Arc::new("v2".to_string())),
            Err(StoreFull)
        );
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn concurrent_handle_store_basic_ops() {
        let store = ConcurrentHandleStore::new(2);
        let value = Arc::new("v1".to_string());
        assert_eq!(store.try_insert(1u64, value.clone()), Ok(None));
        assert_eq!(store.get(&1u64), Some(value.clone()));
        assert!(store.contains(&1u64));
        assert_eq!(store.len(), 1);
        assert_eq!(store.capacity(), 2);
        assert_eq!(store.remove(&1u64), Some(value));
        assert!(!store.contains(&1u64));
    }

    #[test]
    fn handle_store_metrics_counts() {
        let mut store = HandleStore::new(2);
        let value = Arc::new("v1".to_string());

        assert_eq!(store.metrics(), StoreMetrics::default());
        assert_eq!(store.get(&1u64), None);
        assert_eq!(store.try_insert(1u64, value.clone()), Ok(None));
        assert_eq!(
            store.try_insert(1u64, value.clone()),
            Ok(Some(value.clone()))
        );
        assert_eq!(store.get(&1u64), Some(value.clone()));
        assert_eq!(store.remove(&1u64), Some(value));
        store.record_eviction();

        let metrics = store.metrics();
        assert_eq!(metrics.hits, 1);
        assert_eq!(metrics.misses, 1);
        assert_eq!(metrics.inserts, 1);
        assert_eq!(metrics.updates, 1);
        assert_eq!(metrics.removes, 1);
        assert_eq!(metrics.evictions, 1);
    }
}