Skip to main content

redis_tower_commands/
diagnostics.rs

1//! Memory, latency, slow-log, and debugging commands.
2//!
3//! Use these commands for bounded operational inspection. Some commands are
4//! expensive, disabled, or privilege-restricted on managed Redis services;
5//! treat `DEBUG` operations and large diagnostic replies as deliberate operator
6//! actions rather than request-path instrumentation.
7//!
8//! ```
9//! use redis_tower_commands::MemoryUsage;
10//! use redis_tower_core::Command;
11//!
12//! assert_eq!(MemoryUsage::new("cache:key").name(), "MEMORY USAGE");
13//! ```
14//!
15//! See the [command cookbook] for safer continuous observability choices.
16//!
17//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#administration-and-diagnostics
18
19use crate::CommandArg;
20use bytes::Bytes;
21use redis_tower_core::{Command, Frame, RedisError};
22use redis_tower_protocol::helpers::{array, bulk};
23
24// ---------------------------------------------------------------------------
25// MEMORY subcommands
26// ---------------------------------------------------------------------------
27
28/// MEMORY USAGE key [SAMPLES count]
29///
30/// Returns the number of bytes that a key and its value require to be stored
31/// in RAM. Returns `None` if the key does not exist.
32#[derive(Clone)]
33pub struct MemoryUsage {
34    key: CommandArg,
35    samples: Option<u64>,
36}
37
38impl MemoryUsage {
39    /// Create a new [`MemoryUsage`] command.
40    pub fn new(key: impl Into<CommandArg>) -> Self {
41        Self {
42            key: key.into(),
43            samples: None,
44        }
45    }
46
47    /// Set the number of nested values to sample (default 5).
48    pub fn samples(mut self, count: u64) -> Self {
49        self.samples = Some(count);
50        self
51    }
52}
53
54impl Command for MemoryUsage {
55    type Response = Option<i64>;
56
57    fn to_frame(&self) -> Frame {
58        let mut args = vec![bulk("MEMORY"), bulk("USAGE"), bulk(&self.key)];
59        if let Some(samples) = self.samples {
60            args.push(bulk("SAMPLES"));
61            args.push(bulk(samples.to_string()));
62        }
63        array(args)
64    }
65
66    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
67        match frame {
68            Frame::Integer(n) => Ok(Some(n)),
69            Frame::Null => Ok(None),
70            Frame::BulkString(None) => Ok(None),
71            other => Err(RedisError::UnexpectedResponse {
72                expected: "integer or null",
73                actual: format!("{other:?}"),
74            }),
75        }
76    }
77
78    fn name(&self) -> &str {
79        "MEMORY USAGE"
80    }
81}
82
83/// MEMORY DOCTOR
84///
85/// Returns a diagnostic report about memory issues the server may have.
86#[derive(Clone)]
87pub struct MemoryDoctor;
88
89impl MemoryDoctor {
90    /// Create a new [`MemoryDoctor`] command.
91    pub fn new() -> Self {
92        Self
93    }
94}
95
96impl Default for MemoryDoctor {
97    fn default() -> Self {
98        Self::new()
99    }
100}
101
102impl Command for MemoryDoctor {
103    type Response = String;
104
105    fn to_frame(&self) -> Frame {
106        array(vec![bulk("MEMORY"), bulk("DOCTOR")])
107    }
108
109    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
110        match frame {
111            // RESP3 returns MEMORY DOCTOR as a verbatim string.
112            Frame::BulkString(Some(s)) | Frame::VerbatimString(_, s) => {
113                Ok(String::from_utf8_lossy(&s).into_owned())
114            }
115            other => Err(RedisError::UnexpectedResponse {
116                expected: "bulk or verbatim string",
117                actual: format!("{other:?}"),
118            }),
119        }
120    }
121
122    fn name(&self) -> &str {
123        "MEMORY DOCTOR"
124    }
125}
126
127/// MEMORY STATS
128///
129/// Returns detailed memory consumption statistics as a complex nested
130/// key-value response.
131#[derive(Clone)]
132pub struct MemoryStats;
133
134impl MemoryStats {
135    /// Create a new [`MemoryStats`] command.
136    pub fn new() -> Self {
137        Self
138    }
139}
140
141impl Default for MemoryStats {
142    fn default() -> Self {
143        Self::new()
144    }
145}
146
147impl Command for MemoryStats {
148    type Response = Frame;
149
150    fn to_frame(&self) -> Frame {
151        array(vec![bulk("MEMORY"), bulk("STATS")])
152    }
153
154    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
155        Ok(frame)
156    }
157
158    fn name(&self) -> &str {
159        "MEMORY STATS"
160    }
161}
162
163/// MEMORY PURGE
164///
165/// Asks the configured allocator to release memory that it can return to the
166/// operating system.
167#[derive(Debug, Clone)]
168pub struct MemoryPurge;
169
170impl MemoryPurge {
171    /// Create a `MEMORY PURGE` request.
172    pub fn new() -> Self {
173        Self
174    }
175}
176
177impl Default for MemoryPurge {
178    fn default() -> Self {
179        Self::new()
180    }
181}
182
183impl Command for MemoryPurge {
184    type Response = ();
185
186    fn to_frame(&self) -> Frame {
187        array(vec![bulk("MEMORY"), bulk("PURGE")])
188    }
189
190    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
191        match frame {
192            Frame::SimpleString(value) if value.eq_ignore_ascii_case(b"OK") => Ok(()),
193            other => Err(RedisError::UnexpectedResponse {
194                expected: "OK",
195                actual: format!("{other:?}"),
196            }),
197        }
198    }
199
200    fn name(&self) -> &str {
201        "MEMORY PURGE"
202    }
203
204    fn idempotent(&self) -> bool {
205        true
206    }
207}
208
209/// MEMORY MALLOC-STATS
210///
211/// Returns the allocator's implementation-specific statistics as raw bytes.
212#[derive(Debug, Clone)]
213pub struct MemoryMallocStats;
214
215impl MemoryMallocStats {
216    /// Create a `MEMORY MALLOC-STATS` request.
217    pub fn new() -> Self {
218        Self
219    }
220}
221
222impl Default for MemoryMallocStats {
223    fn default() -> Self {
224        Self::new()
225    }
226}
227
228impl Command for MemoryMallocStats {
229    type Response = Bytes;
230
231    fn to_frame(&self) -> Frame {
232        array(vec![bulk("MEMORY"), bulk("MALLOC-STATS")])
233    }
234
235    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
236        match frame {
237            Frame::BulkString(Some(value))
238            | Frame::SimpleString(value)
239            | Frame::VerbatimString(_, value) => Ok(value),
240            other => Err(RedisError::UnexpectedResponse {
241                expected: "bulk, simple, or verbatim string",
242                actual: format!("{other:?}"),
243            }),
244        }
245    }
246
247    fn name(&self) -> &str {
248        "MEMORY MALLOC-STATS"
249    }
250
251    fn idempotent(&self) -> bool {
252        true
253    }
254}
255
256// ---------------------------------------------------------------------------
257// SLOWLOG subcommands
258// ---------------------------------------------------------------------------
259
260/// SLOWLOG GET \[count\]
261///
262/// Returns entries from the slow log. Each entry is an array containing
263/// the log id, timestamp, execution time, command array, client info, etc.
264#[derive(Clone)]
265pub struct SlowlogGet {
266    count: Option<u64>,
267}
268
269impl SlowlogGet {
270    /// Return all slow log entries.
271    pub fn new() -> Self {
272        Self { count: None }
273    }
274
275    /// Return at most `count` slow log entries.
276    pub fn count(count: u64) -> Self {
277        Self { count: Some(count) }
278    }
279}
280
281impl Default for SlowlogGet {
282    fn default() -> Self {
283        Self::new()
284    }
285}
286
287impl Command for SlowlogGet {
288    type Response = Frame;
289
290    fn to_frame(&self) -> Frame {
291        let mut args = vec![bulk("SLOWLOG"), bulk("GET")];
292        if let Some(count) = self.count {
293            args.push(bulk(count.to_string()));
294        }
295        array(args)
296    }
297
298    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
299        Ok(frame)
300    }
301
302    fn name(&self) -> &str {
303        "SLOWLOG GET"
304    }
305}
306
307/// SLOWLOG LEN
308///
309/// Returns the number of entries in the slow log.
310#[derive(Clone)]
311pub struct SlowlogLen;
312
313impl SlowlogLen {
314    /// Create a new [`SlowlogLen`] command.
315    pub fn new() -> Self {
316        Self
317    }
318}
319
320impl Default for SlowlogLen {
321    fn default() -> Self {
322        Self::new()
323    }
324}
325
326impl Command for SlowlogLen {
327    type Response = i64;
328
329    fn to_frame(&self) -> Frame {
330        array(vec![bulk("SLOWLOG"), bulk("LEN")])
331    }
332
333    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
334        match frame {
335            Frame::Integer(n) => Ok(n),
336            other => Err(RedisError::UnexpectedResponse {
337                expected: "integer",
338                actual: format!("{other:?}"),
339            }),
340        }
341    }
342
343    fn name(&self) -> &str {
344        "SLOWLOG LEN"
345    }
346}
347
348/// SLOWLOG RESET
349///
350/// Clears all entries from the slow log.
351#[derive(Clone)]
352pub struct SlowlogReset;
353
354impl SlowlogReset {
355    /// Create a new [`SlowlogReset`] command.
356    pub fn new() -> Self {
357        Self
358    }
359}
360
361impl Default for SlowlogReset {
362    fn default() -> Self {
363        Self::new()
364    }
365}
366
367impl Command for SlowlogReset {
368    type Response = ();
369
370    fn to_frame(&self) -> Frame {
371        array(vec![bulk("SLOWLOG"), bulk("RESET")])
372    }
373
374    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
375        match frame {
376            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
377            other => Err(RedisError::UnexpectedResponse {
378                expected: "OK",
379                actual: format!("{other:?}"),
380            }),
381        }
382    }
383
384    fn name(&self) -> &str {
385        "SLOWLOG RESET"
386    }
387}
388
389// ---------------------------------------------------------------------------
390// LATENCY subcommands
391// ---------------------------------------------------------------------------
392
393/// LATENCY LATEST
394///
395/// Returns the latest latency samples for all monitored events. Each entry
396/// is an array of [event-name, timestamp, latest-latency-ms, max-latency-ms].
397#[derive(Clone)]
398pub struct LatencyLatest;
399
400impl LatencyLatest {
401    /// Create a new [`LatencyLatest`] command.
402    pub fn new() -> Self {
403        Self
404    }
405}
406
407impl Default for LatencyLatest {
408    fn default() -> Self {
409        Self::new()
410    }
411}
412
413impl Command for LatencyLatest {
414    type Response = Frame;
415
416    fn to_frame(&self) -> Frame {
417        array(vec![bulk("LATENCY"), bulk("LATEST")])
418    }
419
420    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
421        Ok(frame)
422    }
423
424    fn name(&self) -> &str {
425        "LATENCY LATEST"
426    }
427}
428
429/// LATENCY HISTORY event
430///
431/// Returns latency time-series data for the specified event. Each entry
432/// is an array of [timestamp, latency-ms].
433#[derive(Clone)]
434pub struct LatencyHistory {
435    event: String,
436}
437
438impl LatencyHistory {
439    /// Create a new [`LatencyHistory`] command.
440    pub fn new(event: impl Into<String>) -> Self {
441        Self {
442            event: event.into(),
443        }
444    }
445}
446
447impl Command for LatencyHistory {
448    type Response = Frame;
449
450    fn to_frame(&self) -> Frame {
451        array(vec![
452            bulk("LATENCY"),
453            bulk("HISTORY"),
454            bulk(self.event.as_str()),
455        ])
456    }
457
458    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
459        Ok(frame)
460    }
461
462    fn name(&self) -> &str {
463        "LATENCY HISTORY"
464    }
465}
466
467/// LATENCY RESET [event ...]
468///
469/// Resets latency data for the specified events, or all events if none given.
470/// Returns the number of events that were reset.
471#[derive(Clone)]
472pub struct LatencyReset {
473    events: Vec<String>,
474}
475
476impl LatencyReset {
477    /// Reset all latency events.
478    pub fn new() -> Self {
479        Self { events: Vec::new() }
480    }
481
482    /// Reset a specific latency event.
483    pub fn event(mut self, event: impl Into<String>) -> Self {
484        self.events.push(event.into());
485        self
486    }
487
488    /// Reset multiple latency events.
489    pub fn events(mut self, events: impl IntoIterator<Item = impl Into<String>>) -> Self {
490        self.events.extend(events.into_iter().map(Into::into));
491        self
492    }
493}
494
495impl Default for LatencyReset {
496    fn default() -> Self {
497        Self::new()
498    }
499}
500
501impl Command for LatencyReset {
502    type Response = i64;
503
504    fn to_frame(&self) -> Frame {
505        let mut args = vec![bulk("LATENCY"), bulk("RESET")];
506        for event in &self.events {
507            args.push(bulk(event.as_str()));
508        }
509        array(args)
510    }
511
512    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
513        match frame {
514            Frame::Integer(n) => Ok(n),
515            other => Err(RedisError::UnexpectedResponse {
516                expected: "integer",
517                actual: format!("{other:?}"),
518            }),
519        }
520    }
521
522    fn name(&self) -> &str {
523        "LATENCY RESET"
524    }
525}
526
527/// LATENCY GRAPH event
528///
529/// Returns a latency graph for the given event, rendered as ASCII art text.
530#[derive(Clone)]
531pub struct LatencyGraph {
532    event: String,
533}
534
535impl LatencyGraph {
536    /// Create a new [`LatencyGraph`] command.
537    pub fn new(event: impl Into<String>) -> Self {
538        Self {
539            event: event.into(),
540        }
541    }
542}
543
544impl Command for LatencyGraph {
545    type Response = String;
546
547    fn to_frame(&self) -> Frame {
548        array(vec![
549            bulk("LATENCY"),
550            bulk("GRAPH"),
551            bulk(self.event.as_str()),
552        ])
553    }
554
555    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
556        match frame {
557            // RESP3 may return the graph as a verbatim string.
558            Frame::BulkString(Some(s)) | Frame::VerbatimString(_, s) => {
559                Ok(String::from_utf8_lossy(&s).into_owned())
560            }
561            other => Err(RedisError::UnexpectedResponse {
562                expected: "bulk or verbatim string",
563                actual: format!("{other:?}"),
564            }),
565        }
566    }
567
568    fn name(&self) -> &str {
569        "LATENCY GRAPH"
570    }
571
572    fn idempotent(&self) -> bool {
573        true
574    }
575}
576
577/// LATENCY HISTOGRAM \[command-name \[command-name ...\]\]
578///
579/// Returns cumulative command-latency histograms. The nested response is kept
580/// as a raw frame because RESP2 uses alternating arrays while RESP3 uses maps.
581#[derive(Debug, Clone)]
582pub struct LatencyHistogram {
583    commands: Vec<Bytes>,
584}
585
586impl LatencyHistogram {
587    /// Request histograms for every command that has latency data.
588    pub fn new() -> Self {
589        Self {
590            commands: Vec::new(),
591        }
592    }
593
594    /// Add one binary-safe command name to the filter.
595    pub fn command(mut self, command: impl AsRef<[u8]>) -> Self {
596        self.commands.push(Bytes::copy_from_slice(command.as_ref()));
597        self
598    }
599
600    /// Add multiple binary-safe command names to the filter.
601    pub fn commands<C, I>(mut self, commands: I) -> Self
602    where
603        C: AsRef<[u8]>,
604        I: IntoIterator<Item = C>,
605    {
606        self.commands.extend(
607            commands
608                .into_iter()
609                .map(|command| Bytes::copy_from_slice(command.as_ref())),
610        );
611        self
612    }
613}
614
615impl Default for LatencyHistogram {
616    fn default() -> Self {
617        Self::new()
618    }
619}
620
621impl Command for LatencyHistogram {
622    type Response = Frame;
623
624    fn to_frame(&self) -> Frame {
625        let mut args = vec![bulk("LATENCY"), bulk("HISTOGRAM")];
626        args.extend(self.commands.iter().map(bulk));
627        array(args)
628    }
629
630    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
631        match frame {
632            frame @ (Frame::Array(Some(_)) | Frame::Map(_)) => Ok(frame),
633            other => Err(RedisError::UnexpectedResponse {
634                expected: "array or map",
635                actual: format!("{other:?}"),
636            }),
637        }
638    }
639
640    fn name(&self) -> &str {
641        "LATENCY HISTOGRAM"
642    }
643
644    fn idempotent(&self) -> bool {
645        true
646    }
647}
648
649/// LATENCY DOCTOR
650///
651/// Returns Redis's human-readable latency analysis report.
652#[derive(Debug, Clone)]
653pub struct LatencyDoctor;
654
655impl LatencyDoctor {
656    /// Create a `LATENCY DOCTOR` request.
657    pub fn new() -> Self {
658        Self
659    }
660}
661
662impl Default for LatencyDoctor {
663    fn default() -> Self {
664        Self::new()
665    }
666}
667
668impl Command for LatencyDoctor {
669    type Response = String;
670
671    fn to_frame(&self) -> Frame {
672        array(vec![bulk("LATENCY"), bulk("DOCTOR")])
673    }
674
675    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
676        match frame {
677            Frame::BulkString(Some(value))
678            | Frame::SimpleString(value)
679            | Frame::VerbatimString(_, value) => Ok(String::from_utf8_lossy(&value).into_owned()),
680            other => Err(RedisError::UnexpectedResponse {
681                expected: "bulk, simple, or verbatim string",
682                actual: format!("{other:?}"),
683            }),
684        }
685    }
686
687    fn name(&self) -> &str {
688        "LATENCY DOCTOR"
689    }
690
691    fn idempotent(&self) -> bool {
692        true
693    }
694}
695
696// ---------------------------------------------------------------------------
697// HELP subcommands
698// ---------------------------------------------------------------------------
699
700/// MEMORY HELP
701///
702/// Returns helpful text describing the MEMORY subcommands.
703#[derive(Clone)]
704pub struct MemoryHelp;
705
706impl MemoryHelp {
707    /// Create a new [`MemoryHelp`] command.
708    pub fn new() -> Self {
709        Self
710    }
711}
712
713impl Default for MemoryHelp {
714    fn default() -> Self {
715        Self::new()
716    }
717}
718
719impl Command for MemoryHelp {
720    type Response = Vec<Bytes>;
721
722    fn to_frame(&self) -> Frame {
723        array(vec![bulk("MEMORY"), bulk("HELP")])
724    }
725
726    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
727        crate::help::parse_help_lines(frame)
728    }
729
730    fn name(&self) -> &str {
731        "MEMORY HELP"
732    }
733
734    fn idempotent(&self) -> bool {
735        true
736    }
737}
738
739/// SLOWLOG HELP
740///
741/// Returns helpful text describing the SLOWLOG subcommands.
742#[derive(Clone)]
743pub struct SlowlogHelp;
744
745impl SlowlogHelp {
746    /// Create a new [`SlowlogHelp`] command.
747    pub fn new() -> Self {
748        Self
749    }
750}
751
752impl Default for SlowlogHelp {
753    fn default() -> Self {
754        Self::new()
755    }
756}
757
758impl Command for SlowlogHelp {
759    type Response = Vec<Bytes>;
760
761    fn to_frame(&self) -> Frame {
762        array(vec![bulk("SLOWLOG"), bulk("HELP")])
763    }
764
765    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
766        crate::help::parse_help_lines(frame)
767    }
768
769    fn name(&self) -> &str {
770        "SLOWLOG HELP"
771    }
772
773    fn idempotent(&self) -> bool {
774        true
775    }
776}
777
778/// LATENCY HELP
779///
780/// Returns helpful text describing the LATENCY subcommands.
781#[derive(Clone)]
782pub struct LatencyHelp;
783
784impl LatencyHelp {
785    /// Create a new [`LatencyHelp`] command.
786    pub fn new() -> Self {
787        Self
788    }
789}
790
791impl Default for LatencyHelp {
792    fn default() -> Self {
793        Self::new()
794    }
795}
796
797impl Command for LatencyHelp {
798    type Response = Vec<Bytes>;
799
800    fn to_frame(&self) -> Frame {
801        array(vec![bulk("LATENCY"), bulk("HELP")])
802    }
803
804    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
805        crate::help::parse_help_lines(frame)
806    }
807
808    fn name(&self) -> &str {
809        "LATENCY HELP"
810    }
811
812    fn idempotent(&self) -> bool {
813        true
814    }
815}
816
817/// DEBUG HELP
818///
819/// Returns helpful text describing the DEBUG subcommands.
820#[derive(Clone)]
821pub struct DebugHelp;
822
823impl DebugHelp {
824    /// Create a new [`DebugHelp`] command.
825    pub fn new() -> Self {
826        Self
827    }
828}
829
830impl Default for DebugHelp {
831    fn default() -> Self {
832        Self::new()
833    }
834}
835
836impl Command for DebugHelp {
837    type Response = Vec<Bytes>;
838
839    fn to_frame(&self) -> Frame {
840        array(vec![bulk("DEBUG"), bulk("HELP")])
841    }
842
843    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
844        crate::help::parse_help_lines(frame)
845    }
846
847    fn name(&self) -> &str {
848        "DEBUG HELP"
849    }
850
851    fn idempotent(&self) -> bool {
852        true
853    }
854}
855
856#[cfg(test)]
857mod tests {
858    use super::*;
859    use bytes::Bytes;
860
861    #[test]
862    fn memory_doctor_parse_bulk_string() {
863        let cmd = MemoryDoctor::new();
864        let frame = Frame::BulkString(Some(Bytes::from("Sam, I detected a few issues")));
865        let out = cmd.parse_response(frame).unwrap();
866        assert!(out.contains("issues"));
867    }
868
869    #[test]
870    fn memory_doctor_parse_verbatim_string_resp3() {
871        // Under RESP3 MEMORY DOCTOR comes back as a verbatim string.
872        let cmd = MemoryDoctor::new();
873        let frame = Frame::VerbatimString(
874            Bytes::from("txt"),
875            Bytes::from("Sam, I detected a few issues"),
876        );
877        let out = cmd.parse_response(frame).unwrap();
878        assert!(out.contains("issues"));
879    }
880
881    #[test]
882    fn memory_purge_to_frame_and_parse_ok() {
883        let cmd = MemoryPurge::new();
884        assert_eq!(cmd.to_frame(), array(vec![bulk("MEMORY"), bulk("PURGE")]));
885        assert_eq!(cmd.name(), "MEMORY PURGE");
886        assert!(cmd.idempotent());
887        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
888            .unwrap();
889        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
890    }
891
892    #[test]
893    fn memory_malloc_stats_accepts_resp2_and_resp3_text() {
894        let cmd = MemoryMallocStats::new();
895        assert_eq!(
896            cmd.to_frame(),
897            array(vec![bulk("MEMORY"), bulk("MALLOC-STATS")])
898        );
899        assert_eq!(cmd.name(), "MEMORY MALLOC-STATS");
900        assert!(cmd.idempotent());
901        assert_eq!(
902            cmd.parse_response(Frame::BulkString(Some(Bytes::from("allocator stats"))))
903                .unwrap(),
904            Bytes::from("allocator stats")
905        );
906        assert_eq!(
907            cmd.parse_response(Frame::VerbatimString(
908                Bytes::from("txt"),
909                Bytes::from("resp3 stats")
910            ))
911            .unwrap(),
912            Bytes::from("resp3 stats")
913        );
914        assert!(cmd.parse_response(Frame::Null).is_err());
915    }
916
917    #[test]
918    fn latency_graph_to_frame() {
919        let cmd = LatencyGraph::new("command");
920        assert_eq!(
921            cmd.to_frame(),
922            array(vec![bulk("LATENCY"), bulk("GRAPH"), bulk("command")])
923        );
924        assert!(cmd.idempotent());
925    }
926
927    #[test]
928    fn latency_graph_parse_string() {
929        let cmd = LatencyGraph::new("command");
930        let out = cmd
931            .parse_response(Frame::BulkString(Some(Bytes::from("command - high . low"))))
932            .unwrap();
933        assert!(out.contains("command"));
934    }
935
936    #[test]
937    fn latency_histogram_serializes_binary_safe_filters() {
938        let cmd = LatencyHistogram::new()
939            .command(b"GET")
940            .commands([b"SET".as_slice(), b"custom\0command".as_slice()]);
941        assert_eq!(
942            cmd.to_frame(),
943            array(vec![
944                bulk("LATENCY"),
945                bulk("HISTOGRAM"),
946                bulk("GET"),
947                bulk("SET"),
948                bulk(b"custom\0command"),
949            ])
950        );
951        assert_eq!(cmd.name(), "LATENCY HISTOGRAM");
952        assert!(cmd.idempotent());
953    }
954
955    #[test]
956    fn latency_histogram_preserves_resp2_and_resp3_shapes() {
957        let cmd = LatencyHistogram::new();
958        let resp2 = array(vec![bulk("get"), array(vec![])]);
959        assert_eq!(cmd.parse_response(resp2.clone()).unwrap(), resp2);
960        let resp3 = Frame::Map(vec![(bulk("get"), Frame::Map(vec![]))]);
961        assert_eq!(cmd.parse_response(resp3.clone()).unwrap(), resp3);
962        assert!(cmd.parse_response(Frame::Null).is_err());
963    }
964
965    #[test]
966    fn latency_doctor_accepts_resp2_and_resp3_text() {
967        let cmd = LatencyDoctor::new();
968        assert_eq!(cmd.to_frame(), array(vec![bulk("LATENCY"), bulk("DOCTOR")]));
969        assert_eq!(cmd.name(), "LATENCY DOCTOR");
970        assert!(cmd.idempotent());
971        assert_eq!(
972            cmd.parse_response(Frame::BulkString(Some(Bytes::from("diagnosis"))))
973                .unwrap(),
974            "diagnosis"
975        );
976        assert_eq!(
977            cmd.parse_response(Frame::VerbatimString(
978                Bytes::from("txt"),
979                Bytes::from("healthy")
980            ))
981            .unwrap(),
982            "healthy"
983        );
984        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
985    }
986
987    #[test]
988    fn help_subcommands_to_frame() {
989        assert_eq!(
990            MemoryHelp::new().to_frame(),
991            array(vec![bulk("MEMORY"), bulk("HELP")])
992        );
993        assert_eq!(
994            SlowlogHelp::new().to_frame(),
995            array(vec![bulk("SLOWLOG"), bulk("HELP")])
996        );
997        assert_eq!(
998            LatencyHelp::new().to_frame(),
999            array(vec![bulk("LATENCY"), bulk("HELP")])
1000        );
1001        assert_eq!(
1002            DebugHelp::new().to_frame(),
1003            array(vec![bulk("DEBUG"), bulk("HELP")])
1004        );
1005        assert!(MemoryHelp::new().idempotent());
1006    }
1007
1008    #[test]
1009    fn memory_help_parse_lines() {
1010        let cmd = MemoryHelp::new();
1011        let reply = array(vec![bulk("MEMORY <subcommand>"), bulk("USAGE <key>")]);
1012        let lines = cmd.parse_response(reply).unwrap();
1013        assert_eq!(lines.len(), 2);
1014        assert_eq!(&lines[1][..], b"USAGE <key>");
1015    }
1016}