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    /// Count of live keys carrying a TTL — the size of Redis's "expire set"
204    /// (`INFO keyspace`'s `expires=`). Maintained in O(1) at every TTL
205    /// transition (`insert_entry` / `remove_entry` deltas + the in-place
206    /// EXPIRE / PERSIST / SET sites) so the gauge never pays an O(n) keyspace
207    /// scan; [`Self::ttl_pending_count`] is the O(n) ground truth used to
208    /// assert this counter never drifts.
209    pub(crate) expires: u64,
210    /// `WATCH` version counters — present only for keys that have been
211    /// `WATCH`-ed at least once. [`Self::record_watch`] inserts the entry
212    /// (version 0 = "never written since first watch"); every subsequent
213    /// write on this shard calls [`Self::bump_if_watched`] which increments
214    /// only if the key is present in the map. Keys never `WATCH`-ed pay
215    /// one empty-map hashmap lookup per write (~10 ns).
216    ///
217    /// The map grows monotonically — entries are never evicted, even
218    /// when no conn is currently watching the key. For high-key-churn
219    /// workloads this can become a memory item; v1.x acceptable since
220    /// the entry is `Vec<u8>` + `u64` (~ 30 B + key length) and only
221    /// touched on writes / WATCH calls.
222    pub(crate) watch_versions: std::collections::HashMap<Vec<u8>, u64>,
223}
224
225impl Store {
226    pub fn new() -> Self {
227        Store::default()
228    }
229
230    /// Refresh the coarse cached clock (`Self::cached_ns`) from a single
231    /// `Instant::now()`. Call once per reactor-loop batch / reaper tick; the
232    /// per-access read path then skips its own clock read. Lazy expiry is
233    /// coarse to this cadence (a key expires ≤ one refresh-interval late,
234    /// never early — writes stamp deadlines from a fresh clock).
235    #[inline]
236    pub fn refresh_clock(&mut self) {
237        self.cached_ns = now_ns();
238    }
239
240    /// Enable/disable trusting the cached clock for lazy expiry (see
241    /// `Self::cached_ns`). Call with `true` only when something refreshes the
242    /// clock regularly (the server reactor per batch, the embedded background
243    /// reaper per tick); leave `false` for manual-reaper mode. Seeds the cache
244    /// when enabling so the first access is accurate.
245    #[inline]
246    pub fn set_cached_clock(&mut self, on: bool) {
247        self.cached_clock = on;
248        if on {
249            self.refresh_clock();
250        }
251    }
252
253    /// Install (or clear, with `maxmemory == 0`) the eviction limit and
254    /// policy. Cheap; safe to call repeatedly (e.g. on `CONFIG SET`).
255    #[inline]
256    pub fn set_max_memory(&mut self, maxmemory: u64, policy: EvictionPolicy) {
257        self.maxmemory = maxmemory;
258        self.eviction_policy = policy;
259    }
260
261    /// Live byte estimate (see field doc).
262    #[inline]
263    pub fn used_memory(&self) -> u64 {
264        self.used_memory
265    }
266
267    /// `used_memory` high-water mark since startup.
268    #[inline]
269    pub fn used_memory_peak(&self) -> u64 {
270        self.used_memory_peak
271    }
272
273    /// Configured `maxmemory` (0 = unlimited).
274    #[inline]
275    pub fn maxmemory(&self) -> u64 {
276        self.maxmemory
277    }
278
279    /// Configured eviction policy.
280    #[inline]
281    pub fn eviction_policy(&self) -> EvictionPolicy {
282        self.eviction_policy
283    }
284
285    /// Total keys evicted since startup.
286    #[inline]
287    pub fn evictions_total(&self) -> u64 {
288        self.evictions_total
289    }
290
291    /// Live keys carrying a TTL (`INFO keyspace`'s `expires=`). O(1) — reads
292    /// the maintained counter, not an O(n) scan (cf. [`Self::ttl_pending_count`]).
293    #[inline]
294    pub fn expires_count(&self) -> usize {
295        self.expires as usize
296    }
297
298    /// Apply a signed delta to the [`Self::expires`] counter, clamped at 0.
299    /// Centralises the saturating arithmetic for every TTL-transition site.
300    #[inline]
301    pub(crate) fn adjust_expires(&mut self, delta: i64) {
302        if delta != 0 {
303            self.expires = (self.expires as i64 + delta).max(0) as u64;
304        }
305    }
306
307    /// `WATCH` — record this key in the version tracker and return its
308    /// current version. Subsequent writes on this shard bump the version
309    /// via [`Self::bump_if_watched`]. Caller (the conn's origin shard)
310    /// stores the returned version; `EXEC` later asks every owning shard
311    /// "is the version still N?" via [`Self::key_version`].
312    ///
313    /// Keys that have never been written stay at version 0 — the first
314    /// write after a `WATCH` bumps to 1, which is what makes the "dirty"
315    /// comparison work (stored 0 ≠ current 1 ⇒ abort EXEC).
316    pub fn record_watch(&mut self, key: &[u8]) -> u64 {
317        *self
318            .watch_versions
319            .entry(key.to_vec())
320            .or_insert(0)
321    }
322
323    /// Read-only version lookup used by `EXEC`'s pre-execution check.
324    /// Returns `0` for keys never `WATCH`-ed (matches the initial value
325    /// `record_watch` would have inserted, so a `WATCH` → no-write →
326    /// `EXEC` sequence sees the stored 0 == current 0 and proceeds).
327    #[inline]
328    pub fn key_version(&self, key: &[u8]) -> u64 {
329        self.watch_versions.get(key).copied().unwrap_or(0)
330    }
331
332    /// Bump the version of `key` if (and only if) it has been `WATCH`-ed at
333    /// least once. Write-side call after every mutation. The empty check
334    /// runs BEFORE the key is hashed — the common nothing-watched case
335    /// pays one branch, not a guaranteed-miss probe.
336    #[inline]
337    pub fn bump_if_watched(&mut self, key: &[u8]) {
338        if self.watch_versions.is_empty() {
339            return;
340        }
341        if let Some(v) = self.watch_versions.get_mut(key) {
342            *v = v.wrapping_add(1);
343        }
344    }
345
346    /// Invalidate every watched key in one shot. Called from `FLUSHDB`
347    /// / `FLUSHALL` execution paths — every WATCH against this shard
348    /// must invalidate so a pending `EXEC` aborts.
349    pub fn bump_all_watched(&mut self) {
350        for v in self.watch_versions.values_mut() {
351            *v = v.wrapping_add(1);
352        }
353    }
354
355    /// Cached weight of `key` (dynamic part + [`ENTRY_OVERHEAD`]). Returns
356    /// `None` when the key is absent or expired (no implicit reap).
357    pub fn estimate_key_bytes(&self, key: &[u8]) -> Option<u64> {
358        self.map.get(key).map(|e| e.weight() + ENTRY_OVERHEAD)
359    }
360
361    /// O(1) precondition check the dispatch layer calls before every write
362    /// command. Returns `Err(OutOfMemory)` only when `maxmemory > 0`, the
363    /// budget is already over, AND the policy is `NoEviction` (Redis
364    /// behaviour). All other policies let the write proceed and recover via
365    /// [`Self::try_evict_after_write`].
366    #[inline]
367    pub fn precheck_for_write(&self) -> Result<(), StoreError> {
368        if self.maxmemory == 0 || self.used_memory <= self.maxmemory {
369            return Ok(());
370        }
371        if self.eviction_policy == EvictionPolicy::NoEviction {
372            return Err(StoreError::OutOfMemory);
373        }
374        Ok(())
375    }
376
377    /// Run after every write command. No-op when disabled or under budget;
378    /// otherwise samples per [`Self::eviction_policy`] and removes keys until
379    /// back under `maxmemory` or no eligible candidate remains. Returns the
380    /// number of keys evicted (0 on the common fast path).
381    #[inline]
382    pub fn try_evict_after_write(&mut self) -> usize {
383        if self.maxmemory == 0 || self.used_memory <= self.maxmemory {
384            return 0;
385        }
386        evict::evict_until_under_limit(self)
387    }
388
389}
390
391/// Apply a signed delta to a `u64` (saturating both directions). Used by
392/// `Store::account_delta` / `reweigh_entry` so the in-place mutators don't
393/// have to repeat the same overflow-guarded match.
394#[inline]
395pub(crate) fn apply_delta(v: &mut u64, delta: i64) {
396    if delta >= 0 {
397        *v = v.saturating_add(delta as u64);
398    } else {
399        *v = v.saturating_sub((-delta) as u64);
400    }
401}
402
403/// Heap bytes a `SmallBytes`-encoded key would own (`&[u8]` mirror of
404/// `SmallBytes::heap_bytes`; 22-byte inline boundary per `kevy-bytes`).
405#[inline]
406pub(crate) fn key_heap_bytes_for(key: &[u8]) -> u64 {
407    if key.len() <= 22 { 0 } else { key.len() as u64 }
408}
409
410#[cfg(test)]
411mod tests;
412#[cfg(test)]
413mod tests_memory;
414#[cfg(test)]
415mod tests_snapshot;