Skip to main content

kevy_store/stream/
group.rs

1//! Consumer groups for v2-7 streams (sprint B). The group state lives
2//! inside its parent [`crate::stream::StreamData`] so XADD / XDEL can
3//! see the group map without an extra lookup. This file owns the
4//! types + the in-stream operations; the `Store`-side wrappers live in
5//! `stream/store.rs` next to the rest of the public API.
6
7#[cfg(not(feature = "std"))]
8use crate::nostd_prelude::*;
9use alloc::collections::BTreeMap;
10
11use kevy_map::KevyMap;
12
13pub(super) use super::claim::AutoclaimResult;
14use super::{EntryBatch, StreamData, StreamId};
15use crate::StoreError;
16use crate::value::SmallBytes;
17
18/// One consumer group's state. Sorted PEL plus a map of known
19/// consumers (with cached pel_count for O(1) XINFO answers).
20#[derive(Clone)]
21pub struct ConsumerGroup {
22    /// Highest ID delivered to any consumer in this group. Bumped by
23    /// XREADGROUP with `>`; settable via XGROUP SETID.
24    pub last_delivered_id: StreamId,
25    /// Pending-Entries List: every ID delivered but not yet ACKed.
26    /// Sorted by ID for `XPENDING start end` range queries.
27    pub pel: BTreeMap<StreamId, PelEntry>,
28    /// Consumers known to this group (by name).
29    pub consumers: KevyMap<SmallBytes, Box<ConsumerState>>,
30}
31
32impl ConsumerGroup {
33    /// Highest ID delivered by this group — for `XINFO GROUPS`.
34    pub fn last_delivered_id(&self) -> StreamId {
35        self.last_delivered_id
36    }
37    /// Total pending entries — `XINFO GROUPS`'s `pending`.
38    pub fn pending_count(&self) -> usize {
39        self.pel.len()
40    }
41    /// Known consumer count — `XINFO GROUPS`'s `consumers`.
42    pub fn consumer_count(&self) -> usize {
43        self.consumers.len()
44    }
45    /// Iterate `(consumer_name, consumer)` pairs — `XINFO CONSUMERS`.
46    pub fn consumers_iter(&self) -> impl Iterator<Item = (&[u8], &ConsumerState)> {
47        self.consumers.iter().map(|(k, v)| (k.as_slice(), v.as_ref()))
48    }
49}
50
51impl ConsumerState {
52    /// `XINFO CONSUMERS`' `pending` field.
53    pub fn pending_count(&self) -> usize {
54        self.pel_count
55    }
56    /// Last unix-ms this consumer interacted with the group.
57    pub fn last_seen_ms(&self) -> u64 {
58        self.last_seen_ms
59    }
60}
61
62impl Default for ConsumerGroup {
63    fn default() -> Self {
64        Self {
65            last_delivered_id: StreamId::MIN,
66            pel: BTreeMap::new(),
67            consumers: KevyMap::default(),
68        }
69    }
70}
71
72/// One pending entry: who got it, when, and how many times.
73#[derive(Clone, Debug)]
74pub struct PelEntry {
75    /// Owning consumer's name. Used by XPENDING's `consumer` filter
76    /// and XCLAIM's ownership transfer.
77    pub consumer: SmallBytes,
78    /// Last delivery wall-clock (unix-ms). XCLAIM compares idle =
79    /// `now - delivery_time_ms` against its `min-idle-ms` arg.
80    pub delivery_time_ms: u64,
81    /// Number of times this entry has been delivered (=1 on first
82    /// XREADGROUP, +=1 on each XCLAIM that doesn't have JUSTID).
83    pub delivery_count: u32,
84}
85
86/// Per-consumer cached counters so `XINFO CONSUMERS` answers in O(1).
87#[derive(Clone, Debug)]
88#[allow(dead_code)]
89pub struct ConsumerState {
90    /// Consumer name. Read by XINFO CONSUMERS (sprint C).
91    pub name: SmallBytes,
92    /// Last wall-clock (unix-ms) the consumer interacted with the
93    /// group (any XREADGROUP / XACK / XCLAIM touch).
94    pub last_seen_ms: u64,
95    /// Cached size of this consumer's slice of the PEL.
96    pub pel_count: usize,
97}
98
99/// `XGROUP CREATE` ID argument: either an explicit ID or `$`
100/// (= current stream's `last_id`, resolved by the caller).
101#[derive(Clone, Copy, Debug, PartialEq, Eq)]
102pub enum GroupCreateMode {
103    /// `<ms>-<seq>` literal — the group's `last_delivered_id` starts here.
104    AtId(StreamId),
105    /// `$` — resolve to the stream's current `last_id` at create time.
106    AtCurrent,
107}
108
109/// Summary form of `XPENDING key group` (only 3 args): total pending,
110/// min/max IDs across the PEL, and per-consumer aggregate counts.
111pub struct PendingSummary {
112    /// Total pending entries across all consumers.
113    pub total: u64,
114    /// Smallest and largest pending IDs, or `None` if the PEL is empty.
115    pub id_range: Option<(StreamId, StreamId)>,
116    /// `(consumer, count)` pairs in arbitrary order.
117    pub by_consumer: Vec<(Vec<u8>, u64)>,
118}
119
120/// Extended form of `XPENDING key group [IDLE ms] start end count
121/// [consumer]`: one row per matching PEL entry.
122pub struct PendingExtended {
123    /// Per-entry rows in ID-ascending order.
124    pub rows: Vec<PendingExtendedRow>,
125}
126
127/// One row of the extended XPENDING reply.
128pub struct PendingExtendedRow {
129    /// Entry ID.
130    pub id: StreamId,
131    /// Owning consumer's name.
132    pub consumer: Vec<u8>,
133    /// Idle time in milliseconds (now - delivery_time_ms).
134    pub idle_ms: u64,
135    /// Delivery count.
136    pub delivery_count: u32,
137}
138
139/// Knobs for [`crate::StreamData`]'s `xclaim`: `min-idle-ms` plus the
140/// `IDLE`/`TIME`/`RETRYCOUNT`/`FORCE`/`JUSTID` flag tail.
141pub struct XClaimOpts {
142    /// Only claim entries idle for at least this many ms.
143    pub min_idle_ms: u64,
144    /// Override post-claim idle to this many ms (else 0 — XCLAIM resets
145    /// the clock so the new owner has the full idle window).
146    pub idle_override_ms: Option<u64>,
147    /// Override post-claim delivery_time_ms to this absolute unix-ms.
148    /// Takes precedence over `idle_override_ms` if both set.
149    pub time_override_ms: Option<u64>,
150    /// Override post-claim `delivery_count` (else +=1).
151    pub retrycount_override: Option<u32>,
152    /// `FORCE`: claim even if the entry isn't in the PEL yet (creates
153    /// a fresh PEL row with delivery_count=1).
154    pub force: bool,
155    /// `JUSTID`: skip the +=1 on `delivery_count` (used by tools that
156    /// don't intend a real redelivery).
157    pub justid: bool,
158}
159
160impl StreamData {
161    /// `XGROUP CREATE key group <id|$> [MKSTREAM]`. Returns `true` if
162    /// a new group was created; `false` if the group already existed
163    /// (caller should report Redis's `-BUSYGROUP` error in that case).
164    pub fn group_create(&mut self, name: &[u8], mode: GroupCreateMode) -> Result<bool, StoreError> {
165        if self.groups.contains_key(name) {
166            return Ok(false);
167        }
168        let last_delivered_id = match mode {
169            GroupCreateMode::AtId(id) => id,
170            GroupCreateMode::AtCurrent => self.last_id,
171        };
172        self.groups.insert(
173            SmallBytes::from_slice(name),
174            Box::new(ConsumerGroup {
175                last_delivered_id,
176                pel: BTreeMap::new(),
177                consumers: KevyMap::default(),
178            }),
179        );
180        Ok(true)
181    }
182
183    /// `XGROUP DESTROY key group`. Returns `true` if a group was dropped.
184    pub fn group_destroy(&mut self, name: &[u8]) -> bool {
185        self.groups.remove(name).is_some()
186    }
187
188    /// `XGROUP SETID key group <id|$>`. Returns `false` if the group
189    /// doesn't exist.
190    pub fn group_setid(&mut self, name: &[u8], mode: GroupCreateMode) -> bool {
191        let Some(g) = self.groups.get_mut(name) else {
192            return false;
193        };
194        g.last_delivered_id = match mode {
195            GroupCreateMode::AtId(id) => id,
196            GroupCreateMode::AtCurrent => self.last_id,
197        };
198        true
199    }
200
201    /// `XGROUP CREATECONSUMER key group consumer`. Returns `true` if a
202    /// new consumer was inserted, `false` if it already existed or the
203    /// group is missing.
204    pub fn group_create_consumer(&mut self, group: &[u8], consumer: &[u8], now_ms: u64) -> bool {
205        let Some(g) = self.groups.get_mut(group) else {
206            return false;
207        };
208        if g.consumers.contains_key(consumer) {
209            return false;
210        }
211        g.consumers.insert(
212            SmallBytes::from_slice(consumer),
213            Box::new(ConsumerState {
214                name: SmallBytes::from_slice(consumer),
215                last_seen_ms: now_ms,
216                pel_count: 0,
217            }),
218        );
219        true
220    }
221
222    /// `XGROUP DELCONSUMER key group consumer`. Returns the number of
223    /// PEL entries dropped along with the consumer (matches Redis).
224    pub fn group_del_consumer(&mut self, group: &[u8], consumer: &[u8]) -> u64 {
225        let Some(g) = self.groups.get_mut(group) else {
226            return 0;
227        };
228        let dropped = g.pel.len();
229        g.pel.retain(|_, p| p.consumer.as_slice() != consumer);
230        let dropped = dropped - g.pel.len();
231        g.consumers.remove(consumer);
232        dropped as u64
233    }
234
235    /// `XREADGROUP GROUP g c [COUNT n] STREAMS key id`. ID `>` →
236    /// "new entries since last_delivered_id" (updates last_delivered);
237    /// ID `<x>` → "PEL entries for this consumer with id > x" (does
238    /// NOT update last_delivered, used for replay).
239    pub fn readgroup(
240        &mut self,
241        group: &[u8],
242        consumer: &[u8],
243        last_seen_arg: ReadGroupId,
244        count: Option<usize>,
245        noack: bool,
246        now_ms: u64,
247    ) -> Result<EntryBatch, StoreError> {
248        let Some(g) = self.groups.get_mut(group) else {
249            return Err(StoreError::NoSuchKey);
250        };
251        let consumer_smb = SmallBytes::from_slice(consumer);
252        ensure_consumer(g, &consumer_smb, now_ms);
253        if let Some(cs) = g.consumers.get_mut(consumer_smb.as_slice()) {
254            cs.last_seen_ms = now_ms;
255        }
256        match last_seen_arg {
257            ReadGroupId::New => {
258                let start = g.last_delivered_id.next();
259                let entries: Vec<(StreamId, &[(SmallBytes, SmallBytes)])> = self
260                    .entries
261                    .range(start..=StreamId::MAX)
262                    .map(|(id, fv)| (*id, fv.as_slice()))
263                    .collect();
264                let take = match count {
265                    Some(n) => entries.into_iter().take(n).collect::<Vec<_>>(),
266                    None => entries,
267                };
268                if take.is_empty() {
269                    return Ok(Vec::new());
270                }
271                if !noack {
272                    record_deliveries(g, &consumer_smb, &take, now_ms);
273                }
274                let g_mut = self.groups.get_mut(group).expect("present");
275                if let Some((last_id, _)) = take.last() {
276                    g_mut.last_delivered_id = *last_id;
277                }
278                Ok(super::clone_entries(take))
279            }
280            ReadGroupId::ReplayAfter(after) => {
281                Ok(replay_pel_entries(g, &self.entries, &consumer_smb, after, count))
282            }
283        }
284    }
285
286    /// `XACK key group id [...]`. Returns count of PEL entries removed.
287    pub fn ack(&mut self, group: &[u8], ids: &[StreamId]) -> u64 {
288        let Some(g) = self.groups.get_mut(group) else {
289            return 0;
290        };
291        let mut n = 0u64;
292        for id in ids {
293            if let Some(p) = g.pel.remove(id) {
294                if let Some(cs) = g.consumers.get_mut(p.consumer.as_slice()) {
295                    cs.pel_count = cs.pel_count.saturating_sub(1);
296                }
297                n += 1;
298            }
299        }
300        n
301    }
302
303    /// `XPENDING key group` — the summary form (4-tuple).
304    pub fn pending_summary(&self, group: &[u8]) -> Option<PendingSummary> {
305        let g = self.groups.get(group)?;
306        let total = g.pel.len() as u64;
307        let id_range = match (g.pel.keys().next(), g.pel.keys().next_back()) {
308            (Some(lo), Some(hi)) => Some((*lo, *hi)),
309            _ => None,
310        };
311        let mut counts: Vec<(Vec<u8>, u64)> = Vec::new();
312        for p in g.pel.values() {
313            if let Some((_, n)) = counts.iter_mut().find(|(name, _)| name == p.consumer.as_slice())
314            {
315                *n += 1;
316            } else {
317                counts.push((p.consumer.to_vec(), 1));
318            }
319        }
320        Some(PendingSummary { total, id_range, by_consumer: counts })
321    }
322
323    /// `XPENDING key group [IDLE ms] start end count [consumer]`.
324    #[allow(clippy::too_many_arguments)]
325    pub fn pending_extended(
326        &self,
327        group: &[u8],
328        idle_min_ms: Option<u64>,
329        start: StreamId,
330        end: StreamId,
331        count: usize,
332        consumer_filter: Option<&[u8]>,
333        now_ms: u64,
334    ) -> Option<PendingExtended> {
335        let g = self.groups.get(group)?;
336        let mut rows = Vec::with_capacity(count.min(g.pel.len()));
337        for (id, p) in g.pel.range(start..=end) {
338            if rows.len() >= count {
339                break;
340            }
341            let idle = now_ms.saturating_sub(p.delivery_time_ms);
342            if let Some(min) = idle_min_ms
343                && idle < min
344            {
345                continue;
346            }
347            if let Some(c) = consumer_filter
348                && p.consumer.as_slice() != c
349            {
350                continue;
351            }
352            rows.push(PendingExtendedRow {
353                id: *id,
354                consumer: p.consumer.to_vec(),
355                idle_ms: idle,
356                delivery_count: p.delivery_count,
357            });
358        }
359        Some(PendingExtended { rows })
360    }
361}
362
363/// XREADGROUP's per-stream ID: either `>` (= new entries) or an explicit
364/// "after this id" for PEL replay.
365#[derive(Clone, Copy, Debug, PartialEq, Eq)]
366pub enum ReadGroupId {
367    /// `>` — new entries only.
368    New,
369    /// `<id>` — replay PEL entries strictly after this id.
370    ReplayAfter(StreamId),
371}
372
373/// Idempotent insert: ensure the named consumer exists in this group's
374/// roster so subsequent `pel_count`/`last_seen_ms` updates have a slot.
375/// The `XREADGROUP … <id>` replay arm: PEL entries owned by `consumer`
376/// with id strictly after `after`, joined against the live entry map
377/// (XDEL'd tombstones are skipped), capped at `count`.
378fn replay_pel_entries(
379    g: &ConsumerGroup,
380    entries: &alloc::collections::BTreeMap<StreamId, Vec<(SmallBytes, SmallBytes)>>,
381    consumer: &SmallBytes,
382    after: StreamId,
383    count: Option<usize>,
384) -> EntryBatch {
385    let mut hit: Vec<(StreamId, Vec<(SmallBytes, SmallBytes)>)> = Vec::new();
386    for (id, pel_entry) in g.pel.range(after.next()..=StreamId::MAX) {
387        if pel_entry.consumer != *consumer {
388            continue;
389        }
390        if let Some(fv) = entries.get(id) {
391            hit.push((*id, fv.clone()));
392        }
393        if let Some(n) = count
394            && hit.len() >= n
395        {
396            break;
397        }
398    }
399    hit.into_iter()
400        .map(|(id, fv)| (id, fv.iter().map(|(f, v)| (f.to_vec(), v.to_vec())).collect()))
401        .collect()
402}
403
404pub(super) fn ensure_consumer(g: &mut ConsumerGroup, name: &SmallBytes, now_ms: u64) {
405    if g.consumers.get(name.as_slice()).is_none() {
406        g.consumers.insert(
407            name.clone(),
408            Box::new(ConsumerState { name: name.clone(), last_seen_ms: now_ms, pel_count: 0 }),
409        );
410    }
411}
412
413fn record_deliveries(
414    g: &mut ConsumerGroup,
415    consumer: &SmallBytes,
416    entries: &[(StreamId, &[(SmallBytes, SmallBytes)])],
417    now_ms: u64,
418) {
419    let mut new_for_consumer = 0usize;
420    for (id, _) in entries {
421        let entry = g.pel.entry(*id).or_insert_with(|| {
422            new_for_consumer += 1;
423            PelEntry { consumer: consumer.clone(), delivery_time_ms: now_ms, delivery_count: 0 }
424        });
425        if entry.consumer != *consumer {
426            // Ownership transfer via the read path is unusual; Redis
427            // does it on `>` reads only when the PEL already had an
428            // entry from a previous owner — treat as XCLAIM-style.
429            if let Some(prev) = g.consumers.get_mut(entry.consumer.as_slice()) {
430                prev.pel_count = prev.pel_count.saturating_sub(1);
431            }
432            entry.consumer = consumer.clone();
433            new_for_consumer += 1;
434        }
435        entry.delivery_time_ms = now_ms;
436        entry.delivery_count = entry.delivery_count.saturating_add(1);
437    }
438    if let Some(cs) = g.consumers.get_mut(consumer.as_slice()) {
439        cs.pel_count = cs.pel_count.saturating_add(new_for_consumer);
440    }
441}