Skip to main content

redis_tower_commands/
streams.rs

1//! Redis Streams, consumer groups, pending entries, and acknowledgements.
2//!
3//! [`XAdd`] returns an entry ID, range/read commands return structured
4//! [`StreamEntry`] values, and group acknowledgement returns a count. A read
5//! with `BLOCK` is a blocking operation: run it on a dedicated connection or
6//! an independently dispatched pool slot, never a shared multiplexed worker.
7//!
8//! ```
9//! use redis_tower_commands::{XAdd, XRead};
10//! use redis_tower_core::Command;
11//!
12//! let add = XAdd::new("events").field("kind", "created");
13//! let read = XRead::new("events", "0-0").count(10);
14//! assert_eq!((add.name(), read.name()), ("XADD", "XREAD"));
15//! ```
16//!
17//! See the [command cookbook] for groups, blocking ownership, and shutdown.
18//!
19//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#streams-consumer-groups-and-blocking-reads
20
21use bytes::Bytes;
22use redis_tower_core::{Command, Frame, RedisError};
23use redis_tower_protocol::helpers::{array, bulk};
24
25use crate::CommandArg;
26
27/// A stream entry: an ID and a list of field-value pairs.
28#[derive(Debug, Clone, PartialEq)]
29pub struct StreamEntry {
30    /// Redis stream entry ID.
31    pub id: String,
32    /// Ordered field-value pairs stored in the entry.
33    pub fields: Vec<(Bytes, Bytes)>,
34}
35
36/// XADD key \[NOMKSTREAM\] \[MAXLEN|MINID \[=|~\] threshold\] \[*|id\] field value \[field value ...\]
37///
38/// Appends an entry to a stream. Returns the entry ID.
39#[derive(Clone)]
40pub struct XAdd {
41    key: CommandArg,
42    id: CommandArg,
43    fields: Vec<(CommandArg, CommandArg)>,
44    nomkstream: bool,
45    maxlen: Option<(bool, u64)>,       // (approximate, count)
46    minid: Option<(bool, CommandArg)>, // (approximate, id)
47}
48
49impl XAdd {
50    /// Create an XADD with auto-generated ID (*).
51    pub fn new(key: impl Into<CommandArg>) -> Self {
52        Self {
53            key: key.into(),
54            id: "*".into(),
55            fields: Vec::new(),
56            nomkstream: false,
57            maxlen: None,
58            minid: None,
59        }
60    }
61
62    /// Set a specific entry ID instead of auto-generated.
63    pub fn id(mut self, id: impl Into<CommandArg>) -> Self {
64        self.id = id.into();
65        self
66    }
67
68    /// Add a field-value pair.
69    pub fn field(mut self, name: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
70        self.fields.push((name.into(), value.into()));
71        self
72    }
73
74    /// Don't create the stream if it doesn't exist.
75    pub fn nomkstream(mut self) -> Self {
76        self.nomkstream = true;
77        self
78    }
79
80    /// Trim stream to approximately `count` entries.
81    pub fn maxlen_approx(mut self, count: u64) -> Self {
82        self.maxlen = Some((true, count));
83        self.minid = None;
84        self
85    }
86
87    /// Trim stream to exactly `count` entries.
88    pub fn maxlen(mut self, count: u64) -> Self {
89        self.maxlen = Some((false, count));
90        self.minid = None;
91        self
92    }
93}
94
95impl Command for XAdd {
96    type Response = String;
97
98    fn to_frame(&self) -> Frame {
99        let mut args = vec![bulk("XADD"), bulk(self.key.as_bytes())];
100        if self.nomkstream {
101            args.push(bulk("NOMKSTREAM"));
102        }
103        if let Some((approx, count)) = &self.maxlen {
104            args.push(bulk("MAXLEN"));
105            if *approx {
106                args.push(bulk("~"));
107            }
108            args.push(bulk(count.to_string()));
109        }
110        if let Some((approx, id)) = &self.minid {
111            args.push(bulk("MINID"));
112            if *approx {
113                args.push(bulk("~"));
114            }
115            args.push(bulk(id.as_bytes()));
116        }
117        args.push(bulk(self.id.as_bytes()));
118        for (name, value) in &self.fields {
119            args.push(bulk(name.as_bytes()));
120            args.push(bulk(value.as_bytes()));
121        }
122        array(args)
123    }
124
125    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
126        match frame {
127            Frame::BulkString(Some(b)) => Ok(String::from_utf8_lossy(&b).into_owned()),
128            other => Err(RedisError::UnexpectedResponse {
129                expected: "bulk string (entry ID)",
130                actual: format!("{other:?}"),
131            }),
132        }
133    }
134
135    fn name(&self) -> &str {
136        "XADD"
137    }
138}
139
140/// The required initial configuration option for [`XCfgSet`].
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142pub enum XCfgSetOption {
143    /// Set how long idempotency IDs are retained, in seconds.
144    IdmpDuration(u64),
145    /// Set the maximum number of idempotency IDs retained per producer.
146    IdmpMaxSize(u64),
147}
148
149/// XCFGSET key \[IDMP-DURATION idmp-duration\] \[IDMP-MAXSIZE idmp-maxsize\]
150///
151/// Sets the idempotent message processing (IDMP) configuration for an
152/// existing stream (Redis 8.6+). Changing the configuration clears the
153/// stream's producer IDMP maps. The command is therefore not retry-safe: a
154/// repeated execution could erase IDs recorded after the first execution.
155#[derive(Clone)]
156pub struct XCfgSet {
157    key: CommandArg,
158    idmp_duration: Option<u64>,
159    idmp_maxsize: Option<u64>,
160}
161
162impl XCfgSet {
163    /// Create an XCFGSET command with its required initial option.
164    pub fn new(key: impl Into<CommandArg>, option: XCfgSetOption) -> Self {
165        let (idmp_duration, idmp_maxsize) = match option {
166            XCfgSetOption::IdmpDuration(seconds) => (Some(seconds), None),
167            XCfgSetOption::IdmpMaxSize(entries) => (None, Some(entries)),
168        };
169        Self {
170            key: key.into(),
171            idmp_duration,
172            idmp_maxsize,
173        }
174    }
175
176    /// Set how long idempotency IDs are retained, in seconds.
177    ///
178    /// Redis accepts values from 1 through 86,400.
179    pub fn idmp_duration(mut self, seconds: u64) -> Self {
180        self.idmp_duration = Some(seconds);
181        self
182    }
183
184    /// Set the maximum number of idempotency IDs retained per producer.
185    ///
186    /// Redis accepts values from 1 through 10,000.
187    pub fn idmp_maxsize(mut self, entries: u64) -> Self {
188        self.idmp_maxsize = Some(entries);
189        self
190    }
191}
192
193impl Command for XCfgSet {
194    type Response = ();
195
196    fn to_frame(&self) -> Frame {
197        let mut args = vec![bulk("XCFGSET"), bulk(self.key.as_bytes())];
198        if let Some(seconds) = self.idmp_duration {
199            args.push(bulk("IDMP-DURATION"));
200            args.push(bulk(seconds.to_string()));
201        }
202        if let Some(entries) = self.idmp_maxsize {
203            args.push(bulk("IDMP-MAXSIZE"));
204            args.push(bulk(entries.to_string()));
205        }
206        array(args)
207    }
208
209    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
210        match frame {
211            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
212            other => Err(RedisError::UnexpectedResponse {
213                expected: "OK",
214                actual: format!("{other:?}"),
215            }),
216        }
217    }
218
219    fn name(&self) -> &str {
220        "XCFGSET"
221    }
222}
223
224/// XIDMPRECORD key pid iid stream-id
225///
226/// Sets IDMP metadata on an existing stream entry. This is an internal Redis
227/// command used when replaying append-only files; applications should normally
228/// use the IDMP options on `XADD` instead.
229#[derive(Clone)]
230pub struct XIdmpRecord {
231    key: CommandArg,
232    producer_id: CommandArg,
233    idempotency_id: CommandArg,
234    stream_id: CommandArg,
235}
236
237impl XIdmpRecord {
238    /// Create an XIDMPRECORD command.
239    pub fn new(
240        key: impl Into<CommandArg>,
241        producer_id: impl Into<CommandArg>,
242        idempotency_id: impl Into<CommandArg>,
243        stream_id: impl Into<CommandArg>,
244    ) -> Self {
245        Self {
246            key: key.into(),
247            producer_id: producer_id.into(),
248            idempotency_id: idempotency_id.into(),
249            stream_id: stream_id.into(),
250        }
251    }
252}
253
254impl Command for XIdmpRecord {
255    type Response = ();
256
257    fn to_frame(&self) -> Frame {
258        array(vec![
259            bulk("XIDMPRECORD"),
260            bulk(self.key.as_bytes()),
261            bulk(self.producer_id.as_bytes()),
262            bulk(self.idempotency_id.as_bytes()),
263            bulk(self.stream_id.as_bytes()),
264        ])
265    }
266
267    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
268        match frame {
269            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
270            other => Err(RedisError::UnexpectedResponse {
271                expected: "OK",
272                actual: format!("{other:?}"),
273            }),
274        }
275    }
276
277    fn name(&self) -> &str {
278        "XIDMPRECORD"
279    }
280
281    fn idempotent(&self) -> bool {
282        true
283    }
284}
285
286/// XLEN key
287///
288/// Returns the number of entries in a stream.
289#[derive(Clone)]
290pub struct XLen {
291    key: CommandArg,
292}
293
294impl XLen {
295    /// Create a new [`XLen`] command.
296    pub fn new(key: impl Into<CommandArg>) -> Self {
297        Self { key: key.into() }
298    }
299}
300
301impl Command for XLen {
302    type Response = i64;
303
304    fn to_frame(&self) -> Frame {
305        array(vec![bulk("XLEN"), bulk(self.key.as_bytes())])
306    }
307
308    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
309        match frame {
310            Frame::Integer(n) => Ok(n),
311            other => Err(RedisError::UnexpectedResponse {
312                expected: "integer",
313                actual: format!("{other:?}"),
314            }),
315        }
316    }
317
318    fn name(&self) -> &str {
319        "XLEN"
320    }
321}
322
323/// XRANGE key start end \[COUNT count\]
324///
325/// Returns entries in a stream within a range of IDs.
326#[derive(Clone)]
327pub struct XRange {
328    key: CommandArg,
329    start: CommandArg,
330    end: CommandArg,
331    count: Option<u64>,
332}
333
334impl XRange {
335    /// Query all entries: start="-", end="+".
336    pub fn all(key: impl Into<CommandArg>) -> Self {
337        Self {
338            key: key.into(),
339            start: "-".into(),
340            end: "+".into(),
341            count: None,
342        }
343    }
344
345    /// Query a specific range.
346    pub fn new(
347        key: impl Into<CommandArg>,
348        start: impl Into<CommandArg>,
349        end: impl Into<CommandArg>,
350    ) -> Self {
351        Self {
352            key: key.into(),
353            start: start.into(),
354            end: end.into(),
355            count: None,
356        }
357    }
358
359    /// Limit the number of returned entries.
360    pub fn count(mut self, n: u64) -> Self {
361        self.count = Some(n);
362        self
363    }
364}
365
366impl Command for XRange {
367    type Response = Vec<StreamEntry>;
368
369    fn to_frame(&self) -> Frame {
370        let mut args = vec![
371            bulk("XRANGE"),
372            bulk(self.key.as_bytes()),
373            bulk(self.start.as_bytes()),
374            bulk(self.end.as_bytes()),
375        ];
376        if let Some(n) = self.count {
377            args.push(bulk("COUNT"));
378            args.push(bulk(n.to_string()));
379        }
380        array(args)
381    }
382
383    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
384        parse_stream_entries(&frame)
385    }
386
387    fn name(&self) -> &str {
388        "XRANGE"
389    }
390}
391
392/// XREVRANGE key end start \[COUNT count\]
393///
394/// Like XRANGE but in reverse order.
395#[derive(Clone)]
396pub struct XRevRange {
397    key: CommandArg,
398    end: CommandArg,
399    start: CommandArg,
400    count: Option<u64>,
401}
402
403impl XRevRange {
404    /// Create the [`XRevRange`] command using the `all` form.
405    pub fn all(key: impl Into<CommandArg>) -> Self {
406        Self {
407            key: key.into(),
408            end: "+".into(),
409            start: "-".into(),
410            count: None,
411        }
412    }
413
414    /// Create a new [`XRevRange`] command.
415    pub fn new(
416        key: impl Into<CommandArg>,
417        end: impl Into<CommandArg>,
418        start: impl Into<CommandArg>,
419    ) -> Self {
420        Self {
421            key: key.into(),
422            end: end.into(),
423            start: start.into(),
424            count: None,
425        }
426    }
427
428    /// Configure the `count` option.
429    pub fn count(mut self, n: u64) -> Self {
430        self.count = Some(n);
431        self
432    }
433}
434
435impl Command for XRevRange {
436    type Response = Vec<StreamEntry>;
437
438    fn to_frame(&self) -> Frame {
439        let mut args = vec![
440            bulk("XREVRANGE"),
441            bulk(self.key.as_bytes()),
442            bulk(self.end.as_bytes()),
443            bulk(self.start.as_bytes()),
444        ];
445        if let Some(n) = self.count {
446            args.push(bulk("COUNT"));
447            args.push(bulk(n.to_string()));
448        }
449        array(args)
450    }
451
452    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
453        parse_stream_entries(&frame)
454    }
455
456    fn name(&self) -> &str {
457        "XREVRANGE"
458    }
459}
460
461/// XDEL key id \[id ...\]
462///
463/// Removes entries from a stream. Returns the number deleted.
464#[derive(Clone)]
465pub struct XDel {
466    key: CommandArg,
467    ids: Vec<CommandArg>,
468}
469
470impl XDel {
471    /// Create a new [`XDel`] command.
472    pub fn new(key: impl Into<CommandArg>, id: impl Into<CommandArg>) -> Self {
473        Self {
474            key: key.into(),
475            ids: vec![id.into()],
476        }
477    }
478
479    /// Create the [`XDel`] command for the supplied ids.
480    pub fn ids(
481        key: impl Into<CommandArg>,
482        ids: impl IntoIterator<Item = impl Into<CommandArg>>,
483    ) -> Self {
484        Self {
485            key: key.into(),
486            ids: ids.into_iter().map(Into::into).collect(),
487        }
488    }
489}
490
491impl Command for XDel {
492    type Response = i64;
493
494    fn to_frame(&self) -> Frame {
495        let mut args = vec![bulk("XDEL"), bulk(self.key.as_bytes())];
496        for id in &self.ids {
497            args.push(bulk(id.as_bytes()));
498        }
499        array(args)
500    }
501
502    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
503        match frame {
504            Frame::Integer(n) => Ok(n),
505            other => Err(RedisError::UnexpectedResponse {
506                expected: "integer",
507                actual: format!("{other:?}"),
508            }),
509        }
510    }
511
512    fn name(&self) -> &str {
513        "XDEL"
514    }
515}
516
517/// XTRIM key MAXLEN|MINID \[=|~\] threshold
518///
519/// Trims a stream. Returns the number of entries deleted.
520#[derive(Clone)]
521pub struct XTrim {
522    key: CommandArg,
523    maxlen: Option<(bool, u64)>,
524    minid: Option<(bool, CommandArg)>,
525}
526
527impl XTrim {
528    /// Create the [`XTrim`] command using the `maxlen` form.
529    pub fn maxlen(key: impl Into<CommandArg>, count: u64) -> Self {
530        Self {
531            key: key.into(),
532            maxlen: Some((false, count)),
533            minid: None,
534        }
535    }
536
537    /// Create the [`XTrim`] command using the `maxlen_approx` form.
538    pub fn maxlen_approx(key: impl Into<CommandArg>, count: u64) -> Self {
539        Self {
540            key: key.into(),
541            maxlen: Some((true, count)),
542            minid: None,
543        }
544    }
545
546    /// Create the [`XTrim`] command using the `minid` form.
547    pub fn minid(key: impl Into<CommandArg>, id: impl Into<CommandArg>) -> Self {
548        Self {
549            key: key.into(),
550            maxlen: None,
551            minid: Some((false, id.into())),
552        }
553    }
554}
555
556impl Command for XTrim {
557    type Response = i64;
558
559    fn to_frame(&self) -> Frame {
560        let mut args = vec![bulk("XTRIM"), bulk(self.key.as_bytes())];
561        if let Some((approx, count)) = &self.maxlen {
562            args.push(bulk("MAXLEN"));
563            if *approx {
564                args.push(bulk("~"));
565            }
566            args.push(bulk(count.to_string()));
567        }
568        if let Some((approx, id)) = &self.minid {
569            args.push(bulk("MINID"));
570            if *approx {
571                args.push(bulk("~"));
572            }
573            args.push(bulk(id.as_bytes()));
574        }
575        array(args)
576    }
577
578    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
579        match frame {
580            Frame::Integer(n) => Ok(n),
581            other => Err(RedisError::UnexpectedResponse {
582                expected: "integer",
583                actual: format!("{other:?}"),
584            }),
585        }
586    }
587
588    fn name(&self) -> &str {
589        "XTRIM"
590    }
591}
592
593/// XACK key group id \[id ...\]
594///
595/// Acknowledges stream entries in a consumer group. Returns count acknowledged.
596#[derive(Clone)]
597pub struct XAck {
598    key: CommandArg,
599    group: CommandArg,
600    ids: Vec<CommandArg>,
601}
602
603impl XAck {
604    /// Create a new [`XAck`] command.
605    pub fn new(
606        key: impl Into<CommandArg>,
607        group: impl Into<CommandArg>,
608        id: impl Into<CommandArg>,
609    ) -> Self {
610        Self {
611            key: key.into(),
612            group: group.into(),
613            ids: vec![id.into()],
614        }
615    }
616
617    /// Create the [`XAck`] command for the supplied ids.
618    pub fn ids(
619        key: impl Into<CommandArg>,
620        group: impl Into<CommandArg>,
621        ids: impl IntoIterator<Item = impl Into<CommandArg>>,
622    ) -> Self {
623        Self {
624            key: key.into(),
625            group: group.into(),
626            ids: ids.into_iter().map(Into::into).collect(),
627        }
628    }
629}
630
631impl Command for XAck {
632    type Response = i64;
633
634    fn to_frame(&self) -> Frame {
635        let mut args = vec![
636            bulk("XACK"),
637            bulk(self.key.as_bytes()),
638            bulk(self.group.as_bytes()),
639        ];
640        for id in &self.ids {
641            args.push(bulk(id.as_bytes()));
642        }
643        array(args)
644    }
645
646    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
647        match frame {
648            Frame::Integer(n) => Ok(n),
649            other => Err(RedisError::UnexpectedResponse {
650                expected: "integer",
651                actual: format!("{other:?}"),
652            }),
653        }
654    }
655
656    fn name(&self) -> &str {
657        "XACK"
658    }
659}
660
661/// Delivery-counter behavior for `XNACK` (Redis 8.8+).
662#[derive(Debug, Clone, Copy, PartialEq, Eq)]
663pub enum XNackMode {
664    /// Decrement the delivery counter, undoing the current delivery.
665    Silent,
666    /// Leave the delivery counter unchanged.
667    Fail,
668    /// Set the delivery counter to Redis's maximum value.
669    Fatal,
670}
671
672impl XNackMode {
673    fn as_str(&self) -> &str {
674        match self {
675            Self::Silent => "SILENT",
676            Self::Fail => "FAIL",
677            Self::Fatal => "FATAL",
678        }
679    }
680}
681
682/// XNACK key group SILENT|FAIL|FATAL IDS numids id \[id ...\]
683/// \[RETRYCOUNT count\] \[FORCE\]
684///
685/// Releases pending messages back to a consumer group's PEL without
686/// acknowledging them (Redis 8.8+). Returns the number of messages released.
687#[derive(Clone)]
688pub struct XNack {
689    key: CommandArg,
690    group: CommandArg,
691    mode: XNackMode,
692    ids: Vec<CommandArg>,
693    retrycount: Option<u64>,
694    force: bool,
695}
696
697impl XNack {
698    /// Create an XNACK command for one or more stream entry IDs.
699    pub fn new(
700        key: impl Into<CommandArg>,
701        group: impl Into<CommandArg>,
702        mode: XNackMode,
703        ids: impl IntoIterator<Item = impl Into<CommandArg>>,
704    ) -> Self {
705        Self {
706            key: key.into(),
707            group: group.into(),
708            mode,
709            ids: ids.into_iter().map(Into::into).collect(),
710            retrycount: None,
711            force: false,
712        }
713    }
714
715    /// Set the delivery counter explicitly instead of applying the mode's
716    /// adjustment.
717    pub fn retrycount(mut self, count: u64) -> Self {
718        self.retrycount = Some(count);
719        self
720    }
721
722    /// Create unowned PEL entries for IDs that exist in the stream but are not
723    /// currently pending.
724    pub fn force(mut self) -> Self {
725        self.force = true;
726        self
727    }
728}
729
730impl Command for XNack {
731    type Response = i64;
732
733    fn to_frame(&self) -> Frame {
734        let mut args = vec![
735            bulk("XNACK"),
736            bulk(self.key.as_bytes()),
737            bulk(self.group.as_bytes()),
738            bulk(self.mode.as_str()),
739            bulk("IDS"),
740            bulk(self.ids.len().to_string()),
741        ];
742        for id in &self.ids {
743            args.push(bulk(id.as_bytes()));
744        }
745        if let Some(count) = self.retrycount {
746            args.push(bulk("RETRYCOUNT"));
747            args.push(bulk(count.to_string()));
748        }
749        if self.force {
750            args.push(bulk("FORCE"));
751        }
752        array(args)
753    }
754
755    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
756        match frame {
757            Frame::Integer(n) => Ok(n),
758            other => Err(RedisError::UnexpectedResponse {
759                expected: "integer",
760                actual: format!("{other:?}"),
761            }),
762        }
763    }
764
765    fn name(&self) -> &str {
766        "XNACK"
767    }
768}
769
770/// Reference-trimming policy for `XACKDEL` and `XDELEX` (Redis 8.0+).
771///
772/// Controls what happens to an entry that is still referenced by other
773/// consumer groups when it is deleted:
774/// - `KeepRef` -- delete the entry but keep references in other groups' PELs
775///   (the default).
776/// - `DelRef` -- delete the entry and remove all references to it.
777/// - `Acked` -- only delete the entry if it has been acknowledged by all
778///   consumer groups.
779#[derive(Debug, Clone, Copy, PartialEq, Eq)]
780pub enum StreamRefPolicy {
781    /// Keep references in other groups' PELs.
782    KeepRef,
783    /// Remove all references to the deleted entries.
784    DelRef,
785    /// Only delete entries acknowledged by all groups.
786    Acked,
787}
788
789impl StreamRefPolicy {
790    fn as_str(&self) -> &str {
791        match self {
792            StreamRefPolicy::KeepRef => "KEEPREF",
793            StreamRefPolicy::DelRef => "DELREF",
794            StreamRefPolicy::Acked => "ACKED",
795        }
796    }
797}
798
799/// Parse a stream ack/del response array of per-id integer status codes.
800fn parse_stream_status_array(frame: Frame) -> Result<Vec<i64>, RedisError> {
801    match frame {
802        Frame::Array(Some(frames)) => frames
803            .into_iter()
804            .map(|f| match f {
805                Frame::Integer(n) => Ok(n),
806                other => Err(RedisError::UnexpectedResponse {
807                    expected: "integer",
808                    actual: format!("{other:?}"),
809                }),
810            })
811            .collect(),
812        other => Err(RedisError::UnexpectedResponse {
813            expected: "array",
814            actual: format!("{other:?}"),
815        }),
816    }
817}
818
819/// XACKDEL key group \[KEEPREF|DELREF|ACKED\] IDS numids id \[id ...\]
820///
821/// Acknowledges and deletes the given entries from a consumer group in one
822/// atomic operation (Redis 8.0+). With no reference policy the default
823/// `KEEPREF` behavior applies. Returns one status code per requested id, in
824/// request order.
825///
826/// # Example
827///
828/// ```no_run
829/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
830/// use redis_tower_commands::{StreamRefPolicy, XAckDel};
831/// use redis_tower_core::RedisConnection;
832///
833/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
834///
835/// let statuses = conn
836///     .execute(XAckDel::new("s", "g", vec!["1-1", "1-2"]).policy(StreamRefPolicy::DelRef))
837///     .await?;
838/// # let _ = statuses;
839/// # Ok(())
840/// # }
841/// ```
842#[derive(Clone)]
843pub struct XAckDel {
844    key: CommandArg,
845    group: CommandArg,
846    policy: Option<StreamRefPolicy>,
847    ids: Vec<CommandArg>,
848}
849
850impl XAckDel {
851    /// Create a new [`XAckDel`] command.
852    pub fn new(
853        key: impl Into<CommandArg>,
854        group: impl Into<CommandArg>,
855        ids: impl IntoIterator<Item = impl Into<CommandArg>>,
856    ) -> Self {
857        Self {
858            key: key.into(),
859            group: group.into(),
860            policy: None,
861            ids: ids.into_iter().map(Into::into).collect(),
862        }
863    }
864
865    /// Set the reference-trimming policy. Defaults to `KEEPREF`.
866    pub fn policy(mut self, policy: StreamRefPolicy) -> Self {
867        self.policy = Some(policy);
868        self
869    }
870}
871
872impl Command for XAckDel {
873    type Response = Vec<i64>;
874
875    fn to_frame(&self) -> Frame {
876        let mut args = vec![
877            bulk("XACKDEL"),
878            bulk(self.key.as_bytes()),
879            bulk(self.group.as_bytes()),
880        ];
881        if let Some(policy) = &self.policy {
882            args.push(bulk(policy.as_str()));
883        }
884        args.push(bulk("IDS"));
885        args.push(bulk(self.ids.len().to_string()));
886        for id in &self.ids {
887            args.push(bulk(id.as_bytes()));
888        }
889        array(args)
890    }
891
892    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
893        parse_stream_status_array(frame)
894    }
895
896    fn name(&self) -> &str {
897        "XACKDEL"
898    }
899}
900
901/// XDELEX key \[KEEPREF|DELREF|ACKED\] IDS numids id \[id ...\]
902///
903/// Deletes the given entries from a stream with explicit control over how
904/// references held by consumer groups are handled (Redis 8.0+). With no
905/// reference policy the default `KEEPREF` behavior applies. Returns one status
906/// code per requested id, in request order.
907///
908/// # Example
909///
910/// ```no_run
911/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
912/// use redis_tower_commands::{StreamRefPolicy, XDelEx};
913/// use redis_tower_core::RedisConnection;
914///
915/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
916///
917/// let statuses = conn
918///     .execute(XDelEx::new("s", vec!["1-1", "1-2"]).policy(StreamRefPolicy::Acked))
919///     .await?;
920/// # let _ = statuses;
921/// # Ok(())
922/// # }
923/// ```
924#[derive(Clone)]
925pub struct XDelEx {
926    key: CommandArg,
927    policy: Option<StreamRefPolicy>,
928    ids: Vec<CommandArg>,
929}
930
931impl XDelEx {
932    /// Create a new [`XDelEx`] command.
933    pub fn new(
934        key: impl Into<CommandArg>,
935        ids: impl IntoIterator<Item = impl Into<CommandArg>>,
936    ) -> Self {
937        Self {
938            key: key.into(),
939            policy: None,
940            ids: ids.into_iter().map(Into::into).collect(),
941        }
942    }
943
944    /// Set the reference-trimming policy. Defaults to `KEEPREF`.
945    pub fn policy(mut self, policy: StreamRefPolicy) -> Self {
946        self.policy = Some(policy);
947        self
948    }
949}
950
951impl Command for XDelEx {
952    type Response = Vec<i64>;
953
954    fn to_frame(&self) -> Frame {
955        let mut args = vec![bulk("XDELEX"), bulk(self.key.as_bytes())];
956        if let Some(policy) = &self.policy {
957            args.push(bulk(policy.as_str()));
958        }
959        args.push(bulk("IDS"));
960        args.push(bulk(self.ids.len().to_string()));
961        for id in &self.ids {
962            args.push(bulk(id.as_bytes()));
963        }
964        array(args)
965    }
966
967    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
968        parse_stream_status_array(frame)
969    }
970
971    fn name(&self) -> &str {
972        "XDELEX"
973    }
974}
975
976/// XGROUP CREATE key group id \[MKSTREAM\]
977///
978/// Creates a consumer group.
979#[derive(Clone)]
980pub struct XGroupCreate {
981    key: CommandArg,
982    group: CommandArg,
983    id: CommandArg,
984    mkstream: bool,
985}
986
987impl XGroupCreate {
988    /// Create a group starting from the given ID.
989    /// Use "$" to only receive new entries, "0" for all existing entries.
990    pub fn new(
991        key: impl Into<CommandArg>,
992        group: impl Into<CommandArg>,
993        id: impl Into<CommandArg>,
994    ) -> Self {
995        Self {
996            key: key.into(),
997            group: group.into(),
998            id: id.into(),
999            mkstream: false,
1000        }
1001    }
1002
1003    /// Create the stream if it doesn't exist.
1004    pub fn mkstream(mut self) -> Self {
1005        self.mkstream = true;
1006        self
1007    }
1008}
1009
1010impl Command for XGroupCreate {
1011    type Response = ();
1012
1013    fn to_frame(&self) -> Frame {
1014        let mut args = vec![
1015            bulk("XGROUP"),
1016            bulk("CREATE"),
1017            bulk(self.key.as_bytes()),
1018            bulk(self.group.as_bytes()),
1019            bulk(self.id.as_bytes()),
1020        ];
1021        if self.mkstream {
1022            args.push(bulk("MKSTREAM"));
1023        }
1024        array(args)
1025    }
1026
1027    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1028        match frame {
1029            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1030            other => Err(RedisError::UnexpectedResponse {
1031                expected: "OK",
1032                actual: format!("{other:?}"),
1033            }),
1034        }
1035    }
1036
1037    fn name(&self) -> &str {
1038        "XGROUP CREATE"
1039    }
1040}
1041
1042/// XGROUP DESTROY key group
1043///
1044/// Destroys a consumer group.
1045#[derive(Clone)]
1046pub struct XGroupDestroy {
1047    key: CommandArg,
1048    group: CommandArg,
1049}
1050
1051impl XGroupDestroy {
1052    /// Create a new [`XGroupDestroy`] command.
1053    pub fn new(key: impl Into<CommandArg>, group: impl Into<CommandArg>) -> Self {
1054        Self {
1055            key: key.into(),
1056            group: group.into(),
1057        }
1058    }
1059}
1060
1061impl Command for XGroupDestroy {
1062    type Response = i64;
1063
1064    fn to_frame(&self) -> Frame {
1065        array(vec![
1066            bulk("XGROUP"),
1067            bulk("DESTROY"),
1068            bulk(self.key.as_bytes()),
1069            bulk(self.group.as_bytes()),
1070        ])
1071    }
1072
1073    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1074        match frame {
1075            Frame::Integer(n) => Ok(n),
1076            other => Err(RedisError::UnexpectedResponse {
1077                expected: "integer",
1078                actual: format!("{other:?}"),
1079            }),
1080        }
1081    }
1082
1083    fn name(&self) -> &str {
1084        "XGROUP DESTROY"
1085    }
1086}
1087
1088/// XREADGROUP GROUP group consumer \[COUNT count\] \[BLOCK ms\] STREAMS key \[key ...\] id \[id ...\]
1089///
1090/// Read from streams as a consumer group member.
1091#[derive(Clone)]
1092pub struct XReadGroup {
1093    group: CommandArg,
1094    consumer: CommandArg,
1095    streams: Vec<(CommandArg, CommandArg)>,
1096    count: Option<u64>,
1097    block: Option<u64>,
1098}
1099
1100impl XReadGroup {
1101    /// Read new entries (id = ">") from a single stream.
1102    pub fn new(
1103        group: impl Into<CommandArg>,
1104        consumer: impl Into<CommandArg>,
1105        key: impl Into<CommandArg>,
1106    ) -> Self {
1107        Self {
1108            group: group.into(),
1109            consumer: consumer.into(),
1110            streams: vec![(key.into(), ">".into())],
1111            count: None,
1112            block: None,
1113        }
1114    }
1115
1116    /// Add another stream to read from.
1117    pub fn stream(mut self, key: impl Into<CommandArg>, id: impl Into<CommandArg>) -> Self {
1118        self.streams.push((key.into(), id.into()));
1119        self
1120    }
1121
1122    /// Limit the number of entries returned per stream.
1123    pub fn count(mut self, n: u64) -> Self {
1124        self.count = Some(n);
1125        self
1126    }
1127
1128    /// Block for up to `ms` milliseconds. 0 = block indefinitely.
1129    pub fn block(mut self, ms: u64) -> Self {
1130        self.block = Some(ms);
1131        self
1132    }
1133
1134    /// Override the ID for all streams already added.
1135    ///
1136    /// Use `"0"` to read pending entries or `">"` for new entries.
1137    pub fn with_id(mut self, id: impl Into<CommandArg>) -> Self {
1138        let id = id.into();
1139        for stream in &mut self.streams {
1140            stream.1 = id.clone();
1141        }
1142        self
1143    }
1144}
1145
1146impl Command for XReadGroup {
1147    type Response = Vec<(Bytes, Vec<StreamEntry>)>;
1148
1149    fn to_frame(&self) -> Frame {
1150        let mut args = vec![
1151            bulk("XREADGROUP"),
1152            bulk("GROUP"),
1153            bulk(self.group.as_bytes()),
1154            bulk(self.consumer.as_bytes()),
1155        ];
1156        if let Some(n) = self.count {
1157            args.push(bulk("COUNT"));
1158            args.push(bulk(n.to_string()));
1159        }
1160        if let Some(ms) = self.block {
1161            args.push(bulk("BLOCK"));
1162            args.push(bulk(ms.to_string()));
1163        }
1164        args.push(bulk("STREAMS"));
1165        for (key, _) in &self.streams {
1166            args.push(bulk(key.as_bytes()));
1167        }
1168        for (_, id) in &self.streams {
1169            args.push(bulk(id.as_bytes()));
1170        }
1171        array(args)
1172    }
1173
1174    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1175        match &frame {
1176            // BLOCK timeout or no pending entries returns Null.
1177            Frame::Null | Frame::Array(None) | Frame::BulkString(None) => Ok(Vec::new()),
1178            _ => parse_xread_response(&frame),
1179        }
1180    }
1181
1182    fn name(&self) -> &str {
1183        "XREADGROUP"
1184    }
1185
1186    fn is_blocking(&self) -> bool {
1187        self.block.is_some()
1188    }
1189}
1190
1191/// XREAD \[COUNT count\] \[BLOCK ms\] STREAMS key \[key ...\] id \[id ...\]
1192///
1193/// Read from one or more streams.
1194#[derive(Clone)]
1195pub struct XRead {
1196    streams: Vec<(CommandArg, CommandArg)>,
1197    count: Option<u64>,
1198    block: Option<u64>,
1199}
1200
1201impl XRead {
1202    /// Read entries after `id` from a single stream. Use "$" for only new entries.
1203    pub fn new(key: impl Into<CommandArg>, id: impl Into<CommandArg>) -> Self {
1204        Self {
1205            streams: vec![(key.into(), id.into())],
1206            count: None,
1207            block: None,
1208        }
1209    }
1210
1211    /// Add another stream to read from.
1212    pub fn stream(mut self, key: impl Into<CommandArg>, id: impl Into<CommandArg>) -> Self {
1213        self.streams.push((key.into(), id.into()));
1214        self
1215    }
1216
1217    /// Configure the `count` option.
1218    pub fn count(mut self, n: u64) -> Self {
1219        self.count = Some(n);
1220        self
1221    }
1222
1223    /// Configure the `block` option.
1224    pub fn block(mut self, ms: u64) -> Self {
1225        self.block = Some(ms);
1226        self
1227    }
1228}
1229
1230impl Command for XRead {
1231    type Response = Option<Vec<(Bytes, Vec<StreamEntry>)>>;
1232
1233    fn to_frame(&self) -> Frame {
1234        let mut args = vec![bulk("XREAD")];
1235        if let Some(n) = self.count {
1236            args.push(bulk("COUNT"));
1237            args.push(bulk(n.to_string()));
1238        }
1239        if let Some(ms) = self.block {
1240            args.push(bulk("BLOCK"));
1241            args.push(bulk(ms.to_string()));
1242        }
1243        args.push(bulk("STREAMS"));
1244        for (key, _) in &self.streams {
1245            args.push(bulk(key.as_bytes()));
1246        }
1247        for (_, id) in &self.streams {
1248            args.push(bulk(id.as_bytes()));
1249        }
1250        array(args)
1251    }
1252
1253    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1254        match &frame {
1255            Frame::Null | Frame::Array(None) | Frame::BulkString(None) => Ok(None),
1256            _ => parse_xread_response(&frame).map(Some),
1257        }
1258    }
1259
1260    fn name(&self) -> &str {
1261        "XREAD"
1262    }
1263
1264    fn is_blocking(&self) -> bool {
1265        self.block.is_some()
1266    }
1267}
1268
1269/// XGROUP SETID key group id
1270///
1271/// Sets the last-delivered ID for a consumer group.
1272#[derive(Clone)]
1273pub struct XGroupSetId {
1274    key: CommandArg,
1275    group: CommandArg,
1276    id: CommandArg,
1277}
1278
1279impl XGroupSetId {
1280    /// Create a new [`XGroupSetId`] command.
1281    pub fn new(
1282        key: impl Into<CommandArg>,
1283        group: impl Into<CommandArg>,
1284        id: impl Into<CommandArg>,
1285    ) -> Self {
1286        Self {
1287            key: key.into(),
1288            group: group.into(),
1289            id: id.into(),
1290        }
1291    }
1292}
1293
1294impl Command for XGroupSetId {
1295    type Response = ();
1296
1297    fn to_frame(&self) -> Frame {
1298        array(vec![
1299            bulk("XGROUP"),
1300            bulk("SETID"),
1301            bulk(self.key.as_bytes()),
1302            bulk(self.group.as_bytes()),
1303            bulk(self.id.as_bytes()),
1304        ])
1305    }
1306
1307    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1308        match frame {
1309            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1310            other => Err(RedisError::UnexpectedResponse {
1311                expected: "OK",
1312                actual: format!("{other:?}"),
1313            }),
1314        }
1315    }
1316
1317    fn name(&self) -> &str {
1318        "XGROUP SETID"
1319    }
1320}
1321
1322/// XGROUP CREATECONSUMER key group consumer
1323///
1324/// Creates a consumer in a consumer group. Returns 1 if created, 0 if already existed.
1325#[derive(Clone)]
1326pub struct XGroupCreateConsumer {
1327    key: CommandArg,
1328    group: CommandArg,
1329    consumer: CommandArg,
1330}
1331
1332impl XGroupCreateConsumer {
1333    /// Create a new [`XGroupCreateConsumer`] command.
1334    pub fn new(
1335        key: impl Into<CommandArg>,
1336        group: impl Into<CommandArg>,
1337        consumer: impl Into<CommandArg>,
1338    ) -> Self {
1339        Self {
1340            key: key.into(),
1341            group: group.into(),
1342            consumer: consumer.into(),
1343        }
1344    }
1345}
1346
1347impl Command for XGroupCreateConsumer {
1348    type Response = i64;
1349
1350    fn to_frame(&self) -> Frame {
1351        array(vec![
1352            bulk("XGROUP"),
1353            bulk("CREATECONSUMER"),
1354            bulk(self.key.as_bytes()),
1355            bulk(self.group.as_bytes()),
1356            bulk(self.consumer.as_bytes()),
1357        ])
1358    }
1359
1360    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1361        match frame {
1362            Frame::Integer(n) => Ok(n),
1363            other => Err(RedisError::UnexpectedResponse {
1364                expected: "integer",
1365                actual: format!("{other:?}"),
1366            }),
1367        }
1368    }
1369
1370    fn name(&self) -> &str {
1371        "XGROUP CREATECONSUMER"
1372    }
1373}
1374
1375/// XGROUP DELCONSUMER key group consumer
1376///
1377/// Deletes a consumer from a consumer group. Returns the number of pending entries the consumer had.
1378#[derive(Clone)]
1379pub struct XGroupDelConsumer {
1380    key: CommandArg,
1381    group: CommandArg,
1382    consumer: CommandArg,
1383}
1384
1385impl XGroupDelConsumer {
1386    /// Create a new [`XGroupDelConsumer`] command.
1387    pub fn new(
1388        key: impl Into<CommandArg>,
1389        group: impl Into<CommandArg>,
1390        consumer: impl Into<CommandArg>,
1391    ) -> Self {
1392        Self {
1393            key: key.into(),
1394            group: group.into(),
1395            consumer: consumer.into(),
1396        }
1397    }
1398}
1399
1400impl Command for XGroupDelConsumer {
1401    type Response = i64;
1402
1403    fn to_frame(&self) -> Frame {
1404        array(vec![
1405            bulk("XGROUP"),
1406            bulk("DELCONSUMER"),
1407            bulk(self.key.as_bytes()),
1408            bulk(self.group.as_bytes()),
1409            bulk(self.consumer.as_bytes()),
1410        ])
1411    }
1412
1413    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1414        match frame {
1415            Frame::Integer(n) => Ok(n),
1416            other => Err(RedisError::UnexpectedResponse {
1417                expected: "integer",
1418                actual: format!("{other:?}"),
1419            }),
1420        }
1421    }
1422
1423    fn name(&self) -> &str {
1424        "XGROUP DELCONSUMER"
1425    }
1426}
1427
1428/// XCLAIM key group consumer min-idle-time id \[id ...\] \[IDLE ms\] \[TIME ms\] \[RETRYCOUNT count\] \[FORCE\] \[JUSTID\]
1429///
1430/// Claims ownership of pending stream entries.
1431#[derive(Clone)]
1432pub struct XClaim {
1433    key: CommandArg,
1434    group: CommandArg,
1435    consumer: CommandArg,
1436    min_idle_time: u64,
1437    ids: Vec<CommandArg>,
1438    idle: Option<u64>,
1439    time: Option<u64>,
1440    retrycount: Option<u64>,
1441    force: bool,
1442    justid: bool,
1443}
1444
1445impl XClaim {
1446    /// Create a new [`XClaim`] command.
1447    pub fn new(
1448        key: impl Into<CommandArg>,
1449        group: impl Into<CommandArg>,
1450        consumer: impl Into<CommandArg>,
1451        min_idle_time: u64,
1452        ids: impl IntoIterator<Item = impl Into<CommandArg>>,
1453    ) -> Self {
1454        Self {
1455            key: key.into(),
1456            group: group.into(),
1457            consumer: consumer.into(),
1458            min_idle_time,
1459            ids: ids.into_iter().map(Into::into).collect(),
1460            idle: None,
1461            time: None,
1462            retrycount: None,
1463            force: false,
1464            justid: false,
1465        }
1466    }
1467
1468    /// Set the idle time (ms) for the claimed entries.
1469    pub fn idle(mut self, ms: u64) -> Self {
1470        self.idle = Some(ms);
1471        self
1472    }
1473
1474    /// Set the last delivery time (ms unix timestamp).
1475    pub fn time(mut self, ms: u64) -> Self {
1476        self.time = Some(ms);
1477        self
1478    }
1479
1480    /// Set the retry counter.
1481    pub fn retrycount(mut self, count: u64) -> Self {
1482        self.retrycount = Some(count);
1483        self
1484    }
1485
1486    /// Force claim even if the entry is not in the PEL.
1487    pub fn force(mut self) -> Self {
1488        self.force = true;
1489        self
1490    }
1491
1492    /// Return only IDs, not full entries.
1493    pub fn justid(mut self) -> Self {
1494        self.justid = true;
1495        self
1496    }
1497}
1498
1499impl Command for XClaim {
1500    type Response = Vec<StreamEntry>;
1501
1502    fn to_frame(&self) -> Frame {
1503        let mut args = vec![
1504            bulk("XCLAIM"),
1505            bulk(self.key.as_bytes()),
1506            bulk(self.group.as_bytes()),
1507            bulk(self.consumer.as_bytes()),
1508            bulk(self.min_idle_time.to_string()),
1509        ];
1510        for id in &self.ids {
1511            args.push(bulk(id.as_bytes()));
1512        }
1513        if let Some(ms) = self.idle {
1514            args.push(bulk("IDLE"));
1515            args.push(bulk(ms.to_string()));
1516        }
1517        if let Some(ms) = self.time {
1518            args.push(bulk("TIME"));
1519            args.push(bulk(ms.to_string()));
1520        }
1521        if let Some(count) = self.retrycount {
1522            args.push(bulk("RETRYCOUNT"));
1523            args.push(bulk(count.to_string()));
1524        }
1525        if self.force {
1526            args.push(bulk("FORCE"));
1527        }
1528        if self.justid {
1529            args.push(bulk("JUSTID"));
1530        }
1531        array(args)
1532    }
1533
1534    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1535        parse_stream_entries(&frame)
1536    }
1537
1538    fn name(&self) -> &str {
1539        "XCLAIM"
1540    }
1541}
1542
1543/// Result from XAUTOCLAIM: \[next-start-id, \[entries...\], \[deleted-ids...\]\]
1544#[derive(Debug, Clone, PartialEq)]
1545pub struct AutoClaimResult {
1546    /// Cursor to use as the next `XAUTOCLAIM` start ID.
1547    pub next_start_id: String,
1548    /// Entries transferred to the requesting consumer.
1549    pub entries: Vec<StreamEntry>,
1550    /// Pending IDs whose stream entries no longer exist.
1551    pub deleted_ids: Vec<String>,
1552}
1553
1554/// XAUTOCLAIM key group consumer min-idle-time start \[COUNT count\] \[JUSTID\]
1555///
1556/// Automatically claims pending entries that have been idle for at least min-idle-time.
1557#[derive(Clone)]
1558pub struct XAutoClaim {
1559    key: CommandArg,
1560    group: CommandArg,
1561    consumer: CommandArg,
1562    min_idle_time: u64,
1563    start: CommandArg,
1564    count: Option<u64>,
1565}
1566
1567impl XAutoClaim {
1568    /// Create a new [`XAutoClaim`] command.
1569    pub fn new(
1570        key: impl Into<CommandArg>,
1571        group: impl Into<CommandArg>,
1572        consumer: impl Into<CommandArg>,
1573        min_idle_time: u64,
1574        start: impl Into<CommandArg>,
1575    ) -> Self {
1576        Self {
1577            key: key.into(),
1578            group: group.into(),
1579            consumer: consumer.into(),
1580            min_idle_time,
1581            start: start.into(),
1582            count: None,
1583        }
1584    }
1585
1586    /// Limit the number of entries to claim.
1587    pub fn count(mut self, n: u64) -> Self {
1588        self.count = Some(n);
1589        self
1590    }
1591}
1592
1593impl Command for XAutoClaim {
1594    type Response = AutoClaimResult;
1595
1596    fn to_frame(&self) -> Frame {
1597        let mut args = vec![
1598            bulk("XAUTOCLAIM"),
1599            bulk(self.key.as_bytes()),
1600            bulk(self.group.as_bytes()),
1601            bulk(self.consumer.as_bytes()),
1602            bulk(self.min_idle_time.to_string()),
1603            bulk(self.start.as_bytes()),
1604        ];
1605        if let Some(n) = self.count {
1606            args.push(bulk("COUNT"));
1607            args.push(bulk(n.to_string()));
1608        }
1609        array(args)
1610    }
1611
1612    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1613        parse_autoclaim_response(&frame)
1614    }
1615
1616    fn name(&self) -> &str {
1617        "XAUTOCLAIM"
1618    }
1619}
1620
1621/// Summary from XPENDING (no range): count, min-id, max-id, and per-consumer counts.
1622#[derive(Debug, Clone, PartialEq)]
1623pub struct PendingSummary {
1624    /// Total entries in the group pending-entry list.
1625    pub count: i64,
1626    /// Smallest pending entry ID, or `None` when the list is empty.
1627    pub min_id: Option<String>,
1628    /// Largest pending entry ID, or `None` when the list is empty.
1629    pub max_id: Option<String>,
1630    /// Pending-entry count for each consumer.
1631    pub consumers: Vec<(Bytes, i64)>,
1632}
1633
1634/// XPENDING key group (summary form)
1635///
1636/// Returns a summary of pending entries for a consumer group.
1637#[derive(Clone)]
1638pub struct XPendingSummary {
1639    key: CommandArg,
1640    group: CommandArg,
1641}
1642
1643impl XPendingSummary {
1644    /// Create a new [`XPendingSummary`] command.
1645    pub fn new(key: impl Into<CommandArg>, group: impl Into<CommandArg>) -> Self {
1646        Self {
1647            key: key.into(),
1648            group: group.into(),
1649        }
1650    }
1651}
1652
1653impl Command for XPendingSummary {
1654    type Response = PendingSummary;
1655
1656    fn to_frame(&self) -> Frame {
1657        array(vec![
1658            bulk("XPENDING"),
1659            bulk(self.key.as_bytes()),
1660            bulk(self.group.as_bytes()),
1661        ])
1662    }
1663
1664    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1665        parse_pending_summary(&frame)
1666    }
1667
1668    fn name(&self) -> &str {
1669        "XPENDING"
1670    }
1671}
1672
1673/// A pending entry detail from XPENDING range form.
1674#[derive(Debug, Clone, PartialEq)]
1675pub struct PendingEntry {
1676    /// Pending stream entry ID.
1677    pub id: String,
1678    /// Consumer that currently owns the entry.
1679    pub consumer: Bytes,
1680    /// Milliseconds since the entry was last delivered.
1681    pub idle_ms: i64,
1682    /// Number of times the entry has been delivered.
1683    pub delivery_count: i64,
1684}
1685
1686/// XPENDING key group \[IDLE min-idle\] start end count \[consumer\]
1687///
1688/// Returns detailed pending entries for a consumer group.
1689#[derive(Clone)]
1690pub struct XPendingRange {
1691    key: CommandArg,
1692    group: CommandArg,
1693    start: CommandArg,
1694    end: CommandArg,
1695    count: u64,
1696    consumer: Option<CommandArg>,
1697    idle: Option<u64>,
1698}
1699
1700impl XPendingRange {
1701    /// Create a new [`XPendingRange`] command.
1702    pub fn new(
1703        key: impl Into<CommandArg>,
1704        group: impl Into<CommandArg>,
1705        start: impl Into<CommandArg>,
1706        end: impl Into<CommandArg>,
1707        count: u64,
1708    ) -> Self {
1709        Self {
1710            key: key.into(),
1711            group: group.into(),
1712            start: start.into(),
1713            end: end.into(),
1714            count,
1715            consumer: None,
1716            idle: None,
1717        }
1718    }
1719
1720    /// Filter by consumer name.
1721    pub fn consumer(mut self, consumer: impl Into<CommandArg>) -> Self {
1722        self.consumer = Some(consumer.into());
1723        self
1724    }
1725
1726    /// Filter entries idle for at least `ms` milliseconds.
1727    pub fn idle(mut self, ms: u64) -> Self {
1728        self.idle = Some(ms);
1729        self
1730    }
1731}
1732
1733impl Command for XPendingRange {
1734    type Response = Vec<PendingEntry>;
1735
1736    fn to_frame(&self) -> Frame {
1737        let mut args = vec![
1738            bulk("XPENDING"),
1739            bulk(self.key.as_bytes()),
1740            bulk(self.group.as_bytes()),
1741        ];
1742        if let Some(ms) = self.idle {
1743            args.push(bulk("IDLE"));
1744            args.push(bulk(ms.to_string()));
1745        }
1746        args.push(bulk(self.start.as_bytes()));
1747        args.push(bulk(self.end.as_bytes()));
1748        args.push(bulk(self.count.to_string()));
1749        if let Some(c) = &self.consumer {
1750            args.push(bulk(c.as_bytes()));
1751        }
1752        array(args)
1753    }
1754
1755    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1756        parse_pending_range(&frame)
1757    }
1758
1759    fn name(&self) -> &str {
1760        "XPENDING"
1761    }
1762}
1763
1764/// Stream info from XINFO STREAM.
1765#[derive(Debug, Clone, PartialEq)]
1766pub struct StreamInfo {
1767    /// Number of entries in the stream.
1768    pub length: i64,
1769    /// Number of keys in the stream radix tree.
1770    pub radix_tree_keys: i64,
1771    /// Number of nodes in the stream radix tree.
1772    pub radix_tree_nodes: i64,
1773    /// Most recently generated stream entry ID.
1774    pub last_generated_id: String,
1775    /// Number of consumer groups attached to the stream.
1776    pub groups: i64,
1777    /// First stream entry, when the stream is non-empty.
1778    pub first_entry: Option<StreamEntry>,
1779    /// Last stream entry, when the stream is non-empty.
1780    pub last_entry: Option<StreamEntry>,
1781}
1782
1783/// XINFO STREAM key
1784///
1785/// Returns information about a stream.
1786#[derive(Clone)]
1787pub struct XInfoStream {
1788    key: CommandArg,
1789}
1790
1791impl XInfoStream {
1792    /// Create a new [`XInfoStream`] command.
1793    pub fn new(key: impl Into<CommandArg>) -> Self {
1794        Self { key: key.into() }
1795    }
1796}
1797
1798impl Command for XInfoStream {
1799    type Response = StreamInfo;
1800
1801    fn to_frame(&self) -> Frame {
1802        array(vec![
1803            bulk("XINFO"),
1804            bulk("STREAM"),
1805            bulk(self.key.as_bytes()),
1806        ])
1807    }
1808
1809    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1810        parse_xinfo_stream(&frame)
1811    }
1812
1813    fn name(&self) -> &str {
1814        "XINFO STREAM"
1815    }
1816}
1817
1818/// Consumer group info from XINFO GROUPS.
1819#[derive(Debug, Clone, PartialEq)]
1820pub struct GroupInfo {
1821    /// Consumer-group name.
1822    pub name: Bytes,
1823    /// Number of consumers registered with the group.
1824    pub consumers: i64,
1825    /// Number of entries in the group's pending-entry list.
1826    pub pending: i64,
1827    /// Last stream entry ID delivered to the group.
1828    pub last_delivered_id: String,
1829}
1830
1831/// XINFO GROUPS key
1832///
1833/// Returns information about the consumer groups of a stream.
1834#[derive(Clone)]
1835pub struct XInfoGroups {
1836    key: CommandArg,
1837}
1838
1839impl XInfoGroups {
1840    /// Create a new [`XInfoGroups`] command.
1841    pub fn new(key: impl Into<CommandArg>) -> Self {
1842        Self { key: key.into() }
1843    }
1844}
1845
1846impl Command for XInfoGroups {
1847    type Response = Vec<GroupInfo>;
1848
1849    fn to_frame(&self) -> Frame {
1850        array(vec![
1851            bulk("XINFO"),
1852            bulk("GROUPS"),
1853            bulk(self.key.as_bytes()),
1854        ])
1855    }
1856
1857    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1858        parse_xinfo_groups(&frame)
1859    }
1860
1861    fn name(&self) -> &str {
1862        "XINFO GROUPS"
1863    }
1864}
1865
1866/// Consumer info from XINFO CONSUMERS.
1867#[derive(Debug, Clone, PartialEq)]
1868pub struct ConsumerInfo {
1869    /// Consumer name.
1870    pub name: Bytes,
1871    /// Number of entries currently pending for the consumer.
1872    pub pending: i64,
1873    /// Milliseconds since the consumer last interacted with the group.
1874    pub idle: i64,
1875}
1876
1877/// XINFO CONSUMERS key group
1878///
1879/// Returns information about the consumers of a consumer group.
1880#[derive(Clone)]
1881pub struct XInfoConsumers {
1882    key: CommandArg,
1883    group: CommandArg,
1884}
1885
1886impl XInfoConsumers {
1887    /// Create a new [`XInfoConsumers`] command.
1888    pub fn new(key: impl Into<CommandArg>, group: impl Into<CommandArg>) -> Self {
1889        Self {
1890            key: key.into(),
1891            group: group.into(),
1892        }
1893    }
1894}
1895
1896impl Command for XInfoConsumers {
1897    type Response = Vec<ConsumerInfo>;
1898
1899    fn to_frame(&self) -> Frame {
1900        array(vec![
1901            bulk("XINFO"),
1902            bulk("CONSUMERS"),
1903            bulk(self.key.as_bytes()),
1904            bulk(self.group.as_bytes()),
1905        ])
1906    }
1907
1908    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1909        parse_xinfo_consumers(&frame)
1910    }
1911
1912    fn name(&self) -> &str {
1913        "XINFO CONSUMERS"
1914    }
1915}
1916
1917// -- Response parsing helpers --
1918
1919/// Parse a stream entry: \[id, \[field, value, field, value, ...\]\]
1920fn parse_stream_entry(frame: &Frame) -> Result<StreamEntry, RedisError> {
1921    let items = match frame {
1922        Frame::Array(Some(items)) if items.len() == 2 => items,
1923        other => {
1924            return Err(RedisError::UnexpectedResponse {
1925                expected: "stream entry array [id, [fields...]]",
1926                actual: format!("{other:?}"),
1927            });
1928        }
1929    };
1930
1931    let id = match &items[0] {
1932        Frame::BulkString(Some(b)) => String::from_utf8_lossy(b).into_owned(),
1933        other => {
1934            return Err(RedisError::UnexpectedResponse {
1935                expected: "bulk string entry ID",
1936                actual: format!("{other:?}"),
1937            });
1938        }
1939    };
1940
1941    let field_values = match &items[1] {
1942        Frame::Array(Some(fvs)) => fvs,
1943        other => {
1944            return Err(RedisError::UnexpectedResponse {
1945                expected: "array of field-value pairs",
1946                actual: format!("{other:?}"),
1947            });
1948        }
1949    };
1950
1951    if field_values.len() % 2 != 0 {
1952        return Err(RedisError::UnexpectedResponse {
1953            expected: "even number of field-value elements",
1954            actual: format!("{} elements", field_values.len()),
1955        });
1956    }
1957
1958    let mut fields = Vec::with_capacity(field_values.len() / 2);
1959    for chunk in field_values.chunks(2) {
1960        let name = match &chunk[0] {
1961            Frame::BulkString(Some(b)) => b.clone(),
1962            other => {
1963                return Err(RedisError::UnexpectedResponse {
1964                    expected: "bulk string field name",
1965                    actual: format!("{other:?}"),
1966                });
1967            }
1968        };
1969        let value = match &chunk[1] {
1970            Frame::BulkString(Some(b)) => b.clone(),
1971            other => {
1972                return Err(RedisError::UnexpectedResponse {
1973                    expected: "bulk string field value",
1974                    actual: format!("{other:?}"),
1975                });
1976            }
1977        };
1978        fields.push((name, value));
1979    }
1980
1981    Ok(StreamEntry { id, fields })
1982}
1983
1984/// Parse a list of stream entries (from XRANGE/XREVRANGE).
1985fn parse_stream_entries(frame: &Frame) -> Result<Vec<StreamEntry>, RedisError> {
1986    let items = match frame {
1987        Frame::Array(Some(items)) => items,
1988        Frame::Array(None) => return Ok(Vec::new()),
1989        other => {
1990            return Err(RedisError::UnexpectedResponse {
1991                expected: "array of stream entries",
1992                actual: format!("{other:?}"),
1993            });
1994        }
1995    };
1996
1997    items.iter().map(parse_stream_entry).collect()
1998}
1999
2000/// Parse XREAD/XREADGROUP response: \[\[stream_key, \[entries...\]\], ...\]
2001fn parse_xread_response(frame: &Frame) -> Result<Vec<(Bytes, Vec<StreamEntry>)>, RedisError> {
2002    let streams = match frame {
2003        Frame::Array(Some(items)) => items,
2004        Frame::Array(None) => return Ok(Vec::new()),
2005        // RESP3 may return a Map.
2006        Frame::Map(entries) => {
2007            let mut result = Vec::new();
2008            for (key_frame, entries_frame) in entries {
2009                let key = match key_frame {
2010                    Frame::BulkString(Some(b)) => b.clone(),
2011                    other => {
2012                        return Err(RedisError::UnexpectedResponse {
2013                            expected: "bulk string stream key",
2014                            actual: format!("{other:?}"),
2015                        });
2016                    }
2017                };
2018                let entries = parse_stream_entries(entries_frame)?;
2019                result.push((key, entries));
2020            }
2021            return Ok(result);
2022        }
2023        other => {
2024            return Err(RedisError::UnexpectedResponse {
2025                expected: "array of [stream_key, [entries...]]",
2026                actual: format!("{other:?}"),
2027            });
2028        }
2029    };
2030
2031    let mut result = Vec::new();
2032    for stream_frame in streams {
2033        let items = match stream_frame {
2034            Frame::Array(Some(items)) if items.len() == 2 => items,
2035            other => {
2036                return Err(RedisError::UnexpectedResponse {
2037                    expected: "stream [key, entries] pair",
2038                    actual: format!("{other:?}"),
2039                });
2040            }
2041        };
2042
2043        let key = match &items[0] {
2044            Frame::BulkString(Some(b)) => b.clone(),
2045            other => {
2046                return Err(RedisError::UnexpectedResponse {
2047                    expected: "bulk string stream key",
2048                    actual: format!("{other:?}"),
2049                });
2050            }
2051        };
2052
2053        let entries = parse_stream_entries(&items[1])?;
2054        result.push((key, entries));
2055    }
2056
2057    Ok(result)
2058}
2059
2060/// Parse XAUTOCLAIM response: \[next-start-id, \[entries...\], \[deleted-ids...\]\]
2061fn parse_autoclaim_response(frame: &Frame) -> Result<AutoClaimResult, RedisError> {
2062    let items = match frame {
2063        Frame::Array(Some(items)) if items.len() >= 2 => items,
2064        other => {
2065            return Err(RedisError::UnexpectedResponse {
2066                expected: "array [next-start-id, [entries...], [deleted-ids...]]",
2067                actual: format!("{other:?}"),
2068            });
2069        }
2070    };
2071
2072    let next_start_id = match &items[0] {
2073        Frame::BulkString(Some(b)) => String::from_utf8_lossy(b).into_owned(),
2074        other => {
2075            return Err(RedisError::UnexpectedResponse {
2076                expected: "bulk string next-start-id",
2077                actual: format!("{other:?}"),
2078            });
2079        }
2080    };
2081
2082    let entries = parse_stream_entries(&items[1])?;
2083
2084    let deleted_ids = if items.len() > 2 {
2085        parse_string_array(&items[2])?
2086    } else {
2087        Vec::new()
2088    };
2089
2090    Ok(AutoClaimResult {
2091        next_start_id,
2092        entries,
2093        deleted_ids,
2094    })
2095}
2096
2097/// Parse an array of bulk strings into Vec<String>.
2098fn parse_string_array(frame: &Frame) -> Result<Vec<String>, RedisError> {
2099    let items = match frame {
2100        Frame::Array(Some(items)) => items,
2101        Frame::Array(None) => return Ok(Vec::new()),
2102        other => {
2103            return Err(RedisError::UnexpectedResponse {
2104                expected: "array of strings",
2105                actual: format!("{other:?}"),
2106            });
2107        }
2108    };
2109
2110    items
2111        .iter()
2112        .map(|f| match f {
2113            Frame::BulkString(Some(b)) => Ok(String::from_utf8_lossy(b).into_owned()),
2114            other => Err(RedisError::UnexpectedResponse {
2115                expected: "bulk string",
2116                actual: format!("{other:?}"),
2117            }),
2118        })
2119        .collect()
2120}
2121
2122/// Parse XPENDING summary: \[count, min-id, max-id, \[\[consumer, count\], ...\]\]
2123fn parse_pending_summary(frame: &Frame) -> Result<PendingSummary, RedisError> {
2124    let items = match frame {
2125        Frame::Array(Some(items)) if items.len() == 4 => items,
2126        other => {
2127            return Err(RedisError::UnexpectedResponse {
2128                expected: "array [count, min-id, max-id, [[consumer, count]...]]",
2129                actual: format!("{other:?}"),
2130            });
2131        }
2132    };
2133
2134    let count = match &items[0] {
2135        Frame::Integer(n) => *n,
2136        other => {
2137            return Err(RedisError::UnexpectedResponse {
2138                expected: "integer count",
2139                actual: format!("{other:?}"),
2140            });
2141        }
2142    };
2143
2144    // min-id and max-id are null when count is 0
2145    let min_id = match &items[1] {
2146        Frame::BulkString(Some(b)) => Some(String::from_utf8_lossy(b).into_owned()),
2147        Frame::BulkString(None) | Frame::Null => None,
2148        other => {
2149            return Err(RedisError::UnexpectedResponse {
2150                expected: "bulk string or null min-id",
2151                actual: format!("{other:?}"),
2152            });
2153        }
2154    };
2155
2156    let max_id = match &items[2] {
2157        Frame::BulkString(Some(b)) => Some(String::from_utf8_lossy(b).into_owned()),
2158        Frame::BulkString(None) | Frame::Null => None,
2159        other => {
2160            return Err(RedisError::UnexpectedResponse {
2161                expected: "bulk string or null max-id",
2162                actual: format!("{other:?}"),
2163            });
2164        }
2165    };
2166
2167    let consumers = match &items[3] {
2168        Frame::Array(Some(consumer_items)) => {
2169            let mut result = Vec::new();
2170            for item in consumer_items {
2171                let pair = match item {
2172                    Frame::Array(Some(pair)) if pair.len() == 2 => pair,
2173                    other => {
2174                        return Err(RedisError::UnexpectedResponse {
2175                            expected: "[consumer, count] pair",
2176                            actual: format!("{other:?}"),
2177                        });
2178                    }
2179                };
2180                let name = match &pair[0] {
2181                    Frame::BulkString(Some(b)) => b.clone(),
2182                    other => {
2183                        return Err(RedisError::UnexpectedResponse {
2184                            expected: "bulk string consumer name",
2185                            actual: format!("{other:?}"),
2186                        });
2187                    }
2188                };
2189                let cnt = match &pair[1] {
2190                    Frame::BulkString(Some(b)) => String::from_utf8_lossy(b)
2191                        .parse::<i64>()
2192                        .map_err(|_| RedisError::UnexpectedResponse {
2193                            expected: "numeric string count",
2194                            actual: String::from_utf8_lossy(b).into_owned(),
2195                        })?,
2196                    other => {
2197                        return Err(RedisError::UnexpectedResponse {
2198                            expected: "bulk string count",
2199                            actual: format!("{other:?}"),
2200                        });
2201                    }
2202                };
2203                result.push((name, cnt));
2204            }
2205            result
2206        }
2207        Frame::Array(None) | Frame::Null => Vec::new(),
2208        other => {
2209            return Err(RedisError::UnexpectedResponse {
2210                expected: "array of [consumer, count] pairs",
2211                actual: format!("{other:?}"),
2212            });
2213        }
2214    };
2215
2216    Ok(PendingSummary {
2217        count,
2218        min_id,
2219        max_id,
2220        consumers,
2221    })
2222}
2223
2224/// Parse XPENDING range: \[\[id, consumer, idle-ms, delivery-count\], ...\]
2225fn parse_pending_range(frame: &Frame) -> Result<Vec<PendingEntry>, RedisError> {
2226    let items = match frame {
2227        Frame::Array(Some(items)) => items,
2228        Frame::Array(None) => return Ok(Vec::new()),
2229        other => {
2230            return Err(RedisError::UnexpectedResponse {
2231                expected: "array of pending entries",
2232                actual: format!("{other:?}"),
2233            });
2234        }
2235    };
2236
2237    let mut result = Vec::new();
2238    for item in items {
2239        let entry = match item {
2240            Frame::Array(Some(parts)) if parts.len() == 4 => parts,
2241            other => {
2242                return Err(RedisError::UnexpectedResponse {
2243                    expected: "[id, consumer, idle-ms, delivery-count]",
2244                    actual: format!("{other:?}"),
2245                });
2246            }
2247        };
2248        let id = match &entry[0] {
2249            Frame::BulkString(Some(b)) => String::from_utf8_lossy(b).into_owned(),
2250            other => {
2251                return Err(RedisError::UnexpectedResponse {
2252                    expected: "bulk string id",
2253                    actual: format!("{other:?}"),
2254                });
2255            }
2256        };
2257        let consumer = match &entry[1] {
2258            Frame::BulkString(Some(b)) => b.clone(),
2259            other => {
2260                return Err(RedisError::UnexpectedResponse {
2261                    expected: "bulk string consumer",
2262                    actual: format!("{other:?}"),
2263                });
2264            }
2265        };
2266        let idle_ms = match &entry[2] {
2267            Frame::Integer(n) => *n,
2268            other => {
2269                return Err(RedisError::UnexpectedResponse {
2270                    expected: "integer idle-ms",
2271                    actual: format!("{other:?}"),
2272                });
2273            }
2274        };
2275        let delivery_count = match &entry[3] {
2276            Frame::Integer(n) => *n,
2277            other => {
2278                return Err(RedisError::UnexpectedResponse {
2279                    expected: "integer delivery-count",
2280                    actual: format!("{other:?}"),
2281                });
2282            }
2283        };
2284        result.push(PendingEntry {
2285            id,
2286            consumer,
2287            idle_ms,
2288            delivery_count,
2289        });
2290    }
2291    Ok(result)
2292}
2293
2294/// Extract a bulk string from a Frame.
2295fn extract_bulk_str(frame: &Frame) -> Result<String, RedisError> {
2296    match frame {
2297        Frame::BulkString(Some(b)) => Ok(String::from_utf8_lossy(b).into_owned()),
2298        other => Err(RedisError::UnexpectedResponse {
2299            expected: "bulk string",
2300            actual: format!("{other:?}"),
2301        }),
2302    }
2303}
2304
2305/// Extract exact bulk-string bytes from a Frame.
2306fn extract_bulk_bytes(frame: &Frame) -> Result<Bytes, RedisError> {
2307    match frame {
2308        Frame::BulkString(Some(bytes)) => Ok(bytes.clone()),
2309        other => Err(RedisError::UnexpectedResponse {
2310            expected: "bulk string",
2311            actual: format!("{other:?}"),
2312        }),
2313    }
2314}
2315
2316/// Extract an integer from a Frame.
2317fn extract_integer(frame: &Frame) -> Result<i64, RedisError> {
2318    match frame {
2319        Frame::Integer(n) => Ok(*n),
2320        other => Err(RedisError::UnexpectedResponse {
2321            expected: "integer",
2322            actual: format!("{other:?}"),
2323        }),
2324    }
2325}
2326
2327/// Parse XINFO STREAM response (flat key-value array).
2328/// Normalize an XINFO key/value container to a flat `[k, v, k, v, ...]` slice.
2329///
2330/// RESP2 returns these as a flat array; RESP3 returns the same data as a
2331/// `Frame::Map` of `(key, value)` pairs. Flattening the map to the array shape
2332/// lets the field-matching loops stay protocol-agnostic. Returns `None` for any
2333/// other frame so callers can emit a precise `UnexpectedResponse` error.
2334fn xinfo_kv_pairs(frame: &Frame) -> Option<Vec<Frame>> {
2335    match frame {
2336        Frame::Array(Some(items)) => Some(items.clone()),
2337        Frame::Map(pairs) => {
2338            let mut out = Vec::with_capacity(pairs.len() * 2);
2339            for (k, v) in pairs {
2340                out.push(k.clone());
2341                out.push(v.clone());
2342            }
2343            Some(out)
2344        }
2345        _ => None,
2346    }
2347}
2348
2349fn parse_xinfo_stream(frame: &Frame) -> Result<StreamInfo, RedisError> {
2350    let items = match xinfo_kv_pairs(frame) {
2351        Some(items) => items,
2352        None => {
2353            return Err(RedisError::UnexpectedResponse {
2354                expected: "array or map of key-value pairs (XINFO STREAM)",
2355                actual: format!("{frame:?}"),
2356            });
2357        }
2358    };
2359
2360    let mut length = 0i64;
2361    let mut radix_tree_keys = 0i64;
2362    let mut radix_tree_nodes = 0i64;
2363    let mut last_generated_id = String::new();
2364    let mut groups = 0i64;
2365    let mut first_entry = None;
2366    let mut last_entry = None;
2367
2368    for chunk in items.chunks(2) {
2369        if chunk.len() < 2 {
2370            break;
2371        }
2372        let key = match &chunk[0] {
2373            Frame::BulkString(Some(b)) => String::from_utf8_lossy(b).to_lowercase(),
2374            _ => continue,
2375        };
2376        match key.as_str() {
2377            "length" => length = extract_integer(&chunk[1])?,
2378            "radix-tree-keys" => radix_tree_keys = extract_integer(&chunk[1])?,
2379            "radix-tree-nodes" => radix_tree_nodes = extract_integer(&chunk[1])?,
2380            "last-generated-id" => last_generated_id = extract_bulk_str(&chunk[1])?,
2381            "groups" => groups = extract_integer(&chunk[1])?,
2382            "first-entry" => {
2383                first_entry = match &chunk[1] {
2384                    Frame::Null | Frame::Array(None) | Frame::BulkString(None) => None,
2385                    entry => Some(parse_stream_entry(entry)?),
2386                };
2387            }
2388            "last-entry" => {
2389                last_entry = match &chunk[1] {
2390                    Frame::Null | Frame::Array(None) | Frame::BulkString(None) => None,
2391                    entry => Some(parse_stream_entry(entry)?),
2392                };
2393            }
2394            _ => {} // skip unknown fields
2395        }
2396    }
2397
2398    Ok(StreamInfo {
2399        length,
2400        radix_tree_keys,
2401        radix_tree_nodes,
2402        last_generated_id,
2403        groups,
2404        first_entry,
2405        last_entry,
2406    })
2407}
2408
2409/// Parse XINFO GROUPS response: array of flat key-value arrays.
2410fn parse_xinfo_groups(frame: &Frame) -> Result<Vec<GroupInfo>, RedisError> {
2411    let items = match frame {
2412        Frame::Array(Some(items)) => items,
2413        Frame::Array(None) => return Ok(Vec::new()),
2414        other => {
2415            return Err(RedisError::UnexpectedResponse {
2416                expected: "array of group info arrays",
2417                actual: format!("{other:?}"),
2418            });
2419        }
2420    };
2421
2422    let mut result = Vec::new();
2423    for group_frame in items {
2424        let fields = match xinfo_kv_pairs(group_frame) {
2425            Some(f) => f,
2426            None => {
2427                return Err(RedisError::UnexpectedResponse {
2428                    expected: "array or map of key-value pairs (group info)",
2429                    actual: format!("{group_frame:?}"),
2430                });
2431            }
2432        };
2433
2434        let mut name = Bytes::new();
2435        let mut consumers = 0i64;
2436        let mut pending = 0i64;
2437        let mut last_delivered_id = String::new();
2438
2439        for chunk in fields.chunks(2) {
2440            if chunk.len() < 2 {
2441                break;
2442            }
2443            let key = match &chunk[0] {
2444                Frame::BulkString(Some(b)) => String::from_utf8_lossy(b).to_lowercase(),
2445                _ => continue,
2446            };
2447            match key.as_str() {
2448                "name" => name = extract_bulk_bytes(&chunk[1])?,
2449                "consumers" => consumers = extract_integer(&chunk[1])?,
2450                "pending" => pending = extract_integer(&chunk[1])?,
2451                "last-delivered-id" => last_delivered_id = extract_bulk_str(&chunk[1])?,
2452                _ => {}
2453            }
2454        }
2455
2456        result.push(GroupInfo {
2457            name,
2458            consumers,
2459            pending,
2460            last_delivered_id,
2461        });
2462    }
2463
2464    Ok(result)
2465}
2466
2467/// Parse XINFO CONSUMERS response: array of flat key-value arrays.
2468fn parse_xinfo_consumers(frame: &Frame) -> Result<Vec<ConsumerInfo>, RedisError> {
2469    let items = match frame {
2470        Frame::Array(Some(items)) => items,
2471        Frame::Array(None) => return Ok(Vec::new()),
2472        other => {
2473            return Err(RedisError::UnexpectedResponse {
2474                expected: "array of consumer info arrays",
2475                actual: format!("{other:?}"),
2476            });
2477        }
2478    };
2479
2480    let mut result = Vec::new();
2481    for consumer_frame in items {
2482        let fields = match xinfo_kv_pairs(consumer_frame) {
2483            Some(f) => f,
2484            None => {
2485                return Err(RedisError::UnexpectedResponse {
2486                    expected: "array or map of key-value pairs (consumer info)",
2487                    actual: format!("{consumer_frame:?}"),
2488                });
2489            }
2490        };
2491
2492        let mut name = Bytes::new();
2493        let mut pending = 0i64;
2494        let mut idle = 0i64;
2495
2496        for chunk in fields.chunks(2) {
2497            if chunk.len() < 2 {
2498                break;
2499            }
2500            let key = match &chunk[0] {
2501                Frame::BulkString(Some(b)) => String::from_utf8_lossy(b).to_lowercase(),
2502                _ => continue,
2503            };
2504            match key.as_str() {
2505                "name" => name = extract_bulk_bytes(&chunk[1])?,
2506                "pending" => pending = extract_integer(&chunk[1])?,
2507                "idle" => idle = extract_integer(&chunk[1])?,
2508                _ => {}
2509            }
2510        }
2511
2512        result.push(ConsumerInfo {
2513            name,
2514            pending,
2515            idle,
2516        });
2517    }
2518
2519    Ok(result)
2520}
2521
2522/// XSETID key last-id [ENTRIESADDED entries-added]
2523///
2524/// Sets the last entry ID of a stream. Used for stream replication and
2525/// management. Returns OK.
2526///
2527/// The optional `ENTRIESADDED` flag (Redis 7.0+) sets the total number of
2528/// entries ever added to the stream.
2529#[derive(Clone)]
2530pub struct XSetId {
2531    key: CommandArg,
2532    last_id: CommandArg,
2533    entries_added: Option<u64>,
2534}
2535
2536impl XSetId {
2537    /// Create an XSETID command.
2538    pub fn new(key: impl Into<CommandArg>, last_id: impl Into<CommandArg>) -> Self {
2539        Self {
2540            key: key.into(),
2541            last_id: last_id.into(),
2542            entries_added: None,
2543        }
2544    }
2545
2546    /// Set the `ENTRIESADDED` option (Redis 7.0+).
2547    ///
2548    /// Records the total number of entries ever added to the stream, used
2549    /// when replicating or restoring a stream with a known history.
2550    pub fn entries_added(mut self, count: u64) -> Self {
2551        self.entries_added = Some(count);
2552        self
2553    }
2554}
2555
2556impl Command for XSetId {
2557    type Response = ();
2558
2559    fn to_frame(&self) -> Frame {
2560        let mut args = vec![
2561            bulk("XSETID"),
2562            bulk(self.key.as_bytes()),
2563            bulk(self.last_id.as_bytes()),
2564        ];
2565        if let Some(n) = self.entries_added {
2566            args.push(bulk("ENTRIESADDED"));
2567            args.push(bulk(n.to_string()));
2568        }
2569        array(args)
2570    }
2571
2572    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2573        match frame {
2574            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2575            other => Err(RedisError::UnexpectedResponse {
2576                expected: "OK",
2577                actual: format!("{other:?}"),
2578            }),
2579        }
2580    }
2581
2582    fn name(&self) -> &str {
2583        "XSETID"
2584    }
2585}
2586
2587/// XINFO HELP
2588///
2589/// Returns helpful text describing the XINFO subcommands.
2590#[derive(Clone)]
2591pub struct XInfoHelp;
2592
2593impl XInfoHelp {
2594    /// Create a new [`XInfoHelp`] command.
2595    pub fn new() -> Self {
2596        Self
2597    }
2598}
2599
2600impl Default for XInfoHelp {
2601    fn default() -> Self {
2602        Self::new()
2603    }
2604}
2605
2606impl Command for XInfoHelp {
2607    type Response = Vec<Bytes>;
2608
2609    fn to_frame(&self) -> Frame {
2610        array(vec![bulk("XINFO"), bulk("HELP")])
2611    }
2612
2613    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2614        crate::help::parse_help_lines(frame)
2615    }
2616
2617    fn name(&self) -> &str {
2618        "XINFO HELP"
2619    }
2620
2621    fn idempotent(&self) -> bool {
2622        true
2623    }
2624}
2625
2626/// XGROUP HELP
2627///
2628/// Returns helpful text describing the XGROUP subcommands.
2629#[derive(Clone)]
2630pub struct XGroupHelp;
2631
2632impl XGroupHelp {
2633    /// Create a new [`XGroupHelp`] command.
2634    pub fn new() -> Self {
2635        Self
2636    }
2637}
2638
2639impl Default for XGroupHelp {
2640    fn default() -> Self {
2641        Self::new()
2642    }
2643}
2644
2645impl Command for XGroupHelp {
2646    type Response = Vec<Bytes>;
2647
2648    fn to_frame(&self) -> Frame {
2649        array(vec![bulk("XGROUP"), bulk("HELP")])
2650    }
2651
2652    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2653        crate::help::parse_help_lines(frame)
2654    }
2655
2656    fn name(&self) -> &str {
2657        "XGROUP HELP"
2658    }
2659
2660    fn idempotent(&self) -> bool {
2661        true
2662    }
2663}
2664
2665#[cfg(test)]
2666mod tests {
2667    use super::*;
2668    use redis_tower_core::Command;
2669    use redis_tower_protocol::Frame;
2670    use redis_tower_protocol::helpers::{array, bulk};
2671
2672    #[test]
2673    fn xread_is_blocking_only_with_block() {
2674        // XREAD is blocking only when BLOCK is set.
2675        assert!(!XRead::new("s", "$").is_blocking());
2676        assert!(XRead::new("s", "$").block(1000).is_blocking());
2677    }
2678
2679    // -- XINFO RESP3 map parsing (#478) --
2680
2681    #[test]
2682    fn xinfo_stream_parses_resp3_map() {
2683        // Under RESP3 XINFO STREAM returns a Map rather than a flat array.
2684        let frame = Frame::Map(vec![
2685            (bulk("length"), Frame::Integer(2)),
2686            (bulk("radix-tree-keys"), Frame::Integer(1)),
2687            (bulk("radix-tree-nodes"), Frame::Integer(2)),
2688            (bulk("last-generated-id"), bulk("1-1")),
2689            (bulk("groups"), Frame::Integer(0)),
2690            (bulk("first-entry"), Frame::Null),
2691            (bulk("last-entry"), Frame::Null),
2692        ]);
2693        let info = parse_xinfo_stream(&frame).unwrap();
2694        assert_eq!(info.length, 2);
2695        assert_eq!(info.last_generated_id, "1-1");
2696        assert!(info.first_entry.is_none());
2697        assert!(info.last_entry.is_none());
2698    }
2699
2700    #[test]
2701    fn xinfo_groups_parses_resp3_map_entries() {
2702        // RESP3 returns each group as a Map inside the outer array.
2703        let frame = Frame::Array(Some(vec![Frame::Map(vec![
2704            (bulk("name"), bulk("g1")),
2705            (bulk("consumers"), Frame::Integer(1)),
2706            (bulk("pending"), Frame::Integer(3)),
2707            (bulk("last-delivered-id"), bulk("5-0")),
2708        ])]));
2709        let groups = parse_xinfo_groups(&frame).unwrap();
2710        assert_eq!(groups.len(), 1);
2711        assert_eq!(groups[0].name, "g1");
2712        assert_eq!(groups[0].consumers, 1);
2713        assert_eq!(groups[0].pending, 3);
2714    }
2715
2716    #[test]
2717    fn xinfo_consumers_parses_resp3_map_entries() {
2718        // RESP3 returns each consumer as a Map inside the outer array.
2719        let frame = Frame::Array(Some(vec![Frame::Map(vec![
2720            (bulk("name"), bulk("c1")),
2721            (bulk("pending"), Frame::Integer(1)),
2722            (bulk("idle"), Frame::Integer(42)),
2723        ])]));
2724        let consumers = parse_xinfo_consumers(&frame).unwrap();
2725        assert_eq!(consumers.len(), 1);
2726        assert_eq!(consumers[0].name, "c1");
2727        assert_eq!(consumers[0].pending, 1);
2728        assert_eq!(consumers[0].idle, 42);
2729    }
2730
2731    // -- XAdd --
2732
2733    #[test]
2734    fn xadd_basic_to_frame() {
2735        let cmd = XAdd::new("mystream")
2736            .field("name", "John")
2737            .field("age", "30");
2738        let frame = cmd.to_frame();
2739        assert_eq!(
2740            frame,
2741            array(vec![
2742                bulk("XADD"),
2743                bulk("mystream"),
2744                bulk("*"),
2745                bulk("name"),
2746                bulk("John"),
2747                bulk("age"),
2748                bulk("30"),
2749            ])
2750        );
2751    }
2752
2753    #[test]
2754    fn xadd_with_options_to_frame() {
2755        let cmd = XAdd::new("mystream")
2756            .nomkstream()
2757            .maxlen_approx(1000)
2758            .field("k", "v");
2759        let frame = cmd.to_frame();
2760        match frame {
2761            Frame::Array(Some(args)) => {
2762                assert_eq!(args[0], bulk("XADD"));
2763                assert_eq!(args[1], bulk("mystream"));
2764                assert_eq!(args[2], bulk("NOMKSTREAM"));
2765                assert_eq!(args[3], bulk("MAXLEN"));
2766                assert_eq!(args[4], bulk("~"));
2767                assert_eq!(args[5], bulk("1000"));
2768            }
2769            _ => panic!("expected array"),
2770        }
2771    }
2772
2773    #[test]
2774    fn xadd_with_specific_id() {
2775        let cmd = XAdd::new("mystream").id("1-1").field("k", "v");
2776        let frame = cmd.to_frame();
2777        match frame {
2778            Frame::Array(Some(args)) => {
2779                assert!(args.contains(&bulk("1-1")));
2780            }
2781            _ => panic!("expected array"),
2782        }
2783    }
2784
2785    #[test]
2786    fn xadd_parse_response() {
2787        let cmd = XAdd::new("mystream").field("k", "v");
2788        let frame = Frame::BulkString(Some(Bytes::from("1526919030474-55")));
2789        let result = cmd.parse_response(frame).unwrap();
2790        assert_eq!(result, "1526919030474-55");
2791    }
2792
2793    #[test]
2794    fn xadd_parse_error_on_integer() {
2795        let cmd = XAdd::new("mystream").field("k", "v");
2796        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
2797    }
2798
2799    // -- XCfgSet --
2800
2801    #[test]
2802    fn xcfgset_with_duration_to_frame() {
2803        let cmd = XCfgSet::new("mystream", XCfgSetOption::IdmpDuration(300));
2804        assert_eq!(
2805            cmd.to_frame(),
2806            array(vec![
2807                bulk("XCFGSET"),
2808                bulk("mystream"),
2809                bulk("IDMP-DURATION"),
2810                bulk("300"),
2811            ])
2812        );
2813    }
2814
2815    #[test]
2816    fn xcfgset_with_maxsize_to_frame() {
2817        let cmd = XCfgSet::new("mystream", XCfgSetOption::IdmpMaxSize(1000));
2818        assert_eq!(
2819            cmd.to_frame(),
2820            array(vec![
2821                bulk("XCFGSET"),
2822                bulk("mystream"),
2823                bulk("IDMP-MAXSIZE"),
2824                bulk("1000"),
2825            ])
2826        );
2827    }
2828
2829    #[test]
2830    fn xcfgset_with_all_options_to_frame() {
2831        let cmd = XCfgSet::new("mystream", XCfgSetOption::IdmpDuration(600)).idmp_maxsize(500);
2832        assert_eq!(
2833            cmd.to_frame(),
2834            array(vec![
2835                bulk("XCFGSET"),
2836                bulk("mystream"),
2837                bulk("IDMP-DURATION"),
2838                bulk("600"),
2839                bulk("IDMP-MAXSIZE"),
2840                bulk("500"),
2841            ])
2842        );
2843    }
2844
2845    #[test]
2846    fn xcfgset_parses_ok_and_is_not_idempotent() {
2847        let cmd = XCfgSet::new("mystream", XCfgSetOption::IdmpDuration(300));
2848        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
2849            .unwrap();
2850        assert!(!cmd.idempotent());
2851        assert_eq!(cmd.name(), "XCFGSET");
2852    }
2853
2854    #[test]
2855    fn xcfgset_rejects_unexpected_response() {
2856        let cmd = XCfgSet::new("mystream", XCfgSetOption::IdmpDuration(300));
2857        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
2858    }
2859
2860    // -- XIdmpRecord --
2861
2862    #[test]
2863    fn xidmprecord_to_frame() {
2864        let cmd = XIdmpRecord::new("mystream", "producer-1", "request-42", "1-0");
2865        assert_eq!(
2866            cmd.to_frame(),
2867            array(vec![
2868                bulk("XIDMPRECORD"),
2869                bulk("mystream"),
2870                bulk("producer-1"),
2871                bulk("request-42"),
2872                bulk("1-0"),
2873            ])
2874        );
2875    }
2876
2877    #[test]
2878    fn xidmprecord_parses_ok_and_is_idempotent() {
2879        let cmd = XIdmpRecord::new("mystream", "producer-1", "request-42", "1-0");
2880        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
2881            .unwrap();
2882        assert!(cmd.idempotent());
2883        assert_eq!(cmd.name(), "XIDMPRECORD");
2884    }
2885
2886    #[test]
2887    fn xidmprecord_rejects_unexpected_response() {
2888        let cmd = XIdmpRecord::new("mystream", "producer-1", "request-42", "1-0");
2889        assert!(cmd.parse_response(bulk("OK")).is_err());
2890    }
2891
2892    // -- XLen --
2893
2894    #[test]
2895    fn xlen_to_frame() {
2896        let cmd = XLen::new("mystream");
2897        assert_eq!(cmd.to_frame(), array(vec![bulk("XLEN"), bulk("mystream")]));
2898    }
2899
2900    #[test]
2901    fn xlen_parse_integer() {
2902        let cmd = XLen::new("mystream");
2903        assert_eq!(cmd.parse_response(Frame::Integer(42)).unwrap(), 42);
2904    }
2905
2906    // -- XRange --
2907
2908    #[test]
2909    fn xrange_all_to_frame() {
2910        let cmd = XRange::all("mystream");
2911        assert_eq!(
2912            cmd.to_frame(),
2913            array(vec![bulk("XRANGE"), bulk("mystream"), bulk("-"), bulk("+"),])
2914        );
2915    }
2916
2917    #[test]
2918    fn xrange_with_count_to_frame() {
2919        let cmd = XRange::all("mystream").count(10);
2920        assert_eq!(
2921            cmd.to_frame(),
2922            array(vec![
2923                bulk("XRANGE"),
2924                bulk("mystream"),
2925                bulk("-"),
2926                bulk("+"),
2927                bulk("COUNT"),
2928                bulk("10"),
2929            ])
2930        );
2931    }
2932
2933    #[test]
2934    fn xrange_parse_entries() {
2935        let cmd = XRange::all("mystream");
2936        let entry = array(vec![
2937            Frame::BulkString(Some(Bytes::from("1-0"))),
2938            array(vec![
2939                Frame::BulkString(Some(Bytes::from("name"))),
2940                Frame::BulkString(Some(Bytes::from("Alice"))),
2941            ]),
2942        ]);
2943        let frame = array(vec![entry]);
2944        let result = cmd.parse_response(frame).unwrap();
2945        assert_eq!(result.len(), 1);
2946        assert_eq!(result[0].id, "1-0");
2947        assert_eq!(result[0].fields.len(), 1);
2948        assert_eq!(result[0].fields[0].0, "name");
2949        assert_eq!(result[0].fields[0].1, Bytes::from("Alice"));
2950    }
2951
2952    #[test]
2953    fn xrange_parse_empty() {
2954        let cmd = XRange::all("mystream");
2955        let frame = Frame::Array(None);
2956        let result = cmd.parse_response(frame).unwrap();
2957        assert!(result.is_empty());
2958    }
2959
2960    // -- XDel --
2961
2962    #[test]
2963    fn xdel_to_frame() {
2964        let cmd = XDel::new("mystream", "1-0");
2965        assert_eq!(
2966            cmd.to_frame(),
2967            array(vec![bulk("XDEL"), bulk("mystream"), bulk("1-0")])
2968        );
2969    }
2970
2971    #[test]
2972    fn xdel_parse_integer() {
2973        let cmd = XDel::new("mystream", "1-0");
2974        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
2975    }
2976
2977    // -- XTrim --
2978
2979    #[test]
2980    fn xtrim_maxlen_to_frame() {
2981        let cmd = XTrim::maxlen("mystream", 100);
2982        assert_eq!(
2983            cmd.to_frame(),
2984            array(vec![
2985                bulk("XTRIM"),
2986                bulk("mystream"),
2987                bulk("MAXLEN"),
2988                bulk("100"),
2989            ])
2990        );
2991    }
2992
2993    #[test]
2994    fn xtrim_maxlen_approx_to_frame() {
2995        let cmd = XTrim::maxlen_approx("mystream", 100);
2996        assert_eq!(
2997            cmd.to_frame(),
2998            array(vec![
2999                bulk("XTRIM"),
3000                bulk("mystream"),
3001                bulk("MAXLEN"),
3002                bulk("~"),
3003                bulk("100"),
3004            ])
3005        );
3006    }
3007
3008    // -- XAck --
3009
3010    #[test]
3011    fn xack_to_frame() {
3012        let cmd = XAck::new("mystream", "mygroup", "1-0");
3013        assert_eq!(
3014            cmd.to_frame(),
3015            array(vec![
3016                bulk("XACK"),
3017                bulk("mystream"),
3018                bulk("mygroup"),
3019                bulk("1-0"),
3020            ])
3021        );
3022    }
3023
3024    #[test]
3025    fn xack_multiple_to_frame() {
3026        let cmd = XAck::ids("mystream", "mygroup", vec!["1-0", "2-0"]);
3027        assert_eq!(
3028            cmd.to_frame(),
3029            array(vec![
3030                bulk("XACK"),
3031                bulk("mystream"),
3032                bulk("mygroup"),
3033                bulk("1-0"),
3034                bulk("2-0"),
3035            ])
3036        );
3037    }
3038
3039    #[test]
3040    fn xack_parse_integer() {
3041        let cmd = XAck::new("mystream", "mygroup", "1-0");
3042        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
3043    }
3044
3045    // -- XNack --
3046
3047    #[test]
3048    fn xnack_modes_to_frame() {
3049        for (mode, token) in [
3050            (XNackMode::Silent, "SILENT"),
3051            (XNackMode::Fail, "FAIL"),
3052            (XNackMode::Fatal, "FATAL"),
3053        ] {
3054            let cmd = XNack::new("mystream", "mygroup", mode, ["1-0"]);
3055            assert_eq!(
3056                cmd.to_frame(),
3057                array(vec![
3058                    bulk("XNACK"),
3059                    bulk("mystream"),
3060                    bulk("mygroup"),
3061                    bulk(token),
3062                    bulk("IDS"),
3063                    bulk("1"),
3064                    bulk("1-0"),
3065                ])
3066            );
3067        }
3068    }
3069
3070    #[test]
3071    fn xnack_multiple_ids_to_frame() {
3072        let cmd = XNack::new("mystream", "mygroup", XNackMode::Fail, ["1-0", "2-0"]);
3073        assert_eq!(
3074            cmd.to_frame(),
3075            array(vec![
3076                bulk("XNACK"),
3077                bulk("mystream"),
3078                bulk("mygroup"),
3079                bulk("FAIL"),
3080                bulk("IDS"),
3081                bulk("2"),
3082                bulk("1-0"),
3083                bulk("2-0"),
3084            ])
3085        );
3086    }
3087
3088    #[test]
3089    fn xnack_with_retrycount_and_force_to_frame() {
3090        let cmd = XNack::new("mystream", "mygroup", XNackMode::Fatal, ["1-0"])
3091            .retrycount(7)
3092            .force();
3093        assert_eq!(
3094            cmd.to_frame(),
3095            array(vec![
3096                bulk("XNACK"),
3097                bulk("mystream"),
3098                bulk("mygroup"),
3099                bulk("FATAL"),
3100                bulk("IDS"),
3101                bulk("1"),
3102                bulk("1-0"),
3103                bulk("RETRYCOUNT"),
3104                bulk("7"),
3105                bulk("FORCE"),
3106            ])
3107        );
3108    }
3109
3110    #[test]
3111    fn xnack_parses_integer_response() {
3112        let cmd = XNack::new("mystream", "mygroup", XNackMode::Fail, ["1-0"]);
3113        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
3114        assert_eq!(cmd.parse_response(Frame::Integer(0)).unwrap(), 0);
3115        assert_eq!(cmd.name(), "XNACK");
3116    }
3117
3118    #[test]
3119    fn xnack_rejects_unexpected_response() {
3120        let cmd = XNack::new("mystream", "mygroup", XNackMode::Fail, ["1-0"]);
3121        assert!(cmd.parse_response(bulk("1")).is_err());
3122    }
3123
3124    // -- XGroupCreate --
3125
3126    #[test]
3127    fn xgroup_create_to_frame() {
3128        let cmd = XGroupCreate::new("mystream", "mygroup", "$");
3129        assert_eq!(
3130            cmd.to_frame(),
3131            array(vec![
3132                bulk("XGROUP"),
3133                bulk("CREATE"),
3134                bulk("mystream"),
3135                bulk("mygroup"),
3136                bulk("$"),
3137            ])
3138        );
3139    }
3140
3141    #[test]
3142    fn xgroup_create_mkstream_to_frame() {
3143        let cmd = XGroupCreate::new("mystream", "mygroup", "0").mkstream();
3144        assert_eq!(
3145            cmd.to_frame(),
3146            array(vec![
3147                bulk("XGROUP"),
3148                bulk("CREATE"),
3149                bulk("mystream"),
3150                bulk("mygroup"),
3151                bulk("0"),
3152                bulk("MKSTREAM"),
3153            ])
3154        );
3155    }
3156
3157    #[test]
3158    fn xgroup_create_parse_ok() {
3159        let cmd = XGroupCreate::new("mystream", "mygroup", "$");
3160        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
3161            .unwrap();
3162    }
3163
3164    // -- XRead --
3165
3166    #[test]
3167    fn xread_to_frame() {
3168        let cmd = XRead::new("mystream", "0").count(10);
3169        assert_eq!(
3170            cmd.to_frame(),
3171            array(vec![
3172                bulk("XREAD"),
3173                bulk("COUNT"),
3174                bulk("10"),
3175                bulk("STREAMS"),
3176                bulk("mystream"),
3177                bulk("0"),
3178            ])
3179        );
3180    }
3181
3182    #[test]
3183    fn xread_parse_null() {
3184        let cmd = XRead::new("mystream", "$");
3185        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
3186    }
3187
3188    // -- XGroupDestroy --
3189
3190    #[test]
3191    fn xgroup_destroy_to_frame() {
3192        let cmd = XGroupDestroy::new("mystream", "mygroup");
3193        assert_eq!(
3194            cmd.to_frame(),
3195            array(vec![
3196                bulk("XGROUP"),
3197                bulk("DESTROY"),
3198                bulk("mystream"),
3199                bulk("mygroup"),
3200            ])
3201        );
3202    }
3203
3204    // -- XSetId --
3205
3206    #[test]
3207    fn xsetid_basic_to_frame() {
3208        let cmd = XSetId::new("mystream", "1-0");
3209        assert_eq!(
3210            cmd.to_frame(),
3211            array(vec![bulk("XSETID"), bulk("mystream"), bulk("1-0"),])
3212        );
3213    }
3214
3215    #[test]
3216    fn xsetid_with_entries_added_to_frame() {
3217        let cmd = XSetId::new("mystream", "5-0").entries_added(100);
3218        assert_eq!(
3219            cmd.to_frame(),
3220            array(vec![
3221                bulk("XSETID"),
3222                bulk("mystream"),
3223                bulk("5-0"),
3224                bulk("ENTRIESADDED"),
3225                bulk("100"),
3226            ])
3227        );
3228    }
3229
3230    #[test]
3231    fn xsetid_parse_ok() {
3232        let cmd = XSetId::new("mystream", "1-0");
3233        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
3234            .unwrap();
3235    }
3236
3237    #[test]
3238    fn xsetid_parse_unexpected_fails() {
3239        let cmd = XSetId::new("mystream", "1-0");
3240        let result = cmd.parse_response(Frame::Integer(1));
3241        assert!(result.is_err());
3242    }
3243
3244    // -- XRevRange --
3245
3246    #[test]
3247    fn xrevrange_to_frame() {
3248        let cmd = XRevRange::all("mystream");
3249        assert_eq!(
3250            cmd.to_frame(),
3251            array(vec![
3252                bulk("XREVRANGE"),
3253                bulk("mystream"),
3254                bulk("+"),
3255                bulk("-"),
3256            ])
3257        );
3258    }
3259
3260    // -- XAckDel --
3261
3262    #[test]
3263    fn xackdel_default_policy_to_frame() {
3264        let cmd = XAckDel::new("s", "g", vec!["1-1", "1-2"]);
3265        assert_eq!(
3266            cmd.to_frame(),
3267            array(vec![
3268                bulk("XACKDEL"),
3269                bulk("s"),
3270                bulk("g"),
3271                bulk("IDS"),
3272                bulk("2"),
3273                bulk("1-1"),
3274                bulk("1-2"),
3275            ])
3276        );
3277    }
3278
3279    #[test]
3280    fn xackdel_with_policy_to_frame() {
3281        let cmd = XAckDel::new("s", "g", vec!["1-1"]).policy(StreamRefPolicy::DelRef);
3282        assert_eq!(
3283            cmd.to_frame(),
3284            array(vec![
3285                bulk("XACKDEL"),
3286                bulk("s"),
3287                bulk("g"),
3288                bulk("DELREF"),
3289                bulk("IDS"),
3290                bulk("1"),
3291                bulk("1-1"),
3292            ])
3293        );
3294    }
3295
3296    #[test]
3297    fn xackdel_parse_status_array() {
3298        let cmd = XAckDel::new("s", "g", vec!["1-1", "1-2"]);
3299        let frame = array(vec![Frame::Integer(1), Frame::Integer(-1)]);
3300        assert_eq!(cmd.parse_response(frame).unwrap(), vec![1, -1]);
3301    }
3302
3303    // -- XDelEx --
3304
3305    #[test]
3306    fn xdelex_default_policy_to_frame() {
3307        let cmd = XDelEx::new("s", vec!["1-1", "1-2"]);
3308        assert_eq!(
3309            cmd.to_frame(),
3310            array(vec![
3311                bulk("XDELEX"),
3312                bulk("s"),
3313                bulk("IDS"),
3314                bulk("2"),
3315                bulk("1-1"),
3316                bulk("1-2"),
3317            ])
3318        );
3319    }
3320
3321    #[test]
3322    fn xdelex_with_policy_to_frame() {
3323        let cmd = XDelEx::new("s", vec!["1-1"]).policy(StreamRefPolicy::Acked);
3324        assert_eq!(
3325            cmd.to_frame(),
3326            array(vec![
3327                bulk("XDELEX"),
3328                bulk("s"),
3329                bulk("ACKED"),
3330                bulk("IDS"),
3331                bulk("1"),
3332                bulk("1-1"),
3333            ])
3334        );
3335    }
3336
3337    #[test]
3338    fn xdelex_parse_status_array() {
3339        let cmd = XDelEx::new("s", vec!["1-1"]);
3340        let frame = array(vec![Frame::Integer(1)]);
3341        assert_eq!(cmd.parse_response(frame).unwrap(), vec![1]);
3342    }
3343
3344    #[test]
3345    fn stream_help_subcommands_to_frame() {
3346        assert_eq!(
3347            XInfoHelp::new().to_frame(),
3348            array(vec![bulk("XINFO"), bulk("HELP")])
3349        );
3350        assert_eq!(
3351            XGroupHelp::new().to_frame(),
3352            array(vec![bulk("XGROUP"), bulk("HELP")])
3353        );
3354        assert!(XInfoHelp::new().idempotent());
3355        assert!(XGroupHelp::new().idempotent());
3356    }
3357
3358    #[test]
3359    fn xinfo_help_parse_lines() {
3360        let cmd = XInfoHelp::new();
3361        let reply = array(vec![bulk("XINFO <subcommand>"), bulk("STREAM <key>")]);
3362        let lines = cmd.parse_response(reply).unwrap();
3363        assert_eq!(lines.len(), 2);
3364        assert_eq!(&lines[0][..], b"XINFO <subcommand>");
3365    }
3366}