kevy_store/types.rs
1//! Public store types split from `lib.rs` (500-LOC rule):
2//! [`RenameOutcome`] / [`StoreError`] / [`EvictionPolicy`].
3
4use core::fmt;
5
6/// Outcome of [`Store::rename`](crate::Store::rename) and
7/// [`Store::rename_nx`](crate::Store::rename_nx) — three-way result so the
8/// dispatch layer can pick the right RESP frame (`+OK` / `-ERR no such
9/// key` / `:0` for `RENAMENX`-with-existing-dst).
10///
11/// ```
12/// use kevy_store::{RenameOutcome, SetCondition, Store};
13/// let mut s = Store::new();
14/// s.set(b"a", b"1".to_vec(), None, SetCondition::Always);
15/// s.set(b"b", b"2".to_vec(), None, SetCondition::Always);
16/// assert_eq!(s.rename_nx(b"a", b"b"), RenameOutcome::DstExists);
17/// assert_eq!(s.rename(b"a", b"b"), RenameOutcome::Renamed);
18/// assert_eq!(s.rename(b"a", b"c"), RenameOutcome::NoSuchSrc);
19/// ```
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum RenameOutcome {
22 /// Source removed, destination created (overwriting any prior dst).
23 ///
24 /// ```
25 /// use kevy_store::{RenameOutcome, SetCondition, Store};
26 /// let mut s = Store::new();
27 /// s.set(b"a", b"1".to_vec(), None, SetCondition::Always);
28 /// assert_eq!(s.rename(b"a", b"b"), RenameOutcome::Renamed);
29 /// assert_eq!(s.get(b"b")?.as_deref(), Some(&b"1"[..]));
30 /// # Ok::<(), kevy_store::StoreError>(())
31 /// ```
32 Renamed,
33 /// Source key doesn't exist.
34 ///
35 /// ```
36 /// use kevy_store::{RenameOutcome, Store};
37 /// let mut s = Store::new();
38 /// assert_eq!(s.rename(b"missing", b"b"), RenameOutcome::NoSuchSrc);
39 /// ```
40 NoSuchSrc,
41 /// `RENAMENX` only — destination already exists, no rename done.
42 ///
43 /// ```
44 /// use kevy_store::{RenameOutcome, SetCondition, Store};
45 /// let mut s = Store::new();
46 /// s.set(b"a", b"1".to_vec(), None, SetCondition::Always);
47 /// s.set(b"b", b"2".to_vec(), None, SetCondition::Always);
48 /// assert_eq!(s.rename_nx(b"a", b"b"), RenameOutcome::DstExists);
49 /// assert_eq!(s.get(b"a")?.as_deref(), Some(&b"1"[..]));
50 /// # Ok::<(), kevy_store::StoreError>(())
51 /// ```
52 DstExists,
53}
54
55/// Operation errors surfaced to the command layer.
56///
57/// `Display` is the lowercase description; [`StoreError::as_wire`] is the
58/// Redis error reply text the command layer sends.
59///
60/// ```
61/// use kevy_store::StoreError;
62/// assert_eq!(StoreError::WrongType.to_string(), "wrong type for this operation");
63/// assert!(StoreError::WrongType.as_wire().starts_with("WRONGTYPE "));
64/// ```
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66#[non_exhaustive]
67pub enum StoreError {
68 /// Key holds a different type than the command expects.
69 ///
70 /// ```
71 /// use kevy_store::{Store, StoreError};
72 /// let mut s = Store::new();
73 /// s.rpush(b"l", &[b"x".as_slice()])?;
74 /// assert_eq!(s.get(b"l"), Err(StoreError::WrongType));
75 /// # Ok::<(), StoreError>(())
76 /// ```
77 WrongType,
78 /// Value is not a base-10 integer (INCR family).
79 ///
80 /// ```
81 /// use kevy_store::{SetCondition, Store, StoreError};
82 /// let mut s = Store::new();
83 /// s.set(b"k", b"ten".to_vec(), None, SetCondition::Always);
84 /// assert_eq!(s.incr_by(b"k", 1), Err(StoreError::NotInteger));
85 /// ```
86 NotInteger,
87 /// Result would overflow `i64`.
88 ///
89 /// ```
90 /// use kevy_store::{SetCondition, Store, StoreError};
91 /// let mut s = Store::new();
92 /// s.set(b"k", i64::MAX.to_string().into_bytes(), None, SetCondition::Always);
93 /// assert_eq!(s.incr_by(b"k", 1), Err(StoreError::Overflow));
94 /// ```
95 Overflow,
96 /// Index outside the collection (LSET).
97 ///
98 /// ```
99 /// use kevy_store::{Store, StoreError};
100 /// let mut s = Store::new();
101 /// s.rpush(b"l", &[b"a".as_slice()])?;
102 /// assert_eq!(s.lset(b"l", 5, b"x"), Err(StoreError::OutOfRange));
103 /// # Ok::<(), StoreError>(())
104 /// ```
105 OutOfRange,
106 /// Key does not exist where the command requires one (LSET).
107 ///
108 /// ```
109 /// use kevy_store::{Store, StoreError};
110 /// let mut s = Store::new();
111 /// assert_eq!(s.lset(b"missing", 0, b"x"), Err(StoreError::NoSuchKey));
112 /// ```
113 NoSuchKey,
114 /// Value is not a valid float (INCRBYFLOAT).
115 ///
116 /// ```
117 /// use kevy_store::{SetCondition, Store, StoreError};
118 /// let mut s = Store::new();
119 /// s.set(b"k", b"pi".to_vec(), None, SetCondition::Always);
120 /// assert_eq!(s.incr_by_float(b"k", 1.0), Err(StoreError::NotFloat));
121 /// ```
122 NotFloat,
123 /// `maxmemory` would be exceeded and the active eviction policy is
124 /// [`EvictionPolicy::NoEviction`]. Surfaces as Redis's classic OOM error
125 /// at the RESP layer.
126 ///
127 /// ```
128 /// use kevy_store::{EvictionPolicy, SetCondition, Store, StoreError};
129 /// let mut s = Store::new();
130 /// s.set_max_memory(1, EvictionPolicy::NoEviction);
131 /// s.set(b"k", b"v".to_vec(), None, SetCondition::Always);
132 /// assert_eq!(s.precheck_for_write(), Err(StoreError::OutOfMemory));
133 /// ```
134 OutOfMemory,
135 /// A stream's last ID is the largest there is, so no entry can follow
136 /// it (XADD).
137 ///
138 /// ```
139 /// use kevy_store::{MissingStream, Store, StoreError, StreamId, XAddIdSpec};
140 /// let mut s = Store::new();
141 /// let f = || vec![(b"f".to_vec(), b"v".to_vec())];
142 /// s.xadd(b"s", XAddIdSpec::Explicit(StreamId::MAX), f(), MissingStream::Create, 0)?;
143 /// let next = s.xadd(b"s", XAddIdSpec::AutoAll, f(), MissingStream::Create, 0);
144 /// assert_eq!(next, Err(StoreError::StreamExhausted));
145 /// # Ok::<(), StoreError>(())
146 /// ```
147 StreamExhausted,
148}
149
150impl StoreError {
151 /// The Redis error reply text for this error, prefix included
152 /// (`WRONGTYPE …`, `ERR …`, `OOM …`) — what a RESP layer writes after
153 /// the `-`.
154 ///
155 /// ```
156 /// assert_eq!(kevy_store::StoreError::NoSuchKey.as_wire(), "ERR no such key");
157 /// ```
158 pub fn as_wire(&self) -> &'static str {
159 match self {
160 Self::WrongType => "WRONGTYPE Operation against a key holding the wrong kind of value",
161 Self::NotInteger => "ERR value is not an integer or out of range",
162 Self::Overflow => "ERR increment or decrement would overflow",
163 Self::OutOfRange => "ERR index out of range",
164 Self::NoSuchKey => "ERR no such key",
165 Self::NotFloat => "ERR value is not a valid float",
166 Self::OutOfMemory => "OOM command not allowed when used memory > 'maxmemory'.",
167 Self::StreamExhausted => {
168 "ERR The stream has exhausted the last possible ID, unable to add more items"
169 }
170 }
171 }
172}
173
174impl fmt::Display for StoreError {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 f.write_str(match self {
177 Self::WrongType => "wrong type for this operation",
178 Self::NotInteger => "value is not an integer or out of range",
179 Self::Overflow => "increment or decrement would overflow",
180 Self::OutOfRange => "index out of range",
181 Self::NoSuchKey => "no such key",
182 Self::NotFloat => "value is not a valid float",
183 Self::OutOfMemory => "maxmemory reached and the eviction policy is noeviction",
184 Self::StreamExhausted => "the stream has exhausted the last possible ID",
185 })
186 }
187}
188
189impl core::error::Error for StoreError {}
190
191/// Maxmemory eviction policy — the one type for it: `kevy-config` parses
192/// `maxmemory-policy` into it and the store enforces it.
193///
194/// ```
195/// use kevy_store::EvictionPolicy;
196/// assert_eq!(EvictionPolicy::parse("ALLKEYS-LRU"), Some(EvictionPolicy::AllKeysLru));
197/// assert_eq!(EvictionPolicy::VolatileTtl.as_str(), "volatile-ttl");
198/// assert_eq!(EvictionPolicy::default(), EvictionPolicy::NoEviction);
199/// ```
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
201#[non_exhaustive]
202pub enum EvictionPolicy {
203 /// Refuse writes once `maxmemory` is hit. Default.
204 ///
205 /// ```
206 /// use kevy_store::{EvictionPolicy, SetCondition, Store, StoreError};
207 /// let mut s = Store::new();
208 /// s.set_max_memory(1, EvictionPolicy::NoEviction);
209 /// s.set(b"k", b"v".to_vec(), None, SetCondition::Always);
210 /// // nothing is evicted; the next write is refused instead
211 /// assert_eq!(s.try_evict_after_write(), 0);
212 /// assert_eq!(s.precheck_for_write(), Err(StoreError::OutOfMemory));
213 /// ```
214 #[default]
215 NoEviction,
216 /// Approximated LRU across all keys.
217 ///
218 /// ```
219 /// use kevy_store::{EvictionPolicy, SetCondition, Store};
220 /// let mut s = Store::new();
221 /// s.set_max_memory(1, EvictionPolicy::AllKeysLru);
222 /// s.set(b"k", b"v".to_vec(), None, SetCondition::Always);
223 /// assert_eq!(s.try_evict_after_write(), 1);
224 /// assert_eq!(s.dbsize(), 0);
225 /// ```
226 AllKeysLru,
227 /// Approximated LFU across all keys.
228 ///
229 /// ```
230 /// use kevy_store::{EvictionPolicy, SetCondition, Store};
231 /// let mut s = Store::new();
232 /// s.set_max_memory(1, EvictionPolicy::AllKeysLfu);
233 /// s.set(b"k", b"v".to_vec(), None, SetCondition::Always);
234 /// assert_eq!(s.try_evict_after_write(), 1);
235 /// assert_eq!(s.evictions_total(), 1);
236 /// ```
237 AllKeysLfu,
238 /// Random key across all keys.
239 ///
240 /// ```
241 /// use kevy_store::{EvictionPolicy, SetCondition, Store};
242 /// let mut s = Store::new();
243 /// s.set_max_memory(1, EvictionPolicy::AllKeysRandom);
244 /// s.set(b"a", b"1".to_vec(), None, SetCondition::Always);
245 /// s.set(b"b", b"2".to_vec(), None, SetCondition::Always);
246 /// assert_eq!(s.try_evict_after_write(), 2);
247 /// ```
248 AllKeysRandom,
249 /// Approximated LRU across keys with a TTL.
250 ///
251 /// ```
252 /// use core::time::Duration;
253 /// use kevy_store::{EvictionPolicy, SetCondition, Store};
254 /// let mut s = Store::new();
255 /// s.set_max_memory(1, EvictionPolicy::VolatileLru);
256 /// s.set(b"cache", b"1".to_vec(), Some(Duration::from_secs(60)), SetCondition::Always);
257 /// s.set(b"durable", b"2".to_vec(), None, SetCondition::Always);
258 /// // only the key with a TTL is a candidate
259 /// assert_eq!(s.try_evict_after_write(), 1);
260 /// assert_eq!(s.exists(&[b"durable".as_slice()]), 1);
261 /// ```
262 VolatileLru,
263 /// Approximated LFU across keys with a TTL.
264 ///
265 /// ```
266 /// use core::time::Duration;
267 /// use kevy_store::{EvictionPolicy, SetCondition, Store};
268 /// let mut s = Store::new();
269 /// s.set_max_memory(1, EvictionPolicy::VolatileLfu);
270 /// s.set(b"cache", b"1".to_vec(), Some(Duration::from_secs(60)), SetCondition::Always);
271 /// s.set(b"durable", b"2".to_vec(), None, SetCondition::Always);
272 /// assert_eq!(s.try_evict_after_write(), 1);
273 /// assert_eq!(s.exists(&[b"cache".as_slice()]), 0);
274 /// ```
275 VolatileLfu,
276 /// Random key from those with a TTL.
277 ///
278 /// ```
279 /// use kevy_store::{EvictionPolicy, SetCondition, Store};
280 /// let mut s = Store::new();
281 /// s.set_max_memory(1, EvictionPolicy::VolatileRandom);
282 /// s.set(b"durable", b"2".to_vec(), None, SetCondition::Always);
283 /// // no key carries a TTL, so nothing can be evicted
284 /// assert_eq!(s.try_evict_after_write(), 0);
285 /// assert_eq!(s.dbsize(), 1);
286 /// ```
287 VolatileRandom,
288 /// Key with the shortest remaining TTL.
289 ///
290 /// ```
291 /// use core::time::Duration;
292 /// use kevy_store::{EvictionPolicy, SetCondition, Store};
293 /// let mut s = Store::new();
294 /// s.set_max_memory(1, EvictionPolicy::VolatileTtl);
295 /// s.set(b"soon", b"1".to_vec(), Some(Duration::from_secs(5)), SetCondition::Always);
296 /// s.set(b"durable", b"2".to_vec(), None, SetCondition::Always);
297 /// assert_eq!(s.try_evict_after_write(), 1);
298 /// assert_eq!(s.exists(&[b"soon".as_slice()]), 0);
299 /// ```
300 VolatileTtl,
301}
302
303impl EvictionPolicy {
304 const ALL: [Self; 8] = [
305 Self::NoEviction,
306 Self::AllKeysLru,
307 Self::AllKeysLfu,
308 Self::AllKeysRandom,
309 Self::VolatileLru,
310 Self::VolatileLfu,
311 Self::VolatileRandom,
312 Self::VolatileTtl,
313 ];
314
315 /// Canonical Redis-compatible name (`maxmemory-policy` value).
316 ///
317 /// ```
318 /// assert_eq!(kevy_store::EvictionPolicy::AllKeysLfu.as_str(), "allkeys-lfu");
319 /// ```
320 pub fn as_str(&self) -> &'static str {
321 match self {
322 Self::NoEviction => "noeviction",
323 Self::AllKeysLru => "allkeys-lru",
324 Self::AllKeysLfu => "allkeys-lfu",
325 Self::AllKeysRandom => "allkeys-random",
326 Self::VolatileLru => "volatile-lru",
327 Self::VolatileLfu => "volatile-lfu",
328 Self::VolatileRandom => "volatile-random",
329 Self::VolatileTtl => "volatile-ttl",
330 }
331 }
332
333 /// Inverse of [`Self::as_str`], ASCII case-insensitive.
334 ///
335 /// ```
336 /// use kevy_store::EvictionPolicy;
337 /// assert_eq!(EvictionPolicy::parse("Volatile-Ttl"), Some(EvictionPolicy::VolatileTtl));
338 /// assert_eq!(EvictionPolicy::parse("lru"), None);
339 /// ```
340 pub fn parse(s: &str) -> Option<Self> {
341 Self::ALL.into_iter().find(|p| p.as_str().eq_ignore_ascii_case(s))
342 }
343
344 /// Whether the policy ranks candidates by LRU clock (read-touches matter).
345 #[inline]
346 pub fn uses_lru(self) -> bool {
347 matches!(self, Self::AllKeysLru | Self::VolatileLru)
348 }
349
350 /// Whether the policy ranks candidates by LFU counter (read-touches and
351 /// log-counter increments matter).
352 #[inline]
353 pub fn uses_lfu(self) -> bool {
354 matches!(self, Self::AllKeysLfu | Self::VolatileLfu)
355 }
356
357 /// Whether the policy restricts eviction to keys that carry a TTL.
358 #[inline]
359 pub fn is_volatile(self) -> bool {
360 matches!(
361 self,
362 Self::VolatileLru | Self::VolatileLfu | Self::VolatileRandom | Self::VolatileTtl
363 )
364 }
365}