Skip to main content

kevy_store/
lib.rs

1//! kevy-store — the keyspace.
2//!
3//! A single-threaded, multi-type keyspace with lazy expiration. Each Redis data
4//! type is backed by a modern `std` structure — behaviour-compatible, but **not**
5//! Redis's legacy encodings:
6//!
7//! | Type | Backing structure |
8//! |------|-------------------|
9//! | String | `Vec<u8>` |
10//! | Hash / Set | `HashMap` / `HashSet` (hashbrown Swiss table) |
11//! | List | `VecDeque` (ring buffer, O(1) ends) |
12//! | Sorted set | `HashMap` + `BTreeSet<(score, member)>` (a B-tree, not a skiplist) |
13//!
14//! Wrong-type access returns [`StoreError::WrongType`]. The API is `&mut self`
15//! and lock-free, so a thread-per-core runtime ([kevy-rt]) can own one shard per
16//! core with no locking. Part of the [kevy] key–value server.
17//!
18//! `maxmemory` enforcement + 8 eviction policies live in [`evict`]; toggle via
19//! [`Store::set_max_memory`]. With `maxmemory == 0` (the default) the hot-path
20//! cost collapses to a single predicted-not-taken branch, matching the
21//! "unlimited" mode in Redis byte-for-byte.
22//!
23//! [kevy]: https://crates.io/crates/kevy
24//! [kevy-rt]: https://crates.io/crates/kevy-rt
25//!
26//! # Example
27//!
28//! ```
29//! use kevy_store::Store;
30//!
31//! let mut s = Store::new();
32//! s.set(b"greeting", b"hello".to_vec(), None, false, false);
33//! assert_eq!(s.get(b"greeting").unwrap(), Some(&b"hello"[..]));
34//!
35//! s.hset(b"user:1", &[(b"name".to_vec(), b"alice".to_vec())]).unwrap();
36//! assert_eq!(s.hget(b"user:1", b"name").unwrap(), Some(&b"alice"[..]));
37//!
38//! // A string command on a hash key is a type error, as in Redis.
39//! assert_eq!(s.get(b"user:1"), Err(kevy_store::StoreError::WrongType));
40//! ```
41#![forbid(unsafe_code)]
42
43mod accounting;
44mod clock;
45mod entry;
46pub mod evict;
47pub mod expire;
48pub use expire::ExpireStats;
49pub(crate) use entry::Entry;
50mod hash;
51mod keyspace;
52mod list;
53mod set;
54mod snapshot;
55pub use snapshot::SnapshotView;
56mod stream;
57mod string;
58mod util;
59mod value;
60mod zset;
61pub use stream::{
62    AutoclaimResult, ConsumerGroup, ConsumerState, EntryBatch, GroupCreateMode,
63    LoadedGroup, LoadedPelEntry, LoadedStreamEntry, PelEntry, PendingExtended,
64    PendingExtendedRow, PendingSummary, ReadGroupId, StreamData, StreamId, StreamIdError,
65    XAddIdSpec, XClaimOpts, now_unix_ms, parse_explicit_id, parse_range_end,
66    parse_range_start, parse_xadd_id,
67};
68pub use util::glob_match;
69pub use value::*;
70
71pub(crate) use clock::{now_ns, pack_deadline, unpack_deadline};
72use kevy_map::KevyMap;
73
74
75/// Outcome of [`Store::rename`] — three-way result so the dispatch
76/// layer can pick the right RESP frame (`+OK` / `-ERR no such key` /
77/// `:0` for `RENAMENX`-with-existing-dst).
78#[derive(Debug, PartialEq, Eq)]
79pub enum RenameOutcome {
80    /// Source removed, destination created (overwriting any prior dst).
81    Renamed,
82    /// Source key doesn't exist.
83    NoSuchSrc,
84    /// `RENAMENX` only — destination already exists, no rename done.
85    DstExists,
86}
87
88/// Operation errors surfaced to the command layer.
89#[derive(Debug, PartialEq, Eq)]
90pub enum StoreError {
91    /// Key holds a different type than the command expects.
92    WrongType,
93    /// Value is not a base-10 integer (INCR family).
94    NotInteger,
95    /// Result would overflow `i64`.
96    Overflow,
97    /// Index outside the collection (LSET).
98    OutOfRange,
99    /// Key does not exist where the command requires one (LSET).
100    NoSuchKey,
101    /// Value is not a valid float (INCRBYFLOAT).
102    NotFloat,
103    /// `maxmemory` would be exceeded and the active eviction policy is
104    /// [`EvictionPolicy::NoEviction`]. Surfaces as Redis's classic OOM error
105    /// at the RESP layer.
106    OutOfMemory,
107}
108
109/// Maxmemory eviction policy. Mirror of `kevy_config::EvictionPolicy` —
110/// duplicated here so `kevy-store` stays a leaf crate (no `kevy-config` dep).
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
112pub enum EvictionPolicy {
113    /// Refuse writes once `maxmemory` is hit. Default.
114    #[default]
115    NoEviction,
116    /// Approximated LRU across all keys.
117    AllKeysLru,
118    /// Approximated LFU across all keys.
119    AllKeysLfu,
120    /// Random key across all keys.
121    AllKeysRandom,
122    /// Approximated LRU across keys with a TTL.
123    VolatileLru,
124    /// Approximated LFU across keys with a TTL.
125    VolatileLfu,
126    /// Random key from those with a TTL.
127    VolatileRandom,
128    /// Key with the shortest remaining TTL.
129    VolatileTtl,
130}
131
132impl EvictionPolicy {
133    /// Whether the policy ranks candidates by LRU clock (read-touches matter).
134    #[inline]
135    pub fn uses_lru(self) -> bool {
136        matches!(self, Self::AllKeysLru | Self::VolatileLru)
137    }
138
139    /// Whether the policy ranks candidates by LFU counter (read-touches and
140    /// log-counter increments matter).
141    #[inline]
142    pub fn uses_lfu(self) -> bool {
143        matches!(self, Self::AllKeysLfu | Self::VolatileLfu)
144    }
145
146    /// Whether the policy restricts eviction to keys that carry a TTL.
147    #[inline]
148    pub fn is_volatile(self) -> bool {
149        matches!(
150            self,
151            Self::VolatileLru | Self::VolatileLfu | Self::VolatileRandom | Self::VolatileTtl
152        )
153    }
154}
155
156/// A single-database keyspace.
157///
158/// The keyspace map is a [`KevyMap`] — a pure-Rust open-addressing Swiss
159/// table tuned for kevy's per-shard, single-trust-domain keyspace. The
160/// hasher is [`kevy_hash::KevyHash`] (one-call inlinable; no DoS hardening
161/// since the shard is single-threaded with no cross-trust keys). Owning the
162/// table also exposes bucket addresses for software prefetch on the batch
163/// driver.
164#[derive(Default)]
165pub struct Store {
166    pub(crate) map: KevyMap<SmallBytes, Entry>,
167    /// Coarse cached monotonic clock (ns since [`epoch`]), refreshed by the
168    /// reactor loop / reaper tick via [`Self::refresh_clock`]. Lazy expiry on
169    /// the read path (`live_entry`) compares deadlines against this instead of
170    /// calling `Instant::now()` per access — the Redis cached-`mstime` model.
171    /// `0` (the `Default`) reads as "epoch" → keys look live until the first
172    /// refresh, the safe direction (expires at most one refresh-interval late,
173    /// never early — writes stamp deadlines from a *fresh* clock).
174    pub(crate) cached_ns: u64,
175    /// Whether lazy expiry trusts `Self::cached_ns` (set by a reactor/reaper
176    /// that calls [`Self::refresh_clock`]) instead of reading a fresh clock per
177    /// access. Enabled by the server reactor and the embedded background
178    /// reaper; left `false` (the `Default`) for manual-reaper / bare-`Store`
179    /// use, where nothing refreshes the cache so each access reads fresh —
180    /// preserving "lazy expiry works without an explicit tick".
181    pub(crate) cached_clock: bool,
182    /// Live byte estimate (dynamic per-entry weights + [`ENTRY_OVERHEAD`] per
183    /// key). Compared against [`Self::maxmemory`] to drive eviction.
184    pub(crate) used_memory: u64,
185    /// Soft byte ceiling. `0` = unlimited; the entire accounting + eviction
186    /// machinery short-circuits to a single not-taken branch in that case.
187    pub(crate) maxmemory: u64,
188    /// Active eviction policy. Only consulted when `used_memory > maxmemory`.
189    pub(crate) eviction_policy: EvictionPolicy,
190    /// Total keys evicted by [`Self::try_evict_after_write`] — surfaced via
191    /// `INFO memory` / `MEMORY STATS`.
192    pub(crate) evictions_total: u64,
193    /// Monotonic access counter; the upper 32 bits are unused, the lower 32
194    /// stamp `Entry::lru_clock` on each access while eviction is enabled.
195    pub(crate) clock_counter: u64,
196    /// `used_memory` peak across the shard's lifetime; surfaced as
197    /// `used_memory_peak` in `INFO memory`.
198    pub(crate) used_memory_peak: u64,
199    /// Keys expired since startup (lazy reap path AND
200    /// [`Self::tick_expire`]). Surfaced via `INFO keyspace` / `MEMORY STATS`
201    /// once those fields land.
202    pub(crate) expired_keys_total: u64,
203    /// `WATCH` version counters — present only for keys that have been
204    /// `WATCH`-ed at least once. [`Self::record_watch`] inserts the entry
205    /// (version 0 = "never written since first watch"); every subsequent
206    /// write on this shard calls [`Self::bump_if_watched`] which increments
207    /// only if the key is present in the map. Keys never `WATCH`-ed pay
208    /// one empty-map hashmap lookup per write (~10 ns).
209    ///
210    /// The map grows monotonically — entries are never evicted, even
211    /// when no conn is currently watching the key. For high-key-churn
212    /// workloads this can become a memory item; v1.x acceptable since
213    /// the entry is `Vec<u8>` + `u64` (~ 30 B + key length) and only
214    /// touched on writes / WATCH calls.
215    pub(crate) watch_versions: std::collections::HashMap<Vec<u8>, u64>,
216}
217
218impl Store {
219    pub fn new() -> Self {
220        Store::default()
221    }
222
223    /// Refresh the coarse cached clock (`Self::cached_ns`) from a single
224    /// `Instant::now()`. Call once per reactor-loop batch / reaper tick; the
225    /// per-access read path then skips its own clock read. Lazy expiry is
226    /// coarse to this cadence (a key expires ≤ one refresh-interval late,
227    /// never early — writes stamp deadlines from a fresh clock).
228    #[inline]
229    pub fn refresh_clock(&mut self) {
230        self.cached_ns = now_ns();
231    }
232
233    /// Enable/disable trusting the cached clock for lazy expiry (see
234    /// `Self::cached_ns`). Call with `true` only when something refreshes the
235    /// clock regularly (the server reactor per batch, the embedded background
236    /// reaper per tick); leave `false` for manual-reaper mode. Seeds the cache
237    /// when enabling so the first access is accurate.
238    #[inline]
239    pub fn set_cached_clock(&mut self, on: bool) {
240        self.cached_clock = on;
241        if on {
242            self.refresh_clock();
243        }
244    }
245
246    /// Install (or clear, with `maxmemory == 0`) the eviction limit and
247    /// policy. Cheap; safe to call repeatedly (e.g. on `CONFIG SET`).
248    #[inline]
249    pub fn set_max_memory(&mut self, maxmemory: u64, policy: EvictionPolicy) {
250        self.maxmemory = maxmemory;
251        self.eviction_policy = policy;
252    }
253
254    /// Live byte estimate (see field doc).
255    #[inline]
256    pub fn used_memory(&self) -> u64 {
257        self.used_memory
258    }
259
260    /// `used_memory` high-water mark since startup.
261    #[inline]
262    pub fn used_memory_peak(&self) -> u64 {
263        self.used_memory_peak
264    }
265
266    /// Configured `maxmemory` (0 = unlimited).
267    #[inline]
268    pub fn maxmemory(&self) -> u64 {
269        self.maxmemory
270    }
271
272    /// Configured eviction policy.
273    #[inline]
274    pub fn eviction_policy(&self) -> EvictionPolicy {
275        self.eviction_policy
276    }
277
278    /// Total keys evicted since startup.
279    #[inline]
280    pub fn evictions_total(&self) -> u64 {
281        self.evictions_total
282    }
283
284    /// `WATCH` — record this key in the version tracker and return its
285    /// current version. Subsequent writes on this shard bump the version
286    /// via [`Self::bump_if_watched`]. Caller (the conn's origin shard)
287    /// stores the returned version; `EXEC` later asks every owning shard
288    /// "is the version still N?" via [`Self::key_version`].
289    ///
290    /// Keys that have never been written stay at version 0 — the first
291    /// write after a `WATCH` bumps to 1, which is what makes the "dirty"
292    /// comparison work (stored 0 ≠ current 1 ⇒ abort EXEC).
293    pub fn record_watch(&mut self, key: &[u8]) -> u64 {
294        *self
295            .watch_versions
296            .entry(key.to_vec())
297            .or_insert(0)
298    }
299
300    /// Read-only version lookup used by `EXEC`'s pre-execution check.
301    /// Returns `0` for keys never `WATCH`-ed (matches the initial value
302    /// `record_watch` would have inserted, so a `WATCH` → no-write →
303    /// `EXEC` sequence sees the stored 0 == current 0 and proceeds).
304    #[inline]
305    pub fn key_version(&self, key: &[u8]) -> u64 {
306        self.watch_versions.get(key).copied().unwrap_or(0)
307    }
308
309    /// Bump the version of `key` if (and only if) it has been `WATCH`-ed at
310    /// least once. Write-side call after every mutation. The empty check
311    /// runs BEFORE the key is hashed — the common nothing-watched case
312    /// pays one branch, not a guaranteed-miss probe.
313    #[inline]
314    pub fn bump_if_watched(&mut self, key: &[u8]) {
315        if self.watch_versions.is_empty() {
316            return;
317        }
318        if let Some(v) = self.watch_versions.get_mut(key) {
319            *v = v.wrapping_add(1);
320        }
321    }
322
323    /// Invalidate every watched key in one shot. Called from `FLUSHDB`
324    /// / `FLUSHALL` execution paths — every WATCH against this shard
325    /// must invalidate so a pending `EXEC` aborts.
326    pub fn bump_all_watched(&mut self) {
327        for v in self.watch_versions.values_mut() {
328            *v = v.wrapping_add(1);
329        }
330    }
331
332    /// Cached weight of `key` (dynamic part + [`ENTRY_OVERHEAD`]). Returns
333    /// `None` when the key is absent or expired (no implicit reap).
334    pub fn estimate_key_bytes(&self, key: &[u8]) -> Option<u64> {
335        self.map.get(key).map(|e| e.weight() + ENTRY_OVERHEAD)
336    }
337
338    /// O(1) precondition check the dispatch layer calls before every write
339    /// command. Returns `Err(OutOfMemory)` only when `maxmemory > 0`, the
340    /// budget is already over, AND the policy is `NoEviction` (Redis
341    /// behaviour). All other policies let the write proceed and recover via
342    /// [`Self::try_evict_after_write`].
343    #[inline]
344    pub fn precheck_for_write(&self) -> Result<(), StoreError> {
345        if self.maxmemory == 0 || self.used_memory <= self.maxmemory {
346            return Ok(());
347        }
348        if self.eviction_policy == EvictionPolicy::NoEviction {
349            return Err(StoreError::OutOfMemory);
350        }
351        Ok(())
352    }
353
354    /// Run after every write command. No-op when disabled or under budget;
355    /// otherwise samples per [`Self::eviction_policy`] and removes keys until
356    /// back under `maxmemory` or no eligible candidate remains. Returns the
357    /// number of keys evicted (0 on the common fast path).
358    #[inline]
359    pub fn try_evict_after_write(&mut self) -> usize {
360        if self.maxmemory == 0 || self.used_memory <= self.maxmemory {
361            return 0;
362        }
363        evict::evict_until_under_limit(self)
364    }
365
366}
367
368/// Apply a signed delta to a `u64` (saturating both directions). Used by
369/// `Store::account_delta` / `reweigh_entry` so the in-place mutators don't
370/// have to repeat the same overflow-guarded match.
371#[inline]
372pub(crate) fn apply_delta(v: &mut u64, delta: i64) {
373    if delta >= 0 {
374        *v = v.saturating_add(delta as u64);
375    } else {
376        *v = v.saturating_sub((-delta) as u64);
377    }
378}
379
380/// Heap bytes a `SmallBytes`-encoded key would own (`&[u8]` mirror of
381/// `SmallBytes::heap_bytes`; 22-byte inline boundary per `kevy-bytes`).
382#[inline]
383pub(crate) fn key_heap_bytes_for(key: &[u8]) -> u64 {
384    if key.len() <= 22 { 0 } else { key.len() as u64 }
385}
386
387#[cfg(test)]
388mod tests;
389#[cfg(test)]
390mod tests_memory;
391#[cfg(test)]
392mod tests_snapshot;