Skip to main content

redis_tower_commands/
tdigest.rs

1//! T-Digest quantile and distribution-estimation commands.
2//!
3//! Available with the `tdigest` feature (included by `stack`) and requiring the
4//! RedisBloom module on the server. Query replies preserve floating-point
5//! results and per-input ordering; estimates are approximate by design.
6//!
7//! ```
8//! use redis_tower_commands::TdigestAdd;
9//! use redis_tower_core::Command;
10//!
11//! let command = TdigestAdd::new("latency", [1.0, 2.0, 8.0]);
12//! assert_eq!(command.name(), "TDIGEST.ADD");
13//! ```
14//!
15//! See the [command cookbook] for feature and server prerequisites.
16//!
17//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#feature-gated-and-versioned-families
18
19use crate::CommandArg;
20use redis_tower_core::{Command, Frame, RedisError};
21use redis_tower_protocol::helpers::{array, bulk};
22
23// ---------------------------------------------------------------------------
24// Helpers
25// ---------------------------------------------------------------------------
26
27fn parse_f64_from_frame(f: Frame) -> Result<f64, RedisError> {
28    match f {
29        Frame::Double(v) => Ok(v),
30        Frame::BulkString(Some(data)) => {
31            let s = std::str::from_utf8(&data).map_err(|_| RedisError::UnexpectedResponse {
32                expected: "valid UTF-8 bulk string",
33                actual: format!("{data:?}"),
34            })?;
35            s.parse::<f64>()
36                .map_err(|_| RedisError::UnexpectedResponse {
37                    expected: "float string",
38                    actual: s.to_string(),
39                })
40        }
41        other => Err(RedisError::UnexpectedResponse {
42            expected: "double or bulk string",
43            actual: format!("{other:?}"),
44        }),
45    }
46}
47
48fn parse_f64_array(frame: Frame) -> Result<Vec<f64>, RedisError> {
49    match frame {
50        Frame::Array(Some(frames)) => frames.into_iter().map(parse_f64_from_frame).collect(),
51        other => Err(RedisError::UnexpectedResponse {
52            expected: "array",
53            actual: format!("{other:?}"),
54        }),
55    }
56}
57
58fn parse_i64_array(frame: Frame) -> Result<Vec<i64>, RedisError> {
59    match frame {
60        Frame::Array(Some(frames)) => frames
61            .into_iter()
62            .map(|f| match f {
63                Frame::Integer(n) => Ok(n),
64                other => Err(RedisError::UnexpectedResponse {
65                    expected: "integer",
66                    actual: format!("{other:?}"),
67                }),
68            })
69            .collect(),
70        other => Err(RedisError::UnexpectedResponse {
71            expected: "array",
72            actual: format!("{other:?}"),
73        }),
74    }
75}
76
77// ===========================================================================
78// T-Digest commands
79// ===========================================================================
80
81/// TDIGEST.CREATE key \[COMPRESSION compression\]
82///
83/// Creates an empty T-Digest sketch at `key`.
84#[derive(Clone)]
85pub struct TdigestCreate {
86    key: CommandArg,
87    compression: Option<i64>,
88}
89
90impl TdigestCreate {
91    /// Create a new [`TdigestCreate`] command.
92    pub fn new(key: impl Into<CommandArg>) -> Self {
93        Self {
94            key: key.into(),
95            compression: None,
96        }
97    }
98
99    /// Set the compression parameter.
100    pub fn compression(mut self, compression: i64) -> Self {
101        self.compression = Some(compression);
102        self
103    }
104}
105
106impl Command for TdigestCreate {
107    type Response = ();
108
109    fn to_frame(&self) -> Frame {
110        let mut args = vec![bulk("TDIGEST.CREATE"), bulk(&self.key)];
111        if let Some(c) = self.compression {
112            args.push(bulk("COMPRESSION"));
113            args.push(bulk(c.to_string()));
114        }
115        array(args)
116    }
117
118    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
119        match frame {
120            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
121            other => Err(RedisError::UnexpectedResponse {
122                expected: "OK",
123                actual: format!("{other:?}"),
124            }),
125        }
126    }
127
128    fn name(&self) -> &str {
129        "TDIGEST.CREATE"
130    }
131}
132
133/// TDIGEST.ADD key value \[value ...\]
134///
135/// Adds one or more values to the T-Digest sketch at `key`.
136#[derive(Clone)]
137pub struct TdigestAdd {
138    key: CommandArg,
139    values: Vec<f64>,
140}
141
142impl TdigestAdd {
143    /// Create a new [`TdigestAdd`] command.
144    pub fn new(key: impl Into<CommandArg>, values: impl IntoIterator<Item = f64>) -> Self {
145        Self {
146            key: key.into(),
147            values: values.into_iter().collect(),
148        }
149    }
150}
151
152impl Command for TdigestAdd {
153    type Response = ();
154
155    fn to_frame(&self) -> Frame {
156        let mut args = vec![bulk("TDIGEST.ADD"), bulk(&self.key)];
157        for v in &self.values {
158            args.push(bulk(v.to_string()));
159        }
160        array(args)
161    }
162
163    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
164        match frame {
165            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
166            other => Err(RedisError::UnexpectedResponse {
167                expected: "OK",
168                actual: format!("{other:?}"),
169            }),
170        }
171    }
172
173    fn name(&self) -> &str {
174        "TDIGEST.ADD"
175    }
176}
177
178/// TDIGEST.MERGE destination numkeys source \[source ...\]
179/// \[COMPRESSION compression\] \[OVERRIDE\]
180///
181/// Merges one or more T-Digest sketches into a destination key.
182#[derive(Clone)]
183pub struct TdigestMerge {
184    destination: CommandArg,
185    sources: Vec<CommandArg>,
186    compression: Option<i64>,
187    override_flag: bool,
188}
189
190impl TdigestMerge {
191    /// Create a new [`TdigestMerge`] command.
192    pub fn new(
193        destination: impl Into<CommandArg>,
194        sources: impl IntoIterator<Item = impl Into<CommandArg>>,
195    ) -> Self {
196        Self {
197            destination: destination.into(),
198            sources: sources.into_iter().map(Into::into).collect(),
199            compression: None,
200            override_flag: false,
201        }
202    }
203
204    /// Set the compression parameter for the merged result.
205    pub fn compression(mut self, compression: i64) -> Self {
206        self.compression = Some(compression);
207        self
208    }
209
210    /// Override the destination if it already exists.
211    pub fn override_dest(mut self) -> Self {
212        self.override_flag = true;
213        self
214    }
215}
216
217impl Command for TdigestMerge {
218    type Response = ();
219
220    fn to_frame(&self) -> Frame {
221        let mut args = vec![
222            bulk("TDIGEST.MERGE"),
223            bulk(&self.destination),
224            bulk(self.sources.len().to_string()),
225        ];
226        for src in &self.sources {
227            args.push(bulk(src));
228        }
229        if let Some(c) = self.compression {
230            args.push(bulk("COMPRESSION"));
231            args.push(bulk(c.to_string()));
232        }
233        if self.override_flag {
234            args.push(bulk("OVERRIDE"));
235        }
236        array(args)
237    }
238
239    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
240        match frame {
241            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
242            other => Err(RedisError::UnexpectedResponse {
243                expected: "OK",
244                actual: format!("{other:?}"),
245            }),
246        }
247    }
248
249    fn name(&self) -> &str {
250        "TDIGEST.MERGE"
251    }
252}
253
254/// TDIGEST.CDF key value \[value ...\]
255///
256/// Returns the cumulative distribution function value for each given value.
257#[derive(Clone)]
258pub struct TdigestCdf {
259    key: CommandArg,
260    values: Vec<f64>,
261}
262
263impl TdigestCdf {
264    /// Create a new [`TdigestCdf`] command.
265    pub fn new(key: impl Into<CommandArg>, values: impl IntoIterator<Item = f64>) -> Self {
266        Self {
267            key: key.into(),
268            values: values.into_iter().collect(),
269        }
270    }
271}
272
273impl Command for TdigestCdf {
274    type Response = Vec<f64>;
275
276    fn to_frame(&self) -> Frame {
277        let mut args = vec![bulk("TDIGEST.CDF"), bulk(&self.key)];
278        for v in &self.values {
279            args.push(bulk(v.to_string()));
280        }
281        array(args)
282    }
283
284    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
285        parse_f64_array(frame)
286    }
287
288    fn name(&self) -> &str {
289        "TDIGEST.CDF"
290    }
291
292    fn idempotent(&self) -> bool {
293        true
294    }
295}
296
297/// TDIGEST.QUANTILE key quantile \[quantile ...\]
298///
299/// Returns the estimated value at each given quantile.
300#[derive(Clone)]
301pub struct TdigestQuantile {
302    key: CommandArg,
303    quantiles: Vec<f64>,
304}
305
306impl TdigestQuantile {
307    /// Create a new [`TdigestQuantile`] command.
308    pub fn new(key: impl Into<CommandArg>, quantiles: impl IntoIterator<Item = f64>) -> Self {
309        Self {
310            key: key.into(),
311            quantiles: quantiles.into_iter().collect(),
312        }
313    }
314}
315
316impl Command for TdigestQuantile {
317    type Response = Vec<f64>;
318
319    fn to_frame(&self) -> Frame {
320        let mut args = vec![bulk("TDIGEST.QUANTILE"), bulk(&self.key)];
321        for q in &self.quantiles {
322            args.push(bulk(q.to_string()));
323        }
324        array(args)
325    }
326
327    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
328        parse_f64_array(frame)
329    }
330
331    fn name(&self) -> &str {
332        "TDIGEST.QUANTILE"
333    }
334
335    fn idempotent(&self) -> bool {
336        true
337    }
338}
339
340/// TDIGEST.MIN key
341///
342/// Returns the minimum value observed by the T-Digest.
343#[derive(Clone)]
344pub struct TdigestMin {
345    key: CommandArg,
346}
347
348impl TdigestMin {
349    /// Create a new [`TdigestMin`] command.
350    pub fn new(key: impl Into<CommandArg>) -> Self {
351        Self { key: key.into() }
352    }
353}
354
355impl Command for TdigestMin {
356    type Response = f64;
357
358    fn to_frame(&self) -> Frame {
359        array(vec![bulk("TDIGEST.MIN"), bulk(&self.key)])
360    }
361
362    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
363        parse_f64_from_frame(frame)
364    }
365
366    fn name(&self) -> &str {
367        "TDIGEST.MIN"
368    }
369
370    fn idempotent(&self) -> bool {
371        true
372    }
373}
374
375/// TDIGEST.MAX key
376///
377/// Returns the maximum value observed by the T-Digest.
378#[derive(Clone)]
379pub struct TdigestMax {
380    key: CommandArg,
381}
382
383impl TdigestMax {
384    /// Create a new [`TdigestMax`] command.
385    pub fn new(key: impl Into<CommandArg>) -> Self {
386        Self { key: key.into() }
387    }
388}
389
390impl Command for TdigestMax {
391    type Response = f64;
392
393    fn to_frame(&self) -> Frame {
394        array(vec![bulk("TDIGEST.MAX"), bulk(&self.key)])
395    }
396
397    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
398        parse_f64_from_frame(frame)
399    }
400
401    fn name(&self) -> &str {
402        "TDIGEST.MAX"
403    }
404
405    fn idempotent(&self) -> bool {
406        true
407    }
408}
409
410/// TDIGEST.INFO key
411///
412/// Returns information about the T-Digest at `key` as a raw Frame.
413#[derive(Clone)]
414pub struct TdigestInfo {
415    key: CommandArg,
416}
417
418impl TdigestInfo {
419    /// Create a new [`TdigestInfo`] command.
420    pub fn new(key: impl Into<CommandArg>) -> Self {
421        Self { key: key.into() }
422    }
423}
424
425impl Command for TdigestInfo {
426    type Response = Frame;
427
428    fn to_frame(&self) -> Frame {
429        array(vec![bulk("TDIGEST.INFO"), bulk(&self.key)])
430    }
431
432    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
433        Ok(frame)
434    }
435
436    fn name(&self) -> &str {
437        "TDIGEST.INFO"
438    }
439
440    fn idempotent(&self) -> bool {
441        true
442    }
443}
444
445/// TDIGEST.RESET key
446///
447/// Resets the T-Digest sketch at `key`, discarding all observed values.
448#[derive(Clone)]
449pub struct TdigestReset {
450    key: CommandArg,
451}
452
453impl TdigestReset {
454    /// Create a new [`TdigestReset`] command.
455    pub fn new(key: impl Into<CommandArg>) -> Self {
456        Self { key: key.into() }
457    }
458}
459
460impl Command for TdigestReset {
461    type Response = ();
462
463    fn to_frame(&self) -> Frame {
464        array(vec![bulk("TDIGEST.RESET"), bulk(&self.key)])
465    }
466
467    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
468        match frame {
469            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
470            other => Err(RedisError::UnexpectedResponse {
471                expected: "OK",
472                actual: format!("{other:?}"),
473            }),
474        }
475    }
476
477    fn name(&self) -> &str {
478        "TDIGEST.RESET"
479    }
480}
481
482/// TDIGEST.TRIMMED_MEAN key low_quantile high_quantile
483///
484/// Returns the trimmed mean between the given quantile bounds.
485#[derive(Clone)]
486pub struct TdigestTrimmedMean {
487    key: CommandArg,
488    low_quantile: f64,
489    high_quantile: f64,
490}
491
492impl TdigestTrimmedMean {
493    /// Create a new [`TdigestTrimmedMean`] command.
494    pub fn new(key: impl Into<CommandArg>, low_quantile: f64, high_quantile: f64) -> Self {
495        Self {
496            key: key.into(),
497            low_quantile,
498            high_quantile,
499        }
500    }
501}
502
503impl Command for TdigestTrimmedMean {
504    type Response = f64;
505
506    fn to_frame(&self) -> Frame {
507        array(vec![
508            bulk("TDIGEST.TRIMMED_MEAN"),
509            bulk(&self.key),
510            bulk(self.low_quantile.to_string()),
511            bulk(self.high_quantile.to_string()),
512        ])
513    }
514
515    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
516        parse_f64_from_frame(frame)
517    }
518
519    fn name(&self) -> &str {
520        "TDIGEST.TRIMMED_MEAN"
521    }
522}
523
524/// TDIGEST.RANK key value \[value ...\]
525///
526/// Returns the estimated rank of each given value.
527#[derive(Clone)]
528pub struct TdigestRank {
529    key: CommandArg,
530    values: Vec<f64>,
531}
532
533impl TdigestRank {
534    /// Create a new [`TdigestRank`] command.
535    pub fn new(key: impl Into<CommandArg>, values: impl IntoIterator<Item = f64>) -> Self {
536        Self {
537            key: key.into(),
538            values: values.into_iter().collect(),
539        }
540    }
541}
542
543impl Command for TdigestRank {
544    type Response = Vec<i64>;
545
546    fn to_frame(&self) -> Frame {
547        let mut args = vec![bulk("TDIGEST.RANK"), bulk(&self.key)];
548        for v in &self.values {
549            args.push(bulk(v.to_string()));
550        }
551        array(args)
552    }
553
554    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
555        parse_i64_array(frame)
556    }
557
558    fn name(&self) -> &str {
559        "TDIGEST.RANK"
560    }
561
562    fn idempotent(&self) -> bool {
563        true
564    }
565}
566
567/// TDIGEST.REVRANK key value \[value ...\]
568///
569/// Returns the estimated reverse rank of each given value.
570#[derive(Clone)]
571pub struct TdigestRevRank {
572    key: CommandArg,
573    values: Vec<f64>,
574}
575
576impl TdigestRevRank {
577    /// Create a new [`TdigestRevRank`] command.
578    pub fn new(key: impl Into<CommandArg>, values: impl IntoIterator<Item = f64>) -> Self {
579        Self {
580            key: key.into(),
581            values: values.into_iter().collect(),
582        }
583    }
584}
585
586impl Command for TdigestRevRank {
587    type Response = Vec<i64>;
588
589    fn to_frame(&self) -> Frame {
590        let mut args = vec![bulk("TDIGEST.REVRANK"), bulk(&self.key)];
591        for v in &self.values {
592            args.push(bulk(v.to_string()));
593        }
594        array(args)
595    }
596
597    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
598        parse_i64_array(frame)
599    }
600
601    fn name(&self) -> &str {
602        "TDIGEST.REVRANK"
603    }
604
605    fn idempotent(&self) -> bool {
606        true
607    }
608}
609
610/// TDIGEST.BYRANK key rank \[rank ...\]
611///
612/// Returns the estimated value at each given rank.
613#[derive(Clone)]
614pub struct TdigestByRank {
615    key: CommandArg,
616    ranks: Vec<i64>,
617}
618
619impl TdigestByRank {
620    /// Create a new [`TdigestByRank`] command.
621    pub fn new(key: impl Into<CommandArg>, ranks: impl IntoIterator<Item = i64>) -> Self {
622        Self {
623            key: key.into(),
624            ranks: ranks.into_iter().collect(),
625        }
626    }
627}
628
629impl Command for TdigestByRank {
630    type Response = Vec<f64>;
631
632    fn to_frame(&self) -> Frame {
633        let mut args = vec![bulk("TDIGEST.BYRANK"), bulk(&self.key)];
634        for r in &self.ranks {
635            args.push(bulk(r.to_string()));
636        }
637        array(args)
638    }
639
640    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
641        parse_f64_array(frame)
642    }
643
644    fn name(&self) -> &str {
645        "TDIGEST.BYRANK"
646    }
647
648    fn idempotent(&self) -> bool {
649        true
650    }
651}
652
653/// TDIGEST.BYREVRANK key rank \[rank ...\]
654///
655/// Returns the estimated value at each given reverse rank.
656#[derive(Clone)]
657pub struct TdigestByRevRank {
658    key: CommandArg,
659    ranks: Vec<i64>,
660}
661
662impl TdigestByRevRank {
663    /// Create a new [`TdigestByRevRank`] command.
664    pub fn new(key: impl Into<CommandArg>, ranks: impl IntoIterator<Item = i64>) -> Self {
665        Self {
666            key: key.into(),
667            ranks: ranks.into_iter().collect(),
668        }
669    }
670}
671
672impl Command for TdigestByRevRank {
673    type Response = Vec<f64>;
674
675    fn to_frame(&self) -> Frame {
676        let mut args = vec![bulk("TDIGEST.BYREVRANK"), bulk(&self.key)];
677        for r in &self.ranks {
678            args.push(bulk(r.to_string()));
679        }
680        array(args)
681    }
682
683    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
684        parse_f64_array(frame)
685    }
686
687    fn name(&self) -> &str {
688        "TDIGEST.BYREVRANK"
689    }
690
691    fn idempotent(&self) -> bool {
692        true
693    }
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699    use redis_tower_core::Command;
700
701    #[test]
702    fn idempotency_flags() {
703        // Read-only commands are safe to retry.
704        assert!(TdigestMin::new("k").idempotent());
705        // Mutating commands keep the default (false).
706        assert!(!TdigestAdd::new("k", [1.0]).idempotent());
707    }
708}