Skip to main content

redis_tower_commands/
timeseries.rs

1//! RedisTimeSeries samples, labels, rules, and aggregations.
2//!
3//! Available with the `timeseries` feature (included by `stack`) and requiring
4//! RedisTimeSeries on the server. Timestamp and aggregation options are typed;
5//! range commands return ordered `(timestamp, value)` samples and multi-range
6//! commands retain their series/label structure.
7//!
8//! ```
9//! use redis_tower_commands::TsAdd;
10//! use redis_tower_core::Command;
11//!
12//! let command = TsAdd::new("temperature", 1_700_000_000_000_i64, 21.5);
13//! assert_eq!(command.name(), "TS.ADD");
14//! ```
15//!
16//! See the [command cookbook] for feature and server prerequisites.
17//!
18//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#feature-gated-and-versioned-families
19
20use crate::CommandArg;
21use bytes::Bytes;
22use redis_tower_core::{Command, Frame, RedisError};
23use redis_tower_protocol::helpers::{array, bulk};
24
25// ---------------------------------------------------------------------------
26// Enums
27// ---------------------------------------------------------------------------
28
29/// Aggregation type for TimeSeries range and multi-range queries.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum TsAggregation {
32    /// Select the `Avg` mode.
33    Avg,
34    /// Select the `Sum` mode.
35    Sum,
36    /// Select the `Min` mode.
37    Min,
38    /// Select the `Max` mode.
39    Max,
40    /// Select the `Range` mode.
41    Range,
42    /// Select the `Count` mode.
43    Count,
44    /// Select the `First` mode.
45    First,
46    /// Select the `Last` mode.
47    Last,
48    /// Select the `StdP` mode.
49    StdP,
50    /// Select the `StdS` mode.
51    StdS,
52    /// Select the `VarP` mode.
53    VarP,
54    /// Select the `VarS` mode.
55    VarS,
56    /// Select the `Twa` mode.
57    Twa,
58}
59
60impl TsAggregation {
61    fn as_str(&self) -> &str {
62        match self {
63            TsAggregation::Avg => "AVG",
64            TsAggregation::Sum => "SUM",
65            TsAggregation::Min => "MIN",
66            TsAggregation::Max => "MAX",
67            TsAggregation::Range => "RANGE",
68            TsAggregation::Count => "COUNT",
69            TsAggregation::First => "FIRST",
70            TsAggregation::Last => "LAST",
71            TsAggregation::StdP => "STD.P",
72            TsAggregation::StdS => "STD.S",
73            TsAggregation::VarP => "VAR.P",
74            TsAggregation::VarS => "VAR.S",
75            TsAggregation::Twa => "TWA",
76        }
77    }
78}
79
80/// Duplicate policy for TimeSeries keys.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum TsDuplicatePolicy {
83    /// Select the `Block` mode.
84    Block,
85    /// Select the `First` mode.
86    First,
87    /// Select the `Last` mode.
88    Last,
89    /// Select the `Min` mode.
90    Min,
91    /// Select the `Max` mode.
92    Max,
93    /// Select the `Sum` mode.
94    Sum,
95}
96
97impl TsDuplicatePolicy {
98    fn as_str(&self) -> &str {
99        match self {
100            TsDuplicatePolicy::Block => "BLOCK",
101            TsDuplicatePolicy::First => "FIRST",
102            TsDuplicatePolicy::Last => "LAST",
103            TsDuplicatePolicy::Min => "MIN",
104            TsDuplicatePolicy::Max => "MAX",
105            TsDuplicatePolicy::Sum => "SUM",
106        }
107    }
108}
109
110/// Encoding for TimeSeries keys.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum TsEncoding {
113    /// Select the `Compressed` mode.
114    Compressed,
115    /// Select the `Uncompressed` mode.
116    Uncompressed,
117}
118
119impl TsEncoding {
120    fn as_str(&self) -> &str {
121        match self {
122            TsEncoding::Compressed => "COMPRESSED",
123            TsEncoding::Uncompressed => "UNCOMPRESSED",
124        }
125    }
126}
127
128// ---------------------------------------------------------------------------
129// Helper: push labels onto an args vec
130// ---------------------------------------------------------------------------
131
132fn push_labels(args: &mut Vec<Frame>, labels: &[(CommandArg, CommandArg)]) {
133    if !labels.is_empty() {
134        args.push(bulk("LABELS"));
135        for (k, v) in labels {
136            args.push(bulk(k));
137            args.push(bulk(v));
138        }
139    }
140}
141
142// ---------------------------------------------------------------------------
143// TS.CREATE
144// ---------------------------------------------------------------------------
145
146/// TS.CREATE key \[RETENTION ms\] \[ENCODING enc\] \[CHUNK_SIZE bytes\]
147/// \[DUPLICATE_POLICY policy\] \[LABELS label value ...\]
148///
149/// Creates a new TimeSeries key.
150#[derive(Clone)]
151pub struct TsCreate {
152    key: CommandArg,
153    retention: Option<u64>,
154    encoding: Option<TsEncoding>,
155    chunk_size: Option<u64>,
156    duplicate_policy: Option<TsDuplicatePolicy>,
157    labels: Vec<(CommandArg, CommandArg)>,
158}
159
160impl TsCreate {
161    /// Create a new [`TsCreate`] command.
162    pub fn new(key: impl Into<CommandArg>) -> Self {
163        Self {
164            key: key.into(),
165            retention: None,
166            encoding: None,
167            chunk_size: None,
168            duplicate_policy: None,
169            labels: Vec::new(),
170        }
171    }
172
173    /// Set the retention period in milliseconds.
174    pub fn retention(mut self, ms: u64) -> Self {
175        self.retention = Some(ms);
176        self
177    }
178
179    /// Set the encoding type.
180    pub fn encoding(mut self, enc: TsEncoding) -> Self {
181        self.encoding = Some(enc);
182        self
183    }
184
185    /// Set the chunk size in bytes.
186    pub fn chunk_size(mut self, bytes: u64) -> Self {
187        self.chunk_size = Some(bytes);
188        self
189    }
190
191    /// Set the duplicate policy.
192    pub fn duplicate_policy(mut self, policy: TsDuplicatePolicy) -> Self {
193        self.duplicate_policy = Some(policy);
194        self
195    }
196
197    /// Add a label key-value pair.
198    pub fn label(mut self, key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
199        self.labels.push((key.into(), value.into()));
200        self
201    }
202}
203
204impl Command for TsCreate {
205    type Response = ();
206
207    fn to_frame(&self) -> Frame {
208        let mut args = vec![bulk("TS.CREATE"), bulk(&self.key)];
209        if let Some(retention) = self.retention {
210            args.push(bulk("RETENTION"));
211            args.push(bulk(retention.to_string()));
212        }
213        if let Some(enc) = &self.encoding {
214            args.push(bulk("ENCODING"));
215            args.push(bulk(enc.as_str()));
216        }
217        if let Some(cs) = self.chunk_size {
218            args.push(bulk("CHUNK_SIZE"));
219            args.push(bulk(cs.to_string()));
220        }
221        if let Some(dp) = &self.duplicate_policy {
222            args.push(bulk("DUPLICATE_POLICY"));
223            args.push(bulk(dp.as_str()));
224        }
225        push_labels(&mut args, &self.labels);
226        array(args)
227    }
228
229    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
230        match frame {
231            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
232            other => Err(RedisError::UnexpectedResponse {
233                expected: "OK",
234                actual: format!("{other:?}"),
235            }),
236        }
237    }
238
239    fn name(&self) -> &str {
240        "TS.CREATE"
241    }
242}
243
244// ---------------------------------------------------------------------------
245// TS.ALTER
246// ---------------------------------------------------------------------------
247
248/// TS.ALTER key \[RETENTION ms\] \[CHUNK_SIZE bytes\]
249/// \[DUPLICATE_POLICY policy\] \[LABELS label value ...\]
250///
251/// Alters an existing TimeSeries key configuration.
252#[derive(Clone)]
253pub struct TsAlter {
254    key: CommandArg,
255    retention: Option<u64>,
256    chunk_size: Option<u64>,
257    duplicate_policy: Option<TsDuplicatePolicy>,
258    labels: Vec<(CommandArg, CommandArg)>,
259}
260
261impl TsAlter {
262    /// Create a new [`TsAlter`] command.
263    pub fn new(key: impl Into<CommandArg>) -> Self {
264        Self {
265            key: key.into(),
266            retention: None,
267            chunk_size: None,
268            duplicate_policy: None,
269            labels: Vec::new(),
270        }
271    }
272
273    /// Set the retention period in milliseconds.
274    pub fn retention(mut self, ms: u64) -> Self {
275        self.retention = Some(ms);
276        self
277    }
278
279    /// Set the chunk size in bytes.
280    pub fn chunk_size(mut self, bytes: u64) -> Self {
281        self.chunk_size = Some(bytes);
282        self
283    }
284
285    /// Set the duplicate policy.
286    pub fn duplicate_policy(mut self, policy: TsDuplicatePolicy) -> Self {
287        self.duplicate_policy = Some(policy);
288        self
289    }
290
291    /// Add a label key-value pair.
292    pub fn label(mut self, key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
293        self.labels.push((key.into(), value.into()));
294        self
295    }
296}
297
298impl Command for TsAlter {
299    type Response = ();
300
301    fn to_frame(&self) -> Frame {
302        let mut args = vec![bulk("TS.ALTER"), bulk(&self.key)];
303        if let Some(retention) = self.retention {
304            args.push(bulk("RETENTION"));
305            args.push(bulk(retention.to_string()));
306        }
307        if let Some(cs) = self.chunk_size {
308            args.push(bulk("CHUNK_SIZE"));
309            args.push(bulk(cs.to_string()));
310        }
311        if let Some(dp) = &self.duplicate_policy {
312            args.push(bulk("DUPLICATE_POLICY"));
313            args.push(bulk(dp.as_str()));
314        }
315        push_labels(&mut args, &self.labels);
316        array(args)
317    }
318
319    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
320        match frame {
321            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
322            other => Err(RedisError::UnexpectedResponse {
323                expected: "OK",
324                actual: format!("{other:?}"),
325            }),
326        }
327    }
328
329    fn name(&self) -> &str {
330        "TS.ALTER"
331    }
332}
333
334// ---------------------------------------------------------------------------
335// TS.DEL
336// ---------------------------------------------------------------------------
337
338/// TS.DEL key from_timestamp to_timestamp
339///
340/// Deletes samples between two timestamps (inclusive). Returns the number
341/// of samples deleted.
342#[derive(Clone)]
343pub struct TsDel {
344    key: CommandArg,
345    from: i64,
346    to: i64,
347}
348
349impl TsDel {
350    /// Create a new [`TsDel`] command.
351    pub fn new(key: impl Into<CommandArg>, from: i64, to: i64) -> Self {
352        Self {
353            key: key.into(),
354            from,
355            to,
356        }
357    }
358}
359
360impl Command for TsDel {
361    type Response = i64;
362
363    fn to_frame(&self) -> Frame {
364        array(vec![
365            bulk("TS.DEL"),
366            bulk(&self.key),
367            bulk(self.from.to_string()),
368            bulk(self.to.to_string()),
369        ])
370    }
371
372    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
373        match frame {
374            Frame::Integer(n) => Ok(n),
375            other => Err(RedisError::UnexpectedResponse {
376                expected: "integer",
377                actual: format!("{other:?}"),
378            }),
379        }
380    }
381
382    fn name(&self) -> &str {
383        "TS.DEL"
384    }
385}
386
387// ---------------------------------------------------------------------------
388// TS.ADD
389// ---------------------------------------------------------------------------
390
391/// Timestamp value for TS.ADD. Use `Auto` for server-assigned timestamps
392/// or `Value(ms)` for explicit millisecond timestamps.
393#[derive(Debug, Clone, Copy)]
394pub enum TsTimestamp {
395    /// Let the server assign a timestamp ("*").
396    Auto,
397    /// Explicit timestamp in milliseconds.
398    Value(i64),
399}
400
401impl TsTimestamp {
402    fn to_bulk(self) -> Frame {
403        match self {
404            TsTimestamp::Auto => bulk("*"),
405            TsTimestamp::Value(ts) => bulk(ts.to_string()),
406        }
407    }
408}
409
410impl From<i64> for TsTimestamp {
411    fn from(ts: i64) -> Self {
412        TsTimestamp::Value(ts)
413    }
414}
415
416/// TS.ADD key timestamp value \[RETENTION ms\] \[ENCODING enc\]
417/// \[CHUNK_SIZE bytes\] \[ON_DUPLICATE policy\] \[LABELS label value ...\]
418///
419/// Appends a sample to a TimeSeries key. Returns the timestamp of the
420/// added sample.
421#[derive(Clone)]
422pub struct TsAdd {
423    key: CommandArg,
424    timestamp: TsTimestamp,
425    value: f64,
426    retention: Option<u64>,
427    encoding: Option<TsEncoding>,
428    chunk_size: Option<u64>,
429    on_duplicate: Option<TsDuplicatePolicy>,
430    labels: Vec<(CommandArg, CommandArg)>,
431}
432
433impl TsAdd {
434    /// Create a new [`TsAdd`] command.
435    pub fn new(key: impl Into<CommandArg>, timestamp: impl Into<TsTimestamp>, value: f64) -> Self {
436        Self {
437            key: key.into(),
438            timestamp: timestamp.into(),
439            value,
440            retention: None,
441            encoding: None,
442            chunk_size: None,
443            on_duplicate: None,
444            labels: Vec::new(),
445        }
446    }
447
448    /// Set the retention period in milliseconds.
449    pub fn retention(mut self, ms: u64) -> Self {
450        self.retention = Some(ms);
451        self
452    }
453
454    /// Set the encoding type.
455    pub fn encoding(mut self, enc: TsEncoding) -> Self {
456        self.encoding = Some(enc);
457        self
458    }
459
460    /// Set the chunk size in bytes.
461    pub fn chunk_size(mut self, bytes: u64) -> Self {
462        self.chunk_size = Some(bytes);
463        self
464    }
465
466    /// Set the on-duplicate policy.
467    pub fn on_duplicate(mut self, policy: TsDuplicatePolicy) -> Self {
468        self.on_duplicate = Some(policy);
469        self
470    }
471
472    /// Add a label key-value pair.
473    pub fn label(mut self, key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
474        self.labels.push((key.into(), value.into()));
475        self
476    }
477}
478
479impl Command for TsAdd {
480    type Response = i64;
481
482    fn to_frame(&self) -> Frame {
483        let mut args = vec![
484            bulk("TS.ADD"),
485            bulk(&self.key),
486            self.timestamp.to_bulk(),
487            bulk(self.value.to_string()),
488        ];
489        if let Some(retention) = self.retention {
490            args.push(bulk("RETENTION"));
491            args.push(bulk(retention.to_string()));
492        }
493        if let Some(enc) = &self.encoding {
494            args.push(bulk("ENCODING"));
495            args.push(bulk(enc.as_str()));
496        }
497        if let Some(cs) = self.chunk_size {
498            args.push(bulk("CHUNK_SIZE"));
499            args.push(bulk(cs.to_string()));
500        }
501        if let Some(dp) = &self.on_duplicate {
502            args.push(bulk("ON_DUPLICATE"));
503            args.push(bulk(dp.as_str()));
504        }
505        push_labels(&mut args, &self.labels);
506        array(args)
507    }
508
509    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
510        match frame {
511            Frame::Integer(n) => Ok(n),
512            other => Err(RedisError::UnexpectedResponse {
513                expected: "integer",
514                actual: format!("{other:?}"),
515            }),
516        }
517    }
518
519    fn name(&self) -> &str {
520        "TS.ADD"
521    }
522}
523
524// ---------------------------------------------------------------------------
525// TS.MADD
526// ---------------------------------------------------------------------------
527
528/// TS.MADD key timestamp value \[key timestamp value ...\]
529///
530/// Appends samples to multiple TimeSeries keys. Returns the raw array of
531/// timestamps (or errors per sample).
532#[derive(Clone)]
533pub struct TsMAdd {
534    samples: Vec<(CommandArg, TsTimestamp, f64)>,
535}
536
537impl TsMAdd {
538    /// Create a new [`TsMAdd`] command.
539    pub fn new() -> Self {
540        Self {
541            samples: Vec::new(),
542        }
543    }
544
545    /// Add a sample (key, timestamp, value) to the batch.
546    pub fn sample(
547        mut self,
548        key: impl Into<CommandArg>,
549        timestamp: impl Into<TsTimestamp>,
550        value: f64,
551    ) -> Self {
552        self.samples.push((key.into(), timestamp.into(), value));
553        self
554    }
555}
556
557impl Default for TsMAdd {
558    fn default() -> Self {
559        Self::new()
560    }
561}
562
563impl Command for TsMAdd {
564    type Response = Vec<Frame>;
565
566    fn to_frame(&self) -> Frame {
567        let mut args = vec![bulk("TS.MADD")];
568        for (key, ts, value) in &self.samples {
569            args.push(bulk(key));
570            args.push(ts.to_bulk());
571            args.push(bulk(value.to_string()));
572        }
573        array(args)
574    }
575
576    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
577        match frame {
578            Frame::Array(Some(frames)) => Ok(frames),
579            other => Err(RedisError::UnexpectedResponse {
580                expected: "array",
581                actual: format!("{other:?}"),
582            }),
583        }
584    }
585
586    fn name(&self) -> &str {
587        "TS.MADD"
588    }
589}
590
591// ---------------------------------------------------------------------------
592// TS.INCRBY / TS.DECRBY (shared structure)
593// ---------------------------------------------------------------------------
594
595/// TS.INCRBY key value \[TIMESTAMP ts\] \[RETENTION ms\] \[LABELS ...\]
596///
597/// Increments the value of the latest sample in a TimeSeries key.
598/// Creates the key if it does not exist. Returns the timestamp.
599#[derive(Clone)]
600pub struct TsIncrBy {
601    key: CommandArg,
602    value: f64,
603    timestamp: Option<TsTimestamp>,
604    retention: Option<u64>,
605    labels: Vec<(CommandArg, CommandArg)>,
606}
607
608impl TsIncrBy {
609    /// Create a new [`TsIncrBy`] command.
610    pub fn new(key: impl Into<CommandArg>, value: f64) -> Self {
611        Self {
612            key: key.into(),
613            value,
614            timestamp: None,
615            retention: None,
616            labels: Vec::new(),
617        }
618    }
619
620    /// Set an explicit timestamp.
621    pub fn timestamp(mut self, ts: impl Into<TsTimestamp>) -> Self {
622        self.timestamp = Some(ts.into());
623        self
624    }
625
626    /// Set the retention period in milliseconds.
627    pub fn retention(mut self, ms: u64) -> Self {
628        self.retention = Some(ms);
629        self
630    }
631
632    /// Add a label key-value pair.
633    pub fn label(mut self, key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
634        self.labels.push((key.into(), value.into()));
635        self
636    }
637}
638
639impl Command for TsIncrBy {
640    type Response = i64;
641
642    fn to_frame(&self) -> Frame {
643        let mut args = vec![
644            bulk("TS.INCRBY"),
645            bulk(&self.key),
646            bulk(self.value.to_string()),
647        ];
648        if let Some(ts) = &self.timestamp {
649            args.push(bulk("TIMESTAMP"));
650            args.push(ts.to_bulk());
651        }
652        if let Some(retention) = self.retention {
653            args.push(bulk("RETENTION"));
654            args.push(bulk(retention.to_string()));
655        }
656        push_labels(&mut args, &self.labels);
657        array(args)
658    }
659
660    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
661        match frame {
662            Frame::Integer(n) => Ok(n),
663            other => Err(RedisError::UnexpectedResponse {
664                expected: "integer",
665                actual: format!("{other:?}"),
666            }),
667        }
668    }
669
670    fn name(&self) -> &str {
671        "TS.INCRBY"
672    }
673}
674
675/// TS.DECRBY key value \[TIMESTAMP ts\] \[RETENTION ms\] \[LABELS ...\]
676///
677/// Decrements the value of the latest sample in a TimeSeries key.
678/// Creates the key if it does not exist. Returns the timestamp.
679#[derive(Clone)]
680pub struct TsDecrBy {
681    key: CommandArg,
682    value: f64,
683    timestamp: Option<TsTimestamp>,
684    retention: Option<u64>,
685    labels: Vec<(CommandArg, CommandArg)>,
686}
687
688impl TsDecrBy {
689    /// Create a new [`TsDecrBy`] command.
690    pub fn new(key: impl Into<CommandArg>, value: f64) -> Self {
691        Self {
692            key: key.into(),
693            value,
694            timestamp: None,
695            retention: None,
696            labels: Vec::new(),
697        }
698    }
699
700    /// Set an explicit timestamp.
701    pub fn timestamp(mut self, ts: impl Into<TsTimestamp>) -> Self {
702        self.timestamp = Some(ts.into());
703        self
704    }
705
706    /// Set the retention period in milliseconds.
707    pub fn retention(mut self, ms: u64) -> Self {
708        self.retention = Some(ms);
709        self
710    }
711
712    /// Add a label key-value pair.
713    pub fn label(mut self, key: impl Into<CommandArg>, value: impl Into<CommandArg>) -> Self {
714        self.labels.push((key.into(), value.into()));
715        self
716    }
717}
718
719impl Command for TsDecrBy {
720    type Response = i64;
721
722    fn to_frame(&self) -> Frame {
723        let mut args = vec![
724            bulk("TS.DECRBY"),
725            bulk(&self.key),
726            bulk(self.value.to_string()),
727        ];
728        if let Some(ts) = &self.timestamp {
729            args.push(bulk("TIMESTAMP"));
730            args.push(ts.to_bulk());
731        }
732        if let Some(retention) = self.retention {
733            args.push(bulk("RETENTION"));
734            args.push(bulk(retention.to_string()));
735        }
736        push_labels(&mut args, &self.labels);
737        array(args)
738    }
739
740    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
741        match frame {
742            Frame::Integer(n) => Ok(n),
743            other => Err(RedisError::UnexpectedResponse {
744                expected: "integer",
745                actual: format!("{other:?}"),
746            }),
747        }
748    }
749
750    fn name(&self) -> &str {
751        "TS.DECRBY"
752    }
753}
754
755// ---------------------------------------------------------------------------
756// TS.GET
757// ---------------------------------------------------------------------------
758
759/// TS.GET key \[LATEST\]
760///
761/// Returns the last sample of a TimeSeries key as a raw Frame
762/// (timestamp-value pair, or empty if the key has no samples).
763#[derive(Clone)]
764pub struct TsGet {
765    key: CommandArg,
766    latest: bool,
767}
768
769impl TsGet {
770    /// Create a new [`TsGet`] command.
771    pub fn new(key: impl Into<CommandArg>) -> Self {
772        Self {
773            key: key.into(),
774            latest: false,
775        }
776    }
777
778    /// Include the latest (possibly un-compacted) bucket.
779    pub fn latest(mut self) -> Self {
780        self.latest = true;
781        self
782    }
783}
784
785impl Command for TsGet {
786    type Response = Frame;
787
788    fn to_frame(&self) -> Frame {
789        let mut args = vec![bulk("TS.GET"), bulk(&self.key)];
790        if self.latest {
791            args.push(bulk("LATEST"));
792        }
793        array(args)
794    }
795
796    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
797        Ok(frame)
798    }
799
800    fn name(&self) -> &str {
801        "TS.GET"
802    }
803
804    fn idempotent(&self) -> bool {
805        true
806    }
807}
808
809// ---------------------------------------------------------------------------
810// TS.MGET
811// ---------------------------------------------------------------------------
812
813/// TS.MGET \[LATEST\] \[WITHLABELS\] FILTER filter_expr \[filter_expr ...\]
814///
815/// Returns the last sample of multiple TimeSeries keys matching the given
816/// filter expressions. Returns the raw Frame.
817#[derive(Clone)]
818pub struct TsMGet {
819    latest: bool,
820    withlabels: bool,
821    filters: Vec<String>,
822}
823
824impl TsMGet {
825    /// Create a new [`TsMGet`] command.
826    pub fn new(filter: impl Into<String>) -> Self {
827        Self {
828            latest: false,
829            withlabels: false,
830            filters: vec![filter.into()],
831        }
832    }
833
834    /// Add an additional filter expression.
835    pub fn filter(mut self, expr: impl Into<String>) -> Self {
836        self.filters.push(expr.into());
837        self
838    }
839
840    /// Include the latest (possibly un-compacted) bucket.
841    pub fn latest(mut self) -> Self {
842        self.latest = true;
843        self
844    }
845
846    /// Include labels in the response.
847    pub fn withlabels(mut self) -> Self {
848        self.withlabels = true;
849        self
850    }
851}
852
853impl Command for TsMGet {
854    type Response = Frame;
855
856    fn to_frame(&self) -> Frame {
857        let mut args = vec![bulk("TS.MGET")];
858        if self.latest {
859            args.push(bulk("LATEST"));
860        }
861        if self.withlabels {
862            args.push(bulk("WITHLABELS"));
863        }
864        args.push(bulk("FILTER"));
865        for f in &self.filters {
866            args.push(bulk(f.as_str()));
867        }
868        array(args)
869    }
870
871    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
872        Ok(frame)
873    }
874
875    fn name(&self) -> &str {
876        "TS.MGET"
877    }
878
879    fn idempotent(&self) -> bool {
880        true
881    }
882}
883
884// ---------------------------------------------------------------------------
885// TS.RANGE / TS.REVRANGE (shared builder logic)
886// ---------------------------------------------------------------------------
887
888/// Common options for TS.RANGE and TS.REVRANGE.
889#[derive(Clone)]
890struct TsRangeOptions {
891    key: CommandArg,
892    from: String,
893    to: String,
894    latest: bool,
895    filter_by_ts: Vec<i64>,
896    filter_by_value: Option<(f64, f64)>,
897    count: Option<i64>,
898    aggregation: Option<(TsAggregation, i64)>,
899}
900
901/// TS.RANGE key from to \[LATEST\] \[FILTER_BY_TS ts ...\]
902/// \[FILTER_BY_VALUE min max\] \[COUNT count\] \[AGGREGATION agg timebucket\]
903///
904/// Queries a range of samples from a TimeSeries key in chronological
905/// order. Returns the raw Frame.
906#[derive(Clone)]
907pub struct TsRange {
908    opts: TsRangeOptions,
909}
910
911impl TsRange {
912    /// Create a range query. `from` and `to` are timestamp strings
913    /// (use "-" for minimum, "+" for maximum, or a millisecond timestamp).
914    pub fn new(key: impl Into<CommandArg>, from: impl Into<String>, to: impl Into<String>) -> Self {
915        Self {
916            opts: TsRangeOptions {
917                key: key.into(),
918                from: from.into(),
919                to: to.into(),
920                latest: false,
921                filter_by_ts: Vec::new(),
922                filter_by_value: None,
923                count: None,
924                aggregation: None,
925            },
926        }
927    }
928
929    /// Include the latest (possibly un-compacted) bucket.
930    pub fn latest(mut self) -> Self {
931        self.opts.latest = true;
932        self
933    }
934
935    /// Filter results to specific timestamps.
936    pub fn filter_by_ts(mut self, timestamps: impl IntoIterator<Item = i64>) -> Self {
937        self.opts.filter_by_ts = timestamps.into_iter().collect();
938        self
939    }
940
941    /// Filter results to a value range.
942    pub fn filter_by_value(mut self, min: f64, max: f64) -> Self {
943        self.opts.filter_by_value = Some((min, max));
944        self
945    }
946
947    /// Limit the number of returned samples.
948    pub fn count(mut self, count: i64) -> Self {
949        self.opts.count = Some(count);
950        self
951    }
952
953    /// Apply an aggregation with the given time bucket (in milliseconds).
954    pub fn aggregation(mut self, agg: TsAggregation, time_bucket: i64) -> Self {
955        self.opts.aggregation = Some((agg, time_bucket));
956        self
957    }
958}
959
960fn push_range_args(args: &mut Vec<Frame>, opts: &TsRangeOptions) {
961    args.push(bulk(&opts.key));
962    args.push(bulk(opts.from.as_str()));
963    args.push(bulk(opts.to.as_str()));
964    if opts.latest {
965        args.push(bulk("LATEST"));
966    }
967    if !opts.filter_by_ts.is_empty() {
968        args.push(bulk("FILTER_BY_TS"));
969        for ts in &opts.filter_by_ts {
970            args.push(bulk(ts.to_string()));
971        }
972    }
973    if let Some((min, max)) = opts.filter_by_value {
974        args.push(bulk("FILTER_BY_VALUE"));
975        args.push(bulk(min.to_string()));
976        args.push(bulk(max.to_string()));
977    }
978    if let Some(count) = opts.count {
979        args.push(bulk("COUNT"));
980        args.push(bulk(count.to_string()));
981    }
982    if let Some((agg, bucket)) = &opts.aggregation {
983        args.push(bulk("AGGREGATION"));
984        args.push(bulk(agg.as_str()));
985        args.push(bulk(bucket.to_string()));
986    }
987}
988
989impl Command for TsRange {
990    type Response = Frame;
991
992    fn to_frame(&self) -> Frame {
993        let mut args = vec![bulk("TS.RANGE")];
994        push_range_args(&mut args, &self.opts);
995        array(args)
996    }
997
998    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
999        Ok(frame)
1000    }
1001
1002    fn name(&self) -> &str {
1003        "TS.RANGE"
1004    }
1005
1006    fn idempotent(&self) -> bool {
1007        true
1008    }
1009}
1010
1011/// TS.REVRANGE key from to \[LATEST\] \[FILTER_BY_TS ts ...\]
1012/// \[FILTER_BY_VALUE min max\] \[COUNT count\] \[AGGREGATION agg timebucket\]
1013///
1014/// Queries a range of samples from a TimeSeries key in reverse
1015/// chronological order. Returns the raw Frame.
1016#[derive(Clone)]
1017pub struct TsRevRange {
1018    opts: TsRangeOptions,
1019}
1020
1021impl TsRevRange {
1022    /// Create a reverse range query. `from` and `to` are timestamp strings
1023    /// (use "-" for minimum, "+" for maximum, or a millisecond timestamp).
1024    pub fn new(key: impl Into<CommandArg>, from: impl Into<String>, to: impl Into<String>) -> Self {
1025        Self {
1026            opts: TsRangeOptions {
1027                key: key.into(),
1028                from: from.into(),
1029                to: to.into(),
1030                latest: false,
1031                filter_by_ts: Vec::new(),
1032                filter_by_value: None,
1033                count: None,
1034                aggregation: None,
1035            },
1036        }
1037    }
1038
1039    /// Include the latest (possibly un-compacted) bucket.
1040    pub fn latest(mut self) -> Self {
1041        self.opts.latest = true;
1042        self
1043    }
1044
1045    /// Filter results to specific timestamps.
1046    pub fn filter_by_ts(mut self, timestamps: impl IntoIterator<Item = i64>) -> Self {
1047        self.opts.filter_by_ts = timestamps.into_iter().collect();
1048        self
1049    }
1050
1051    /// Filter results to a value range.
1052    pub fn filter_by_value(mut self, min: f64, max: f64) -> Self {
1053        self.opts.filter_by_value = Some((min, max));
1054        self
1055    }
1056
1057    /// Limit the number of returned samples.
1058    pub fn count(mut self, count: i64) -> Self {
1059        self.opts.count = Some(count);
1060        self
1061    }
1062
1063    /// Apply an aggregation with the given time bucket (in milliseconds).
1064    pub fn aggregation(mut self, agg: TsAggregation, time_bucket: i64) -> Self {
1065        self.opts.aggregation = Some((agg, time_bucket));
1066        self
1067    }
1068}
1069
1070impl Command for TsRevRange {
1071    type Response = Frame;
1072
1073    fn to_frame(&self) -> Frame {
1074        let mut args = vec![bulk("TS.REVRANGE")];
1075        push_range_args(&mut args, &self.opts);
1076        array(args)
1077    }
1078
1079    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1080        Ok(frame)
1081    }
1082
1083    fn name(&self) -> &str {
1084        "TS.REVRANGE"
1085    }
1086
1087    fn idempotent(&self) -> bool {
1088        true
1089    }
1090}
1091
1092// ---------------------------------------------------------------------------
1093// TS.MRANGE / TS.MREVRANGE (shared builder logic)
1094// ---------------------------------------------------------------------------
1095
1096/// Common options for TS.MRANGE and TS.MREVRANGE.
1097#[derive(Clone)]
1098struct TsMRangeOptions {
1099    from: String,
1100    to: String,
1101    latest: bool,
1102    withlabels: bool,
1103    filter_by_ts: Vec<i64>,
1104    filter_by_value: Option<(f64, f64)>,
1105    count: Option<i64>,
1106    aggregation: Option<(TsAggregation, i64)>,
1107    filters: Vec<String>,
1108}
1109
1110fn push_mrange_args(args: &mut Vec<Frame>, opts: &TsMRangeOptions) {
1111    args.push(bulk(opts.from.as_str()));
1112    args.push(bulk(opts.to.as_str()));
1113    if opts.latest {
1114        args.push(bulk("LATEST"));
1115    }
1116    if !opts.filter_by_ts.is_empty() {
1117        args.push(bulk("FILTER_BY_TS"));
1118        for ts in &opts.filter_by_ts {
1119            args.push(bulk(ts.to_string()));
1120        }
1121    }
1122    if let Some((min, max)) = opts.filter_by_value {
1123        args.push(bulk("FILTER_BY_VALUE"));
1124        args.push(bulk(min.to_string()));
1125        args.push(bulk(max.to_string()));
1126    }
1127    if opts.withlabels {
1128        args.push(bulk("WITHLABELS"));
1129    }
1130    if let Some(count) = opts.count {
1131        args.push(bulk("COUNT"));
1132        args.push(bulk(count.to_string()));
1133    }
1134    if let Some((agg, bucket)) = &opts.aggregation {
1135        args.push(bulk("AGGREGATION"));
1136        args.push(bulk(agg.as_str()));
1137        args.push(bulk(bucket.to_string()));
1138    }
1139    args.push(bulk("FILTER"));
1140    for f in &opts.filters {
1141        args.push(bulk(f.as_str()));
1142    }
1143}
1144
1145/// TS.MRANGE from to \[LATEST\] \[WITHLABELS\] \[FILTER_BY_TS ts ...\]
1146/// \[FILTER_BY_VALUE min max\] \[COUNT count\] \[AGGREGATION agg timebucket\]
1147/// FILTER filter_expr \[filter_expr ...\]
1148///
1149/// Queries a range of samples from multiple TimeSeries keys matching
1150/// the given filter expressions. Returns the raw Frame.
1151#[derive(Clone)]
1152pub struct TsMRange {
1153    opts: TsMRangeOptions,
1154}
1155
1156impl TsMRange {
1157    /// Create a multi-key range query.
1158    pub fn new(from: impl Into<String>, to: impl Into<String>, filter: impl Into<String>) -> Self {
1159        Self {
1160            opts: TsMRangeOptions {
1161                from: from.into(),
1162                to: to.into(),
1163                latest: false,
1164                withlabels: false,
1165                filter_by_ts: Vec::new(),
1166                filter_by_value: None,
1167                count: None,
1168                aggregation: None,
1169                filters: vec![filter.into()],
1170            },
1171        }
1172    }
1173
1174    /// Add an additional filter expression.
1175    pub fn filter(mut self, expr: impl Into<String>) -> Self {
1176        self.opts.filters.push(expr.into());
1177        self
1178    }
1179
1180    /// Include the latest (possibly un-compacted) bucket.
1181    pub fn latest(mut self) -> Self {
1182        self.opts.latest = true;
1183        self
1184    }
1185
1186    /// Include labels in the response.
1187    pub fn withlabels(mut self) -> Self {
1188        self.opts.withlabels = true;
1189        self
1190    }
1191
1192    /// Filter results to specific timestamps.
1193    pub fn filter_by_ts(mut self, timestamps: impl IntoIterator<Item = i64>) -> Self {
1194        self.opts.filter_by_ts = timestamps.into_iter().collect();
1195        self
1196    }
1197
1198    /// Filter results to a value range.
1199    pub fn filter_by_value(mut self, min: f64, max: f64) -> Self {
1200        self.opts.filter_by_value = Some((min, max));
1201        self
1202    }
1203
1204    /// Limit the number of returned samples per key.
1205    pub fn count(mut self, count: i64) -> Self {
1206        self.opts.count = Some(count);
1207        self
1208    }
1209
1210    /// Apply an aggregation with the given time bucket (in milliseconds).
1211    pub fn aggregation(mut self, agg: TsAggregation, time_bucket: i64) -> Self {
1212        self.opts.aggregation = Some((agg, time_bucket));
1213        self
1214    }
1215}
1216
1217impl Command for TsMRange {
1218    type Response = Frame;
1219
1220    fn to_frame(&self) -> Frame {
1221        let mut args = vec![bulk("TS.MRANGE")];
1222        push_mrange_args(&mut args, &self.opts);
1223        array(args)
1224    }
1225
1226    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1227        Ok(frame)
1228    }
1229
1230    fn name(&self) -> &str {
1231        "TS.MRANGE"
1232    }
1233
1234    fn idempotent(&self) -> bool {
1235        true
1236    }
1237}
1238
1239/// TS.MREVRANGE from to \[LATEST\] \[WITHLABELS\] \[FILTER_BY_TS ts ...\]
1240/// \[FILTER_BY_VALUE min max\] \[COUNT count\] \[AGGREGATION agg timebucket\]
1241/// FILTER filter_expr \[filter_expr ...\]
1242///
1243/// Queries a range of samples from multiple TimeSeries keys in reverse
1244/// chronological order. Returns the raw Frame.
1245#[derive(Clone)]
1246pub struct TsMRevRange {
1247    opts: TsMRangeOptions,
1248}
1249
1250impl TsMRevRange {
1251    /// Create a multi-key reverse range query.
1252    pub fn new(from: impl Into<String>, to: impl Into<String>, filter: impl Into<String>) -> Self {
1253        Self {
1254            opts: TsMRangeOptions {
1255                from: from.into(),
1256                to: to.into(),
1257                latest: false,
1258                withlabels: false,
1259                filter_by_ts: Vec::new(),
1260                filter_by_value: None,
1261                count: None,
1262                aggregation: None,
1263                filters: vec![filter.into()],
1264            },
1265        }
1266    }
1267
1268    /// Add an additional filter expression.
1269    pub fn filter(mut self, expr: impl Into<String>) -> Self {
1270        self.opts.filters.push(expr.into());
1271        self
1272    }
1273
1274    /// Include the latest (possibly un-compacted) bucket.
1275    pub fn latest(mut self) -> Self {
1276        self.opts.latest = true;
1277        self
1278    }
1279
1280    /// Include labels in the response.
1281    pub fn withlabels(mut self) -> Self {
1282        self.opts.withlabels = true;
1283        self
1284    }
1285
1286    /// Filter results to specific timestamps.
1287    pub fn filter_by_ts(mut self, timestamps: impl IntoIterator<Item = i64>) -> Self {
1288        self.opts.filter_by_ts = timestamps.into_iter().collect();
1289        self
1290    }
1291
1292    /// Filter results to a value range.
1293    pub fn filter_by_value(mut self, min: f64, max: f64) -> Self {
1294        self.opts.filter_by_value = Some((min, max));
1295        self
1296    }
1297
1298    /// Limit the number of returned samples per key.
1299    pub fn count(mut self, count: i64) -> Self {
1300        self.opts.count = Some(count);
1301        self
1302    }
1303
1304    /// Apply an aggregation with the given time bucket (in milliseconds).
1305    pub fn aggregation(mut self, agg: TsAggregation, time_bucket: i64) -> Self {
1306        self.opts.aggregation = Some((agg, time_bucket));
1307        self
1308    }
1309}
1310
1311impl Command for TsMRevRange {
1312    type Response = Frame;
1313
1314    fn to_frame(&self) -> Frame {
1315        let mut args = vec![bulk("TS.MREVRANGE")];
1316        push_mrange_args(&mut args, &self.opts);
1317        array(args)
1318    }
1319
1320    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1321        Ok(frame)
1322    }
1323
1324    fn name(&self) -> &str {
1325        "TS.MREVRANGE"
1326    }
1327
1328    fn idempotent(&self) -> bool {
1329        true
1330    }
1331}
1332
1333// ---------------------------------------------------------------------------
1334// TS.INFO
1335// ---------------------------------------------------------------------------
1336
1337/// TS.INFO key \[DEBUG\]
1338///
1339/// Returns information and statistics about a TimeSeries key. Returns
1340/// the raw Frame (complex nested structure).
1341#[derive(Clone)]
1342pub struct TsInfo {
1343    key: CommandArg,
1344    debug: bool,
1345}
1346
1347impl TsInfo {
1348    /// Create a new [`TsInfo`] command.
1349    pub fn new(key: impl Into<CommandArg>) -> Self {
1350        Self {
1351            key: key.into(),
1352            debug: false,
1353        }
1354    }
1355
1356    /// Include debug information in the response.
1357    pub fn debug(mut self) -> Self {
1358        self.debug = true;
1359        self
1360    }
1361}
1362
1363impl Command for TsInfo {
1364    type Response = Frame;
1365
1366    fn to_frame(&self) -> Frame {
1367        let mut args = vec![bulk("TS.INFO"), bulk(&self.key)];
1368        if self.debug {
1369            args.push(bulk("DEBUG"));
1370        }
1371        array(args)
1372    }
1373
1374    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1375        Ok(frame)
1376    }
1377
1378    fn name(&self) -> &str {
1379        "TS.INFO"
1380    }
1381
1382    fn idempotent(&self) -> bool {
1383        true
1384    }
1385}
1386
1387// ---------------------------------------------------------------------------
1388// TS.QUERYINDEX
1389// ---------------------------------------------------------------------------
1390
1391/// TS.QUERYINDEX filter_expr \[filter_expr ...\]
1392///
1393/// Returns the keys matching the given filter expressions.
1394#[derive(Clone)]
1395pub struct TsQueryIndex {
1396    filters: Vec<String>,
1397}
1398
1399impl TsQueryIndex {
1400    /// Create a new [`TsQueryIndex`] command.
1401    pub fn new(filter: impl Into<String>) -> Self {
1402        Self {
1403            filters: vec![filter.into()],
1404        }
1405    }
1406
1407    /// Add an additional filter expression.
1408    pub fn filter(mut self, expr: impl Into<String>) -> Self {
1409        self.filters.push(expr.into());
1410        self
1411    }
1412}
1413
1414impl Command for TsQueryIndex {
1415    type Response = Vec<Bytes>;
1416
1417    fn to_frame(&self) -> Frame {
1418        let mut args = vec![bulk("TS.QUERYINDEX")];
1419        for f in &self.filters {
1420            args.push(bulk(f.as_str()));
1421        }
1422        array(args)
1423    }
1424
1425    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1426        match frame {
1427            Frame::Array(Some(frames)) | Frame::Set(frames) | Frame::StreamedSet(frames) => frames
1428                .into_iter()
1429                .map(|f| match f {
1430                    Frame::BulkString(Some(data)) | Frame::SimpleString(data) => Ok(data),
1431                    other => Err(RedisError::UnexpectedResponse {
1432                        expected: "bulk or simple string",
1433                        actual: format!("{other:?}"),
1434                    }),
1435                })
1436                .collect(),
1437            Frame::Array(None) => Ok(Vec::new()),
1438            other => Err(RedisError::UnexpectedResponse {
1439                expected: "array or set",
1440                actual: format!("{other:?}"),
1441            }),
1442        }
1443    }
1444
1445    fn name(&self) -> &str {
1446        "TS.QUERYINDEX"
1447    }
1448
1449    fn idempotent(&self) -> bool {
1450        true
1451    }
1452}
1453
1454// ---------------------------------------------------------------------------
1455// TS.CREATERULE
1456// ---------------------------------------------------------------------------
1457
1458/// TS.CREATERULE sourceKey destKey AGGREGATION aggregator bucketDuration
1459/// \[alignTimestamp\]
1460///
1461/// Creates a compaction rule that aggregates samples from `source_key` into
1462/// `dest_key` over fixed time buckets. Returns `Ok(())` on success.
1463///
1464/// # Example
1465///
1466/// ```no_run
1467/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1468/// use redis_tower_commands::{TsAggregation, TsCreateRule};
1469/// use redis_tower_core::RedisConnection;
1470///
1471/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1472///
1473/// conn.execute(TsCreateRule::new("src", "dst", TsAggregation::Avg, 60_000))
1474///     .await?;
1475/// # Ok(())
1476/// # }
1477/// ```
1478#[derive(Clone)]
1479pub struct TsCreateRule {
1480    source_key: CommandArg,
1481    dest_key: CommandArg,
1482    aggregation: TsAggregation,
1483    bucket_duration: i64,
1484    align_timestamp: Option<i64>,
1485}
1486
1487impl TsCreateRule {
1488    /// Create a new [`TsCreateRule`] command.
1489    pub fn new(
1490        source_key: impl Into<CommandArg>,
1491        dest_key: impl Into<CommandArg>,
1492        aggregation: TsAggregation,
1493        bucket_duration: i64,
1494    ) -> Self {
1495        Self {
1496            source_key: source_key.into(),
1497            dest_key: dest_key.into(),
1498            aggregation,
1499            bucket_duration,
1500            align_timestamp: None,
1501        }
1502    }
1503
1504    /// Set the alignment timestamp for the aggregation buckets.
1505    pub fn align_timestamp(mut self, align_timestamp: i64) -> Self {
1506        self.align_timestamp = Some(align_timestamp);
1507        self
1508    }
1509}
1510
1511impl Command for TsCreateRule {
1512    type Response = ();
1513
1514    fn to_frame(&self) -> Frame {
1515        let mut args = vec![
1516            bulk("TS.CREATERULE"),
1517            bulk(&self.source_key),
1518            bulk(&self.dest_key),
1519            bulk("AGGREGATION"),
1520            bulk(self.aggregation.as_str()),
1521            bulk(self.bucket_duration.to_string()),
1522        ];
1523        if let Some(align) = self.align_timestamp {
1524            args.push(bulk(align.to_string()));
1525        }
1526        array(args)
1527    }
1528
1529    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1530        match frame {
1531            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1532            other => Err(RedisError::UnexpectedResponse {
1533                expected: "OK",
1534                actual: format!("{other:?}"),
1535            }),
1536        }
1537    }
1538
1539    fn name(&self) -> &str {
1540        "TS.CREATERULE"
1541    }
1542}
1543
1544// ---------------------------------------------------------------------------
1545// TS.DELETERULE
1546// ---------------------------------------------------------------------------
1547
1548/// TS.DELETERULE sourceKey destKey
1549///
1550/// Deletes the compaction rule from `source_key` to `dest_key`. Returns
1551/// `Ok(())` on success.
1552///
1553/// # Example
1554///
1555/// ```no_run
1556/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
1557/// use redis_tower_commands::TsDeleteRule;
1558/// use redis_tower_core::RedisConnection;
1559///
1560/// let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
1561///
1562/// conn.execute(TsDeleteRule::new("src", "dst")).await?;
1563/// # Ok(())
1564/// # }
1565/// ```
1566#[derive(Clone)]
1567pub struct TsDeleteRule {
1568    source_key: CommandArg,
1569    dest_key: CommandArg,
1570}
1571
1572impl TsDeleteRule {
1573    /// Create a new [`TsDeleteRule`] command.
1574    pub fn new(source_key: impl Into<CommandArg>, dest_key: impl Into<CommandArg>) -> Self {
1575        Self {
1576            source_key: source_key.into(),
1577            dest_key: dest_key.into(),
1578        }
1579    }
1580}
1581
1582impl Command for TsDeleteRule {
1583    type Response = ();
1584
1585    fn to_frame(&self) -> Frame {
1586        array(vec![
1587            bulk("TS.DELETERULE"),
1588            bulk(&self.source_key),
1589            bulk(&self.dest_key),
1590        ])
1591    }
1592
1593    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1594        match frame {
1595            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1596            other => Err(RedisError::UnexpectedResponse {
1597                expected: "OK",
1598                actual: format!("{other:?}"),
1599            }),
1600        }
1601    }
1602
1603    fn name(&self) -> &str {
1604        "TS.DELETERULE"
1605    }
1606}
1607
1608#[cfg(test)]
1609mod tests {
1610    use super::*;
1611    use redis_tower_core::Command;
1612    use redis_tower_protocol::helpers::{array, bulk};
1613
1614    #[test]
1615    fn idempotency_flags() {
1616        // Read-only commands are safe to retry.
1617        assert!(TsGet::new("k").idempotent());
1618        // Mutating commands keep the default (false).
1619        assert!(!TsAdd::new("k", 1i64, 1.0).idempotent());
1620    }
1621
1622    #[test]
1623    fn ts_queryindex_accepts_resp2_array_and_resp3_sets() {
1624        let command = TsQueryIndex::new("sensor=temperature");
1625        let expected = vec![Bytes::from_static(b"ts:a"), Bytes::from_static(b"ts:b")];
1626
1627        assert_eq!(
1628            command
1629                .parse_response(Frame::Array(Some(vec![bulk("ts:a"), bulk("ts:b")])))
1630                .unwrap(),
1631            expected
1632        );
1633        assert_eq!(
1634            command
1635                .parse_response(Frame::Set(vec![
1636                    Frame::SimpleString(Bytes::from_static(b"ts:a")),
1637                    bulk("ts:b"),
1638                ]))
1639                .unwrap(),
1640            expected
1641        );
1642        assert_eq!(
1643            command
1644                .parse_response(Frame::StreamedSet(vec![bulk("ts:a"), bulk("ts:b")]))
1645                .unwrap(),
1646            expected
1647        );
1648    }
1649
1650    #[test]
1651    fn ts_createrule_to_frame() {
1652        let cmd = TsCreateRule::new("src", "dst", TsAggregation::Avg, 60_000);
1653        assert_eq!(
1654            cmd.to_frame(),
1655            array(vec![
1656                bulk("TS.CREATERULE"),
1657                bulk("src"),
1658                bulk("dst"),
1659                bulk("AGGREGATION"),
1660                bulk("AVG"),
1661                bulk("60000"),
1662            ])
1663        );
1664    }
1665
1666    #[test]
1667    fn ts_createrule_with_align_to_frame() {
1668        let cmd = TsCreateRule::new("src", "dst", TsAggregation::Sum, 60_000).align_timestamp(0);
1669        assert_eq!(
1670            cmd.to_frame(),
1671            array(vec![
1672                bulk("TS.CREATERULE"),
1673                bulk("src"),
1674                bulk("dst"),
1675                bulk("AGGREGATION"),
1676                bulk("SUM"),
1677                bulk("60000"),
1678                bulk("0"),
1679            ])
1680        );
1681    }
1682
1683    #[test]
1684    fn ts_deleterule_to_frame() {
1685        let cmd = TsDeleteRule::new("src", "dst");
1686        assert_eq!(
1687            cmd.to_frame(),
1688            array(vec![bulk("TS.DELETERULE"), bulk("src"), bulk("dst")])
1689        );
1690    }
1691}