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::KevyResult;
13
14use kevy_store::{ZaddFlags, ZaddReport};
15
16use crate::store::ensure_writable;
17use crate::store::{Store, commit_write, store_err};
18
19impl Store {
20    /// Flags-aware `ZADD`. See [`ZaddFlags`]; read
21    /// [`ZaddReport::changed`] for the `CH` reply shape. The
22    /// monotonic-heal idiom is `zadd_flags(k, pairs,
23    /// ZaddFlags::new(SetCondition::Always, ScoreCompare::Greater)?)`.
24    pub fn zadd_flags(
25        &self,
26        key: &[u8],
27        pairs: &[(f64, &[u8])],
28        flags: ZaddFlags,
29    ) -> KevyResult<ZaddReport> {
30        ensure_writable(self)?;
31        let mut g = self.wshard(key);
32        let rep = g.store.zadd_flags(key, pairs, flags).map_err(store_err)?;
33        if !rep.applied.is_empty() {
34            let score_strs: Vec<Vec<u8>> =
35                rep.applied.iter().map(|(s, _)| format!("{s}").into_bytes()).collect();
36            let mut parts: Vec<&[u8]> = Vec::with_capacity(2 + rep.applied.len() * 2);
37            parts.push(b"ZADD");
38            parts.push(key);
39            for (i, (_, m)) in rep.applied.iter().enumerate() {
40                parts.push(&score_strs[i]);
41                parts.push(m);
42            }
43            commit_write(&mut g, &parts)?;
44        }
45        Ok(rep)
46    }
47
48    /// `ZADD … INCR` — a conditional `ZINCRBY`; `None` when the flags
49    /// veto the operation.
50    pub fn zadd_incr(
51        &self,
52        key: &[u8],
53        delta: f64,
54        member: &[u8],
55        flags: ZaddFlags,
56    ) -> KevyResult<Option<f64>> {
57        ensure_writable(self)?;
58        let mut g = self.wshard(key);
59        let next = g.store.zadd_incr(key, delta, member, flags).map_err(store_err)?;
60        if let Some(n) = next {
61            let s = format!("{n}");
62            commit_write(&mut g, &[b"ZADD", key, s.as_bytes(), member])?;
63        }
64        Ok(next)
65    }
66}