Skip to main content

kevy_embedded/
ops_zset_flags.rs

1//! `ZADD` condition-flag surfaces (Redis 6.2 `NX`/`XX`/`GT`/`LT`/`CH`
2//! + the `INCR` form). The plain `zadd` hot path is untouched.
3//!
4//! AOF form: the **effect** is logged, never the condition — applied
5//! pairs go into the log as plain unconditional `ZADD` (and the
6//! `INCR` form as `ZADD key <new-absolute-score> member`). A
7//! conditional verb replayed against divergent state (a replica
8//! applying frames onto snapshot-loaded state) could veto differently
9//! and diverge; the absolute form is deterministic. Same lesson as
10//! the SPOP→SREM propagation fix (log the effect, not the verb).
11
12use crate::{KevyError, KevyResult};
13
14use kevy_store::{ZaddFlags, ZaddReport};
15
16use crate::store::ensure_writable;
17use crate::store::{Store, commit_write, store_err};
18
19fn reject_invalid(flags: ZaddFlags) -> KevyResult<()> {
20    if flags.valid() {
21        Ok(())
22    } else {
23        Err(KevyError::InvalidInput(
24            "GT, LT, and/or NX options at the same time are not compatible".into(),
25        ))
26    }
27}
28
29impl Store {
30    /// Flags-aware `ZADD`. See [`ZaddFlags`]; read
31    /// [`ZaddReport::changed`] for the `CH` reply shape. The
32    /// monotonic-heal idiom is `zadd_flags(k, pairs, ZaddFlags { gt:
33    /// true, ..Default::default() })`.
34    pub fn zadd_flags(
35        &self,
36        key: &[u8],
37        pairs: &[(f64, &[u8])],
38        flags: ZaddFlags,
39    ) -> KevyResult<ZaddReport> {
40        reject_invalid(flags)?;
41        ensure_writable(self)?;
42        let mut g = self.wshard(key);
43        let rep = g.store.zadd_flags(key, pairs, flags).map_err(store_err)?;
44        if !rep.applied.is_empty() {
45            let score_strs: Vec<Vec<u8>> =
46                rep.applied.iter().map(|(s, _)| format!("{s}").into_bytes()).collect();
47            let mut parts: Vec<&[u8]> = Vec::with_capacity(2 + rep.applied.len() * 2);
48            parts.push(b"ZADD");
49            parts.push(key);
50            for (i, (_, m)) in rep.applied.iter().enumerate() {
51                parts.push(&score_strs[i]);
52                parts.push(m);
53            }
54            commit_write(&mut g, &parts)?;
55        }
56        Ok(rep)
57    }
58
59    /// `ZADD … INCR` — a conditional `ZINCRBY`; `None` when the flags
60    /// veto the operation.
61    pub fn zadd_incr(
62        &self,
63        key: &[u8],
64        delta: f64,
65        member: &[u8],
66        flags: ZaddFlags,
67    ) -> KevyResult<Option<f64>> {
68        reject_invalid(flags)?;
69        ensure_writable(self)?;
70        let mut g = self.wshard(key);
71        let next = g.store.zadd_incr(key, delta, member, flags).map_err(store_err)?;
72        if let Some(n) = next {
73            let s = format!("{n}");
74            commit_write(&mut g, &[b"ZADD", key, s.as_bytes(), member])?;
75        }
76        Ok(next)
77    }
78}