Skip to main content

redis_tower_commands/
server.rs

1//! Connection state, server administration, and client-management commands.
2//!
3//! Stateless inspection such as [`Ping`] and [`Info`] can use ordinary
4//! clients. Commands that alter connection state (`SELECT`, tracking, reply
5//! mode) or the server itself require deliberate ownership and permissions;
6//! prefer the higher-level connection constructors for AUTH, protocol, and
7//! database setup so reconnects replay that state.
8//!
9//! ```
10//! use redis_tower_commands::{Info, Ping};
11//! use redis_tower_core::Command;
12//!
13//! assert_eq!(Ping::new().name(), "PING");
14//! assert_eq!(Info::new().name(), "INFO");
15//! ```
16//!
17//! See the [command cookbook] for stateful-session and administration rules.
18//!
19//! [command cookbook]: https://github.com/joshrotenberg/redis-tower/blob/main/docs/COMMAND-COOKBOOK.md#administration-and-diagnostics
20
21use crate::CommandArg;
22use bytes::Bytes;
23use redis_tower_core::{Command, Frame, RedisError};
24use redis_tower_protocol::helpers::{array, bulk};
25
26fn parse_ok_response(frame: Frame) -> Result<(), RedisError> {
27    match frame {
28        Frame::SimpleString(value) if value.eq_ignore_ascii_case(b"OK") => Ok(()),
29        other => Err(RedisError::UnexpectedResponse {
30            expected: "OK",
31            actual: format!("{other:?}"),
32        }),
33    }
34}
35
36/// PING \[message\]
37///
38/// Returns `PONG`, or echoes the message if provided, as exact bytes.
39#[derive(Clone)]
40pub struct Ping {
41    message: Option<CommandArg>,
42}
43
44impl Ping {
45    /// Create a new [`Ping`] command.
46    pub fn new() -> Self {
47        Self { message: None }
48    }
49
50    /// Create the [`Ping`] command using the `with_message` form.
51    pub fn with_message(message: impl Into<CommandArg>) -> Self {
52        Self {
53            message: Some(message.into()),
54        }
55    }
56}
57
58impl Default for Ping {
59    fn default() -> Self {
60        Self::new()
61    }
62}
63
64impl Command for Ping {
65    type Response = Bytes;
66
67    fn to_frame(&self) -> Frame {
68        let mut args = vec![bulk("PING")];
69        if let Some(ref msg) = self.message {
70            args.push(bulk(msg));
71        }
72        array(args)
73    }
74
75    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
76        match frame {
77            Frame::SimpleString(s) | Frame::BulkString(Some(s)) => Ok(s),
78            other => Err(RedisError::UnexpectedResponse {
79                expected: "simple string or bulk string",
80                actual: format!("{other:?}"),
81            }),
82        }
83    }
84
85    fn name(&self) -> &str {
86        "PING"
87    }
88}
89
90/// MONITOR
91///
92/// Switches a connection into Redis's continuous command-monitoring mode.
93/// This command never returns the connection to normal request/response use:
94/// execute it only on a fresh, dedicated [`RedisConnection`](redis_tower_core::RedisConnection).
95/// Applications using the `redis-tower` facade should prefer its
96/// `MonitorStream`, which owns the dedicated connection and decodes events.
97/// Executing `Monitor` through a shared or multiplexed client commandeers that
98/// transport and will stall or corrupt unrelated command traffic.
99#[derive(Debug, Clone)]
100pub struct Monitor;
101
102impl Monitor {
103    /// Create a `MONITOR` request for a fresh dedicated connection.
104    pub fn new() -> Self {
105        Self
106    }
107}
108
109impl Default for Monitor {
110    fn default() -> Self {
111        Self::new()
112    }
113}
114
115impl Command for Monitor {
116    type Response = ();
117
118    fn to_frame(&self) -> Frame {
119        array(vec![bulk("MONITOR")])
120    }
121
122    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
123        parse_ok_response(frame)
124    }
125
126    fn name(&self) -> &str {
127        "MONITOR"
128    }
129
130    fn is_blocking(&self) -> bool {
131        true
132    }
133}
134
135/// FLUSHDB [ASYNC|SYNC]
136///
137/// Delete all keys in the current database.
138#[derive(Clone)]
139pub struct FlushDb {
140    mode: Option<FlushMode>,
141}
142
143#[derive(Clone)]
144/// Execution mode for this Redis command.
145pub enum FlushMode {
146    /// Select the `Async` mode.
147    Async,
148    /// Select the `Sync` mode.
149    Sync,
150}
151
152impl FlushDb {
153    /// Create a new [`FlushDb`] command.
154    pub fn new() -> Self {
155        Self { mode: None }
156    }
157
158    /// Configure the `async_mode` option.
159    pub fn async_mode(mut self) -> Self {
160        self.mode = Some(FlushMode::Async);
161        self
162    }
163
164    /// Configure the `sync_mode` option.
165    pub fn sync_mode(mut self) -> Self {
166        self.mode = Some(FlushMode::Sync);
167        self
168    }
169}
170
171impl Default for FlushDb {
172    fn default() -> Self {
173        Self::new()
174    }
175}
176
177impl Command for FlushDb {
178    type Response = ();
179
180    fn to_frame(&self) -> Frame {
181        let mut args = vec![bulk("FLUSHDB")];
182        match &self.mode {
183            Some(FlushMode::Async) => args.push(bulk("ASYNC")),
184            Some(FlushMode::Sync) => args.push(bulk("SYNC")),
185            None => {}
186        }
187        array(args)
188    }
189
190    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
191        match frame {
192            Frame::SimpleString(s) if &s[..] == 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        "FLUSHDB"
202    }
203}
204
205/// DBSIZE
206///
207/// Returns the number of keys in the current database.
208#[derive(Clone)]
209pub struct DbSize;
210
211impl DbSize {
212    /// Create a new [`DbSize`] command.
213    pub fn new() -> Self {
214        Self
215    }
216}
217
218impl Default for DbSize {
219    fn default() -> Self {
220        Self::new()
221    }
222}
223
224impl Command for DbSize {
225    type Response = i64;
226
227    fn to_frame(&self) -> Frame {
228        array(vec![bulk("DBSIZE")])
229    }
230
231    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
232        match frame {
233            Frame::Integer(n) => Ok(n),
234            other => Err(RedisError::UnexpectedResponse {
235                expected: "integer",
236                actual: format!("{other:?}"),
237            }),
238        }
239    }
240
241    fn name(&self) -> &str {
242        "DBSIZE"
243    }
244}
245
246/// SELECT index
247///
248/// Select the Redis database for the current connection.
249#[derive(Clone)]
250pub struct Select {
251    db: u16,
252}
253
254impl Select {
255    /// Create a new [`Select`] command.
256    pub fn new(db: u16) -> Self {
257        Self { db }
258    }
259}
260
261impl Command for Select {
262    type Response = ();
263
264    fn to_frame(&self) -> Frame {
265        array(vec![bulk("SELECT"), bulk(self.db.to_string())])
266    }
267
268    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
269        match frame {
270            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
271            other => Err(RedisError::UnexpectedResponse {
272                expected: "OK",
273                actual: format!("{other:?}"),
274            }),
275        }
276    }
277
278    fn name(&self) -> &str {
279        "SELECT"
280    }
281}
282
283/// AUTH \[username\] password
284///
285/// Authenticate to the server. With Redis 6+ ACLs, pass both username
286/// and password. For older versions, only pass the password.
287#[derive(Clone)]
288pub struct Auth {
289    username: Option<String>,
290    password: CommandArg,
291}
292
293impl Auth {
294    /// Authenticate with password only (pre-Redis 6).
295    pub fn password(password: impl Into<CommandArg>) -> Self {
296        Self {
297            username: None,
298            password: password.into(),
299        }
300    }
301
302    /// Authenticate with username and password (Redis 6+ ACL).
303    pub fn credentials(username: impl Into<String>, password: impl Into<CommandArg>) -> Self {
304        Self {
305            username: Some(username.into()),
306            password: password.into(),
307        }
308    }
309}
310
311impl Command for Auth {
312    type Response = ();
313
314    fn to_frame(&self) -> Frame {
315        let mut args = vec![bulk("AUTH")];
316        if let Some(ref user) = self.username {
317            args.push(bulk(user.as_str()));
318        }
319        args.push(bulk(&self.password));
320        array(args)
321    }
322
323    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
324        match frame {
325            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
326            other => Err(RedisError::UnexpectedResponse {
327                expected: "OK",
328                actual: format!("{other:?}"),
329            }),
330        }
331    }
332
333    fn name(&self) -> &str {
334        "AUTH"
335    }
336}
337
338/// CLIENT TRACKING ON|OFF \[REDIRECT client-id\] \[PREFIX prefix\] \[BCAST\] \[OPTIN\] \[OPTOUT\] \[NOLOOP\]
339///
340/// Enable or disable server-assisted client-side caching.
341#[derive(Clone)]
342pub struct ClientTracking {
343    enabled: bool,
344    redirect: Option<i64>,
345    bcast: bool,
346    prefixes: Vec<Bytes>,
347    optin: bool,
348    optout: bool,
349    noloop: bool,
350}
351
352impl ClientTracking {
353    /// Enable client tracking.
354    pub fn on() -> Self {
355        Self {
356            enabled: true,
357            redirect: None,
358            bcast: false,
359            prefixes: Vec::new(),
360            optin: false,
361            optout: false,
362            noloop: false,
363        }
364    }
365
366    /// Disable client tracking.
367    pub fn off() -> Self {
368        Self {
369            enabled: false,
370            redirect: None,
371            bcast: false,
372            prefixes: Vec::new(),
373            optin: false,
374            optout: false,
375            noloop: false,
376        }
377    }
378
379    /// Redirect invalidation messages to another connection's client ID.
380    ///
381    /// The ID can be obtained with [`ClientId`]. Redirecting is useful when a
382    /// dedicated RESP3 connection owns the invalidation push stream while a
383    /// separate connection executes data commands.
384    pub fn redirect(mut self, client_id: i64) -> Self {
385        self.redirect = Some(client_id);
386        self
387    }
388
389    /// Enable broadcasting mode (invalidate all keys matching prefixes).
390    pub fn bcast(mut self) -> Self {
391        self.bcast = true;
392        self.optin = false;
393        self.optout = false;
394        self
395    }
396
397    /// Add a binary-safe key prefix to track and enable BCAST mode.
398    pub fn prefix(mut self, prefix: impl AsRef<[u8]>) -> Self {
399        self.bcast = true;
400        self.optin = false;
401        self.optout = false;
402        self.prefixes.push(Bytes::copy_from_slice(prefix.as_ref()));
403        self
404    }
405
406    /// Enable opt-in mode (only track keys after CLIENT CACHING YES).
407    pub fn optin(mut self) -> Self {
408        self.bcast = false;
409        self.prefixes.clear();
410        self.optin = true;
411        self.optout = false;
412        self
413    }
414
415    /// Enable opt-out mode (track all keys, skip after CLIENT CACHING NO).
416    pub fn optout(mut self) -> Self {
417        self.bcast = false;
418        self.prefixes.clear();
419        self.optin = false;
420        self.optout = true;
421        self
422    }
423
424    /// Suppress invalidations caused by writes on the tracked connection.
425    ///
426    /// Cached clients must pair this with synchronous local write invalidation
427    /// so their own writes cannot leave stale entries behind.
428    pub fn noloop(mut self) -> Self {
429        self.noloop = true;
430        self
431    }
432}
433
434impl Command for ClientTracking {
435    type Response = ();
436
437    fn to_frame(&self) -> Frame {
438        let mut args = vec![
439            bulk("CLIENT"),
440            bulk("TRACKING"),
441            bulk(if self.enabled { "ON" } else { "OFF" }),
442        ];
443        // Redis accepts no options with OFF. Omitting any options that were
444        // added to an OFF builder keeps the serialized command valid.
445        if self.enabled {
446            if let Some(client_id) = self.redirect {
447                args.push(bulk("REDIRECT"));
448                args.push(bulk(client_id.to_string()));
449            }
450            if self.bcast {
451                args.push(bulk("BCAST"));
452            }
453            for prefix in &self.prefixes {
454                args.push(bulk("PREFIX"));
455                args.push(bulk(prefix));
456            }
457            if self.optin {
458                args.push(bulk("OPTIN"));
459            }
460            if self.optout {
461                args.push(bulk("OPTOUT"));
462            }
463            if self.noloop {
464                args.push(bulk("NOLOOP"));
465            }
466        }
467        array(args)
468    }
469
470    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
471        match frame {
472            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
473            other => Err(RedisError::UnexpectedResponse {
474                expected: "OK",
475                actual: format!("{other:?}"),
476            }),
477        }
478    }
479
480    fn name(&self) -> &str {
481        "CLIENT TRACKING"
482    }
483}
484
485/// INFO \[section ...\]
486///
487/// Returns information and statistics about the server. An optional section
488/// filter can be provided to limit the output (e.g. "server", "memory",
489/// "replication"). Returns the raw bulk string; callers can parse the
490/// key-value pairs from the line-oriented format.
491#[derive(Clone)]
492pub struct Info {
493    sections: Vec<String>,
494}
495
496impl Info {
497    /// Request all info sections.
498    pub fn new() -> Self {
499        Self {
500            sections: Vec::new(),
501        }
502    }
503
504    /// Request a specific section (e.g. "server", "memory", "replication").
505    pub fn section(mut self, section: impl Into<String>) -> Self {
506        self.sections.push(section.into());
507        self
508    }
509}
510
511impl Default for Info {
512    fn default() -> Self {
513        Self::new()
514    }
515}
516
517impl Command for Info {
518    type Response = String;
519
520    fn to_frame(&self) -> Frame {
521        let mut args = vec![bulk("INFO")];
522        for s in &self.sections {
523            args.push(bulk(s.as_str()));
524        }
525        array(args)
526    }
527
528    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
529        match frame {
530            // RESP3 returns INFO as a verbatim string; RESP2 as a bulk string.
531            Frame::BulkString(Some(s)) | Frame::VerbatimString(_, s) => {
532                Ok(String::from_utf8_lossy(&s).into_owned())
533            }
534            other => Err(RedisError::UnexpectedResponse {
535                expected: "bulk or verbatim string",
536                actual: format!("{other:?}"),
537            }),
538        }
539    }
540
541    fn name(&self) -> &str {
542        "INFO"
543    }
544}
545
546/// TIME
547///
548/// Returns the current server time as a two-element array:
549/// unix timestamp in seconds and microseconds.
550#[derive(Clone)]
551pub struct Time;
552
553impl Time {
554    /// Create a new [`Time`] command.
555    pub fn new() -> Self {
556        Self
557    }
558}
559
560impl Default for Time {
561    fn default() -> Self {
562        Self::new()
563    }
564}
565
566impl Command for Time {
567    /// (unix_seconds, microseconds)
568    type Response = (i64, i64);
569
570    fn to_frame(&self) -> Frame {
571        array(vec![bulk("TIME")])
572    }
573
574    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
575        match frame {
576            Frame::Array(Some(frames)) if frames.len() == 2 => {
577                let secs = match &frames[0] {
578                    Frame::BulkString(Some(s)) => String::from_utf8_lossy(s)
579                        .parse::<i64>()
580                        .map_err(|_| RedisError::UnexpectedResponse {
581                            expected: "integer string",
582                            actual: format!("{:?}", frames[0]),
583                        })?,
584                    other => {
585                        return Err(RedisError::UnexpectedResponse {
586                            expected: "bulk string",
587                            actual: format!("{other:?}"),
588                        });
589                    }
590                };
591                let micros = match &frames[1] {
592                    Frame::BulkString(Some(s)) => String::from_utf8_lossy(s)
593                        .parse::<i64>()
594                        .map_err(|_| RedisError::UnexpectedResponse {
595                            expected: "integer string",
596                            actual: format!("{:?}", frames[1]),
597                        })?,
598                    other => {
599                        return Err(RedisError::UnexpectedResponse {
600                            expected: "bulk string",
601                            actual: format!("{other:?}"),
602                        });
603                    }
604                };
605                Ok((secs, micros))
606            }
607            other => Err(RedisError::UnexpectedResponse {
608                expected: "array of two bulk strings",
609                actual: format!("{other:?}"),
610            }),
611        }
612    }
613
614    fn name(&self) -> &str {
615        "TIME"
616    }
617}
618
619/// COMMAND
620///
621/// Returns detailed metadata for every command known to the server. The
622/// response is preserved as a raw frame because its deeply nested shape and
623/// aggregate types differ between RESP2 and RESP3.
624#[derive(Debug, Clone)]
625pub struct CommandOverview;
626
627impl CommandOverview {
628    /// Create a root `COMMAND` request.
629    pub fn new() -> Self {
630        Self
631    }
632}
633
634impl Default for CommandOverview {
635    fn default() -> Self {
636        Self::new()
637    }
638}
639
640impl Command for CommandOverview {
641    type Response = Frame;
642
643    fn to_frame(&self) -> Frame {
644        array(vec![bulk("COMMAND")])
645    }
646
647    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
648        match frame {
649            frame @ (Frame::Array(Some(_)) | Frame::Map(_)) => Ok(frame),
650            other => Err(RedisError::UnexpectedResponse {
651                expected: "array or map",
652                actual: format!("{other:?}"),
653            }),
654        }
655    }
656
657    fn name(&self) -> &str {
658        "COMMAND"
659    }
660
661    fn idempotent(&self) -> bool {
662        true
663    }
664}
665
666/// COMMAND COUNT
667///
668/// Returns the total number of commands supported by the server.
669#[derive(Clone)]
670pub struct CommandCount;
671
672impl CommandCount {
673    /// Create a new [`CommandCount`] command.
674    pub fn new() -> Self {
675        Self
676    }
677}
678
679impl Default for CommandCount {
680    fn default() -> Self {
681        Self::new()
682    }
683}
684
685impl Command for CommandCount {
686    type Response = i64;
687
688    fn to_frame(&self) -> Frame {
689        array(vec![bulk("COMMAND"), bulk("COUNT")])
690    }
691
692    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
693        match frame {
694            Frame::Integer(n) => Ok(n),
695            other => Err(RedisError::UnexpectedResponse {
696                expected: "integer",
697                actual: format!("{other:?}"),
698            }),
699        }
700    }
701
702    fn name(&self) -> &str {
703        "COMMAND COUNT"
704    }
705}
706
707/// COMMAND DOCS \[command-name ...\]
708///
709/// Returns documentary information about one or more commands.
710/// Each command's documentation is returned as a nested array of
711/// key-value pairs.
712#[derive(Clone)]
713pub struct CommandDocs {
714    commands: Vec<String>,
715}
716
717impl CommandDocs {
718    /// Request docs for all commands.
719    pub fn new() -> Self {
720        Self {
721            commands: Vec::new(),
722        }
723    }
724
725    /// Request docs for a specific command.
726    pub fn command(mut self, name: impl Into<String>) -> Self {
727        self.commands.push(name.into());
728        self
729    }
730}
731
732impl Default for CommandDocs {
733    fn default() -> Self {
734        Self::new()
735    }
736}
737
738impl Command for CommandDocs {
739    /// Raw frames -- the structure is deeply nested and command-specific.
740    type Response = Vec<Frame>;
741
742    fn to_frame(&self) -> Frame {
743        let mut args = vec![bulk("COMMAND"), bulk("DOCS")];
744        for c in &self.commands {
745            args.push(bulk(c.as_str()));
746        }
747        array(args)
748    }
749
750    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
751        match frame {
752            Frame::Array(Some(frames)) => Ok(frames),
753            Frame::Array(None) => Ok(Vec::new()),
754            // RESP3 returns the docs as a map; flatten it to the RESP2
755            // key/value array shape so callers see one stable layout.
756            Frame::Map(pairs) => {
757                let mut out = Vec::with_capacity(pairs.len() * 2);
758                for (k, v) in pairs {
759                    out.push(k);
760                    out.push(v);
761                }
762                Ok(out)
763            }
764            other => Err(RedisError::UnexpectedResponse {
765                expected: "array or map",
766                actual: format!("{other:?}"),
767            }),
768        }
769    }
770
771    fn name(&self) -> &str {
772        "COMMAND DOCS"
773    }
774}
775
776/// COMMAND LIST \[FILTERBY MODULE module | ACLCAT category | PATTERN pattern\]
777///
778/// Returns a list of all command names supported by the server.
779#[derive(Clone)]
780pub struct CommandList {
781    filter: Option<CommandListFilter>,
782}
783
784/// Filter for the COMMAND LIST command.
785#[derive(Clone)]
786pub enum CommandListFilter {
787    /// Filter by module name.
788    Module(String),
789    /// Filter by ACL category.
790    AclCat(String),
791    /// Filter by glob-style pattern.
792    Pattern(String),
793}
794
795impl CommandList {
796    /// List all commands without filtering.
797    pub fn new() -> Self {
798        Self { filter: None }
799    }
800
801    /// Filter by module name.
802    pub fn module(name: impl Into<String>) -> Self {
803        Self {
804            filter: Some(CommandListFilter::Module(name.into())),
805        }
806    }
807
808    /// Filter by ACL category.
809    pub fn aclcat(category: impl Into<String>) -> Self {
810        Self {
811            filter: Some(CommandListFilter::AclCat(category.into())),
812        }
813    }
814
815    /// Filter by glob-style pattern.
816    pub fn pattern(pattern: impl Into<String>) -> Self {
817        Self {
818            filter: Some(CommandListFilter::Pattern(pattern.into())),
819        }
820    }
821}
822
823impl Default for CommandList {
824    fn default() -> Self {
825        Self::new()
826    }
827}
828
829impl Command for CommandList {
830    type Response = Vec<String>;
831
832    fn to_frame(&self) -> Frame {
833        let mut args = vec![bulk("COMMAND"), bulk("LIST")];
834        if let Some(ref filter) = self.filter {
835            args.push(bulk("FILTERBY"));
836            match filter {
837                CommandListFilter::Module(m) => {
838                    args.push(bulk("MODULE"));
839                    args.push(bulk(m.as_str()));
840                }
841                CommandListFilter::AclCat(c) => {
842                    args.push(bulk("ACLCAT"));
843                    args.push(bulk(c.as_str()));
844                }
845                CommandListFilter::Pattern(p) => {
846                    args.push(bulk("PATTERN"));
847                    args.push(bulk(p.as_str()));
848                }
849            }
850        }
851        array(args)
852    }
853
854    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
855        match frame {
856            Frame::Array(Some(frames)) => frames
857                .into_iter()
858                .map(|f| match f {
859                    Frame::BulkString(Some(data)) => {
860                        Ok(String::from_utf8_lossy(&data).into_owned())
861                    }
862                    other => Err(RedisError::UnexpectedResponse {
863                        expected: "bulk string",
864                        actual: format!("{other:?}"),
865                    }),
866                })
867                .collect(),
868            Frame::Array(None) => Ok(Vec::new()),
869            other => Err(RedisError::UnexpectedResponse {
870                expected: "array",
871                actual: format!("{other:?}"),
872            }),
873        }
874    }
875
876    fn name(&self) -> &str {
877        "COMMAND LIST"
878    }
879}
880
881/// MODULE LIST
882///
883/// Returns information about the modules loaded into the server. The reply is
884/// an array of per-module maps (`name`, `ver`, `path`, `args`) and is returned
885/// as a raw [`Frame`] because its shape differs between RESP2 (flat arrays) and
886/// RESP3 (maps).
887///
888/// # Example
889///
890/// ```rust,no_run
891/// use redis_tower_commands::ModuleList;
892///
893/// let cmd = ModuleList::new();
894/// ```
895#[derive(Clone)]
896pub struct ModuleList;
897
898impl ModuleList {
899    /// Create a `MODULE LIST` command.
900    pub fn new() -> Self {
901        Self
902    }
903}
904
905impl Default for ModuleList {
906    fn default() -> Self {
907        Self::new()
908    }
909}
910
911impl Command for ModuleList {
912    type Response = Frame;
913
914    fn to_frame(&self) -> Frame {
915        array(vec![bulk("MODULE"), bulk("LIST")])
916    }
917
918    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
919        Ok(frame)
920    }
921
922    fn name(&self) -> &str {
923        "MODULE LIST"
924    }
925
926    fn idempotent(&self) -> bool {
927        true
928    }
929}
930
931/// MODULE LOAD path \[arg \[arg ...\]\]
932///
933/// Loads a Redis module and passes the optional binary-safe arguments to its
934/// initialization function.
935#[derive(Debug, Clone)]
936pub struct ModuleLoad {
937    path: Bytes,
938    args: Vec<Bytes>,
939}
940
941impl ModuleLoad {
942    /// Create a module-load request for `path`.
943    pub fn new(path: impl AsRef<[u8]>) -> Self {
944        Self {
945            path: Bytes::copy_from_slice(path.as_ref()),
946            args: Vec::new(),
947        }
948    }
949
950    /// Append one module initialization argument.
951    pub fn arg(mut self, argument: impl AsRef<[u8]>) -> Self {
952        self.args.push(Bytes::copy_from_slice(argument.as_ref()));
953        self
954    }
955
956    /// Append multiple module initialization arguments.
957    pub fn args<A, I>(mut self, arguments: I) -> Self
958    where
959        A: AsRef<[u8]>,
960        I: IntoIterator<Item = A>,
961    {
962        self.args.extend(
963            arguments
964                .into_iter()
965                .map(|argument| Bytes::copy_from_slice(argument.as_ref())),
966        );
967        self
968    }
969}
970
971impl Command for ModuleLoad {
972    type Response = ();
973
974    fn to_frame(&self) -> Frame {
975        let mut args = vec![bulk("MODULE"), bulk("LOAD"), bulk(&self.path)];
976        args.extend(self.args.iter().map(bulk));
977        array(args)
978    }
979
980    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
981        parse_ok_response(frame)
982    }
983
984    fn name(&self) -> &str {
985        "MODULE LOAD"
986    }
987}
988
989/// MODULE LOADEX path \[CONFIG name value \[CONFIG name value ...\]\]
990/// \[ARGS arg \[arg ...\]\]
991///
992/// Loads a Redis module with optional module configuration values and binary-
993/// safe initialization arguments.
994#[derive(Debug, Clone)]
995pub struct ModuleLoadEx {
996    path: Bytes,
997    configs: Vec<(Bytes, Bytes)>,
998    args: Vec<Bytes>,
999}
1000
1001impl ModuleLoadEx {
1002    /// Create an extended module-load request for `path`.
1003    pub fn new(path: impl AsRef<[u8]>) -> Self {
1004        Self {
1005            path: Bytes::copy_from_slice(path.as_ref()),
1006            configs: Vec::new(),
1007            args: Vec::new(),
1008        }
1009    }
1010
1011    /// Add one module configuration name/value pair.
1012    pub fn config(mut self, name: impl AsRef<[u8]>, value: impl AsRef<[u8]>) -> Self {
1013        self.configs.push((
1014            Bytes::copy_from_slice(name.as_ref()),
1015            Bytes::copy_from_slice(value.as_ref()),
1016        ));
1017        self
1018    }
1019
1020    /// Append one module initialization argument after the `ARGS` token.
1021    pub fn arg(mut self, argument: impl AsRef<[u8]>) -> Self {
1022        self.args.push(Bytes::copy_from_slice(argument.as_ref()));
1023        self
1024    }
1025
1026    /// Append multiple module initialization arguments after the `ARGS` token.
1027    pub fn args<A, I>(mut self, arguments: I) -> Self
1028    where
1029        A: AsRef<[u8]>,
1030        I: IntoIterator<Item = A>,
1031    {
1032        self.args.extend(
1033            arguments
1034                .into_iter()
1035                .map(|argument| Bytes::copy_from_slice(argument.as_ref())),
1036        );
1037        self
1038    }
1039}
1040
1041impl Command for ModuleLoadEx {
1042    type Response = ();
1043
1044    fn to_frame(&self) -> Frame {
1045        let mut args = vec![bulk("MODULE"), bulk("LOADEX"), bulk(&self.path)];
1046        for (name, value) in &self.configs {
1047            args.push(bulk("CONFIG"));
1048            args.push(bulk(name));
1049            args.push(bulk(value));
1050        }
1051        if !self.args.is_empty() {
1052            args.push(bulk("ARGS"));
1053            args.extend(self.args.iter().map(bulk));
1054        }
1055        array(args)
1056    }
1057
1058    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1059        parse_ok_response(frame)
1060    }
1061
1062    fn name(&self) -> &str {
1063        "MODULE LOADEX"
1064    }
1065}
1066
1067/// MODULE UNLOAD name
1068///
1069/// Unloads a module by its registered name.
1070#[derive(Debug, Clone)]
1071pub struct ModuleUnload {
1072    name: Bytes,
1073}
1074
1075impl ModuleUnload {
1076    /// Create a module-unload request.
1077    pub fn new(name: impl AsRef<[u8]>) -> Self {
1078        Self {
1079            name: Bytes::copy_from_slice(name.as_ref()),
1080        }
1081    }
1082}
1083
1084impl Command for ModuleUnload {
1085    type Response = ();
1086
1087    fn to_frame(&self) -> Frame {
1088        array(vec![bulk("MODULE"), bulk("UNLOAD"), bulk(&self.name)])
1089    }
1090
1091    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1092        parse_ok_response(frame)
1093    }
1094
1095    fn name(&self) -> &str {
1096        "MODULE UNLOAD"
1097    }
1098}
1099
1100/// BGSAVE \[SCHEDULE\]
1101///
1102/// Trigger a background save of the dataset. With `schedule`, the save
1103/// is queued if one is already in progress (instead of returning an error).
1104#[derive(Clone)]
1105pub struct BgSave {
1106    schedule: bool,
1107}
1108
1109impl BgSave {
1110    /// Create a new [`BgSave`] command.
1111    pub fn new() -> Self {
1112        Self { schedule: false }
1113    }
1114
1115    /// Queue the save if one is already in progress.
1116    pub fn schedule(mut self) -> Self {
1117        self.schedule = true;
1118        self
1119    }
1120}
1121
1122impl Default for BgSave {
1123    fn default() -> Self {
1124        Self::new()
1125    }
1126}
1127
1128impl Command for BgSave {
1129    type Response = String;
1130
1131    fn to_frame(&self) -> Frame {
1132        let mut args = vec![bulk("BGSAVE")];
1133        if self.schedule {
1134            args.push(bulk("SCHEDULE"));
1135        }
1136        array(args)
1137    }
1138
1139    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1140        match frame {
1141            Frame::SimpleString(s) => Ok(String::from_utf8_lossy(&s).into_owned()),
1142            other => Err(RedisError::UnexpectedResponse {
1143                expected: "simple string",
1144                actual: format!("{other:?}"),
1145            }),
1146        }
1147    }
1148
1149    fn name(&self) -> &str {
1150        "BGSAVE"
1151    }
1152}
1153
1154/// BGREWRITEAOF
1155///
1156/// Trigger an Append Only File rewrite. The rewrite runs in the background.
1157#[derive(Clone)]
1158pub struct BgRewriteAof;
1159
1160impl BgRewriteAof {
1161    /// Create a new [`BgRewriteAof`] command.
1162    pub fn new() -> Self {
1163        Self
1164    }
1165}
1166
1167impl Default for BgRewriteAof {
1168    fn default() -> Self {
1169        Self::new()
1170    }
1171}
1172
1173impl Command for BgRewriteAof {
1174    type Response = String;
1175
1176    fn to_frame(&self) -> Frame {
1177        array(vec![bulk("BGREWRITEAOF")])
1178    }
1179
1180    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1181        match frame {
1182            Frame::SimpleString(s) => Ok(String::from_utf8_lossy(&s).into_owned()),
1183            other => Err(RedisError::UnexpectedResponse {
1184                expected: "simple string",
1185                actual: format!("{other:?}"),
1186            }),
1187        }
1188    }
1189
1190    fn name(&self) -> &str {
1191        "BGREWRITEAOF"
1192    }
1193}
1194
1195/// LASTSAVE
1196///
1197/// Returns the Unix timestamp of the last successful save to disk.
1198#[derive(Clone)]
1199pub struct LastSave;
1200
1201impl LastSave {
1202    /// Create a new [`LastSave`] command.
1203    pub fn new() -> Self {
1204        Self
1205    }
1206}
1207
1208impl Default for LastSave {
1209    fn default() -> Self {
1210        Self::new()
1211    }
1212}
1213
1214impl Command for LastSave {
1215    type Response = i64;
1216
1217    fn to_frame(&self) -> Frame {
1218        array(vec![bulk("LASTSAVE")])
1219    }
1220
1221    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1222        match frame {
1223            Frame::Integer(n) => Ok(n),
1224            other => Err(RedisError::UnexpectedResponse {
1225                expected: "integer",
1226                actual: format!("{other:?}"),
1227            }),
1228        }
1229    }
1230
1231    fn name(&self) -> &str {
1232        "LASTSAVE"
1233    }
1234}
1235
1236/// REPLICAOF host port
1237///
1238/// Configure the server as a replica of another Redis instance,
1239/// or promote it to a primary with `ReplicaOf::no_one()`.
1240#[derive(Clone)]
1241pub struct ReplicaOf {
1242    host: String,
1243    port: String,
1244}
1245
1246impl ReplicaOf {
1247    /// Make this server a replica of the given host and port.
1248    pub fn new(host: impl Into<String>, port: u16) -> Self {
1249        Self {
1250            host: host.into(),
1251            port: port.to_string(),
1252        }
1253    }
1254
1255    /// Promote this server to primary (REPLICAOF NO ONE).
1256    pub fn no_one() -> Self {
1257        Self {
1258            host: "NO".to_string(),
1259            port: "ONE".to_string(),
1260        }
1261    }
1262}
1263
1264impl Command for ReplicaOf {
1265    type Response = ();
1266
1267    fn to_frame(&self) -> Frame {
1268        array(vec![
1269            bulk("REPLICAOF"),
1270            bulk(self.host.as_str()),
1271            bulk(self.port.as_str()),
1272        ])
1273    }
1274
1275    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1276        match frame {
1277            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1278            other => Err(RedisError::UnexpectedResponse {
1279                expected: "OK",
1280                actual: format!("{other:?}"),
1281            }),
1282        }
1283    }
1284
1285    fn name(&self) -> &str {
1286        "REPLICAOF"
1287    }
1288}
1289
1290/// SWAPDB index1 index2
1291///
1292/// Swap two Redis databases atomically.
1293#[derive(Clone)]
1294pub struct SwapDb {
1295    db1: u16,
1296    db2: u16,
1297}
1298
1299impl SwapDb {
1300    /// Create a new [`SwapDb`] command.
1301    pub fn new(db1: u16, db2: u16) -> Self {
1302        Self { db1, db2 }
1303    }
1304}
1305
1306impl Command for SwapDb {
1307    type Response = ();
1308
1309    fn to_frame(&self) -> Frame {
1310        array(vec![
1311            bulk("SWAPDB"),
1312            bulk(self.db1.to_string()),
1313            bulk(self.db2.to_string()),
1314        ])
1315    }
1316
1317    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1318        match frame {
1319            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1320            other => Err(RedisError::UnexpectedResponse {
1321                expected: "OK",
1322                actual: format!("{other:?}"),
1323            }),
1324        }
1325    }
1326
1327    fn name(&self) -> &str {
1328        "SWAPDB"
1329    }
1330}
1331
1332/// FAILOVER \[TO host port \[FORCE\]\] \[ABORT\] \[TIMEOUT milliseconds\]
1333///
1334/// Trigger a replica failover (Redis 6.2+). When run on a primary, it
1335/// coordinates with a replica to perform a graceful failover.
1336#[derive(Clone)]
1337pub struct Failover {
1338    to: Option<(String, u16)>,
1339    force: bool,
1340    abort: bool,
1341    timeout: Option<u64>,
1342}
1343
1344impl Failover {
1345    /// Initiate a failover with default settings.
1346    pub fn new() -> Self {
1347        Self {
1348            to: None,
1349            force: false,
1350            abort: false,
1351            timeout: None,
1352        }
1353    }
1354
1355    /// Abort an in-progress failover.
1356    pub fn abort() -> Self {
1357        Self {
1358            to: None,
1359            force: false,
1360            abort: true,
1361            timeout: None,
1362        }
1363    }
1364
1365    /// Target a specific replica for the failover.
1366    pub fn to(mut self, host: impl Into<String>, port: u16) -> Self {
1367        self.to = Some((host.into(), port));
1368        self
1369    }
1370
1371    /// Force the failover even if the target replica is unreachable.
1372    /// Only valid when a target is specified with `to()`.
1373    pub fn force(mut self) -> Self {
1374        self.force = true;
1375        self
1376    }
1377
1378    /// Set a timeout in milliseconds for the failover operation.
1379    pub fn timeout(mut self, ms: u64) -> Self {
1380        self.timeout = Some(ms);
1381        self
1382    }
1383}
1384
1385impl Default for Failover {
1386    fn default() -> Self {
1387        Self::new()
1388    }
1389}
1390
1391impl Command for Failover {
1392    type Response = ();
1393
1394    fn to_frame(&self) -> Frame {
1395        let mut args = vec![bulk("FAILOVER")];
1396        if let Some((ref host, port)) = self.to {
1397            args.push(bulk("TO"));
1398            args.push(bulk(host.as_str()));
1399            args.push(bulk(port.to_string()));
1400            if self.force {
1401                args.push(bulk("FORCE"));
1402            }
1403        }
1404        if self.abort {
1405            args.push(bulk("ABORT"));
1406        }
1407        if let Some(ms) = self.timeout {
1408            args.push(bulk("TIMEOUT"));
1409            args.push(bulk(ms.to_string()));
1410        }
1411        array(args)
1412    }
1413
1414    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1415        match frame {
1416            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1417            other => Err(RedisError::UnexpectedResponse {
1418                expected: "OK",
1419                actual: format!("{other:?}"),
1420            }),
1421        }
1422    }
1423
1424    fn name(&self) -> &str {
1425        "FAILOVER"
1426    }
1427}
1428
1429/// WAIT numreplicas timeout
1430///
1431/// Blocks the current client until all previous write commands are acknowledged
1432/// by at least `numreplicas` replicas, or until the timeout (in milliseconds)
1433/// expires. Returns the number of replicas that acknowledged.
1434#[derive(Clone)]
1435pub struct Wait {
1436    numreplicas: i64,
1437    timeout: i64,
1438}
1439
1440impl Wait {
1441    /// Create a new [`Wait`] command.
1442    pub fn new(numreplicas: i64, timeout: i64) -> Self {
1443        Self {
1444            numreplicas,
1445            timeout,
1446        }
1447    }
1448}
1449
1450impl Command for Wait {
1451    type Response = i64;
1452
1453    fn to_frame(&self) -> Frame {
1454        array(vec![
1455            bulk("WAIT"),
1456            bulk(self.numreplicas.to_string()),
1457            bulk(self.timeout.to_string()),
1458        ])
1459    }
1460
1461    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1462        match frame {
1463            Frame::Integer(n) => Ok(n),
1464            other => Err(RedisError::UnexpectedResponse {
1465                expected: "integer",
1466                actual: format!("{other:?}"),
1467            }),
1468        }
1469    }
1470
1471    fn name(&self) -> &str {
1472        "WAIT"
1473    }
1474}
1475
1476/// WAITAOF numlocal numreplicas timeout
1477///
1478/// Blocks the current client until all previous write commands are fsynced
1479/// to the AOF of the local host and/or at least `numreplicas` replicas.
1480/// Returns a tuple of (local, replicas) counts parsed from a two-element array.
1481#[derive(Clone)]
1482pub struct WaitAof {
1483    numlocal: i64,
1484    numreplicas: i64,
1485    timeout: i64,
1486}
1487
1488impl WaitAof {
1489    /// Create a new [`WaitAof`] command.
1490    pub fn new(numlocal: i64, numreplicas: i64, timeout: i64) -> Self {
1491        Self {
1492            numlocal,
1493            numreplicas,
1494            timeout,
1495        }
1496    }
1497}
1498
1499impl Command for WaitAof {
1500    type Response = (i64, i64);
1501
1502    fn to_frame(&self) -> Frame {
1503        array(vec![
1504            bulk("WAITAOF"),
1505            bulk(self.numlocal.to_string()),
1506            bulk(self.numreplicas.to_string()),
1507            bulk(self.timeout.to_string()),
1508        ])
1509    }
1510
1511    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1512        match frame {
1513            Frame::Array(Some(frames)) if frames.len() == 2 => {
1514                let local = match &frames[0] {
1515                    Frame::Integer(n) => *n,
1516                    other => {
1517                        return Err(RedisError::UnexpectedResponse {
1518                            expected: "integer",
1519                            actual: format!("{other:?}"),
1520                        });
1521                    }
1522                };
1523                let replicas = match &frames[1] {
1524                    Frame::Integer(n) => *n,
1525                    other => {
1526                        return Err(RedisError::UnexpectedResponse {
1527                            expected: "integer",
1528                            actual: format!("{other:?}"),
1529                        });
1530                    }
1531                };
1532                Ok((local, replicas))
1533            }
1534            other => Err(RedisError::UnexpectedResponse {
1535                expected: "array of two integers",
1536                actual: format!("{other:?}"),
1537            }),
1538        }
1539    }
1540
1541    fn name(&self) -> &str {
1542        "WAITAOF"
1543    }
1544}
1545
1546// ---------------------------------------------------------------------------
1547// CLIENT subcommands
1548// ---------------------------------------------------------------------------
1549
1550/// CLIENT ID
1551///
1552/// Returns the ID of the current connection.
1553#[derive(Clone)]
1554pub struct ClientId;
1555
1556impl ClientId {
1557    /// Create a new [`ClientId`] command.
1558    pub fn new() -> Self {
1559        Self
1560    }
1561}
1562
1563impl Default for ClientId {
1564    fn default() -> Self {
1565        Self::new()
1566    }
1567}
1568
1569impl Command for ClientId {
1570    type Response = i64;
1571
1572    fn to_frame(&self) -> Frame {
1573        array(vec![bulk("CLIENT"), bulk("ID")])
1574    }
1575
1576    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1577        match frame {
1578            Frame::Integer(n) => Ok(n),
1579            other => Err(RedisError::UnexpectedResponse {
1580                expected: "integer",
1581                actual: format!("{other:?}"),
1582            }),
1583        }
1584    }
1585
1586    fn name(&self) -> &str {
1587        "CLIENT ID"
1588    }
1589}
1590
1591/// CLIENT GETNAME
1592///
1593/// Returns the name of the current connection as set by CLIENT SETNAME,
1594/// or None if no name is set.
1595#[derive(Clone)]
1596pub struct ClientGetName;
1597
1598impl ClientGetName {
1599    /// Create a new [`ClientGetName`] command.
1600    pub fn new() -> Self {
1601        Self
1602    }
1603}
1604
1605impl Default for ClientGetName {
1606    fn default() -> Self {
1607        Self::new()
1608    }
1609}
1610
1611impl Command for ClientGetName {
1612    type Response = Option<Bytes>;
1613
1614    fn to_frame(&self) -> Frame {
1615        array(vec![bulk("CLIENT"), bulk("GETNAME")])
1616    }
1617
1618    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1619        match frame {
1620            Frame::BulkString(Some(data)) => Ok(Some(data)),
1621            Frame::BulkString(None) | Frame::Null => Ok(None),
1622            other => Err(RedisError::UnexpectedResponse {
1623                expected: "bulk string or null",
1624                actual: format!("{other:?}"),
1625            }),
1626        }
1627    }
1628
1629    fn name(&self) -> &str {
1630        "CLIENT GETNAME"
1631    }
1632}
1633
1634/// CLIENT SETNAME connection-name
1635///
1636/// Set the name of the current connection.
1637#[derive(Clone)]
1638pub struct ClientSetName {
1639    name: String,
1640}
1641
1642impl ClientSetName {
1643    /// Create a new [`ClientSetName`] command.
1644    pub fn new(name: impl Into<String>) -> Self {
1645        Self { name: name.into() }
1646    }
1647}
1648
1649impl Command for ClientSetName {
1650    type Response = ();
1651
1652    fn to_frame(&self) -> Frame {
1653        array(vec![
1654            bulk("CLIENT"),
1655            bulk("SETNAME"),
1656            bulk(self.name.as_str()),
1657        ])
1658    }
1659
1660    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1661        match frame {
1662            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1663            other => Err(RedisError::UnexpectedResponse {
1664                expected: "OK",
1665                actual: format!("{other:?}"),
1666            }),
1667        }
1668    }
1669
1670    fn name(&self) -> &str {
1671        "CLIENT SETNAME"
1672    }
1673}
1674
1675/// Filter type for CLIENT LIST.
1676#[derive(Clone)]
1677pub enum ClientListType {
1678    /// Select the `Normal` mode.
1679    Normal,
1680    /// Select the `Master` mode.
1681    Master,
1682    /// Select the `Replica` mode.
1683    Replica,
1684    /// Select the `Pubsub` mode.
1685    Pubsub,
1686}
1687
1688impl ClientListType {
1689    fn as_str(&self) -> &str {
1690        match self {
1691            Self::Normal => "normal",
1692            Self::Master => "master",
1693            Self::Replica => "replica",
1694            Self::Pubsub => "pubsub",
1695        }
1696    }
1697}
1698
1699/// CLIENT LIST \[TYPE normal|master|replica|pubsub\]
1700///
1701/// Returns information and statistics about client connections.
1702/// The response is raw text with one client per line.
1703#[derive(Clone)]
1704pub struct ClientList {
1705    client_type: Option<ClientListType>,
1706}
1707
1708impl ClientList {
1709    /// Create a new [`ClientList`] command.
1710    pub fn new() -> Self {
1711        Self { client_type: None }
1712    }
1713
1714    /// Filter clients by type.
1715    pub fn client_type(mut self, t: ClientListType) -> Self {
1716        self.client_type = Some(t);
1717        self
1718    }
1719}
1720
1721impl Default for ClientList {
1722    fn default() -> Self {
1723        Self::new()
1724    }
1725}
1726
1727impl Command for ClientList {
1728    type Response = Bytes;
1729
1730    fn to_frame(&self) -> Frame {
1731        let mut args = vec![bulk("CLIENT"), bulk("LIST")];
1732        if let Some(ref t) = self.client_type {
1733            args.push(bulk("TYPE"));
1734            args.push(bulk(t.as_str()));
1735        }
1736        array(args)
1737    }
1738
1739    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1740        match frame {
1741            // RESP3 returns CLIENT LIST as a verbatim string.
1742            Frame::BulkString(Some(data)) | Frame::VerbatimString(_, data) => Ok(data),
1743            other => Err(RedisError::UnexpectedResponse {
1744                expected: "bulk or verbatim string",
1745                actual: format!("{other:?}"),
1746            }),
1747        }
1748    }
1749
1750    fn name(&self) -> &str {
1751        "CLIENT LIST"
1752    }
1753}
1754
1755/// CLIENT KILL \[ID id\] \[ADDR addr\] \[LADDR addr\] \[USER user\] \[SKIPME yes|no\]
1756///
1757/// Kill client connections matching the given filters.
1758/// Returns the number of clients killed.
1759#[derive(Clone)]
1760pub struct ClientKill {
1761    id: Option<i64>,
1762    addr: Option<String>,
1763    laddr: Option<String>,
1764    user: Option<String>,
1765    skipme: Option<bool>,
1766}
1767
1768impl ClientKill {
1769    /// Create a new [`ClientKill`] command.
1770    pub fn new() -> Self {
1771        Self {
1772            id: None,
1773            addr: None,
1774            laddr: None,
1775            user: None,
1776            skipme: None,
1777        }
1778    }
1779
1780    /// Kill client by connection ID.
1781    pub fn id(mut self, id: i64) -> Self {
1782        self.id = Some(id);
1783        self
1784    }
1785
1786    /// Kill client by remote address (ip:port).
1787    pub fn addr(mut self, addr: impl Into<String>) -> Self {
1788        self.addr = Some(addr.into());
1789        self
1790    }
1791
1792    /// Kill client by local address (ip:port).
1793    pub fn laddr(mut self, laddr: impl Into<String>) -> Self {
1794        self.laddr = Some(laddr.into());
1795        self
1796    }
1797
1798    /// Kill client by authenticated username.
1799    pub fn user(mut self, user: impl Into<String>) -> Self {
1800        self.user = Some(user.into());
1801        self
1802    }
1803
1804    /// Whether to skip the calling client (default yes).
1805    pub fn skipme(mut self, skipme: bool) -> Self {
1806        self.skipme = Some(skipme);
1807        self
1808    }
1809}
1810
1811impl Default for ClientKill {
1812    fn default() -> Self {
1813        Self::new()
1814    }
1815}
1816
1817impl Command for ClientKill {
1818    type Response = i64;
1819
1820    fn to_frame(&self) -> Frame {
1821        let mut args = vec![bulk("CLIENT"), bulk("KILL")];
1822        if let Some(id) = self.id {
1823            args.push(bulk("ID"));
1824            args.push(bulk(id.to_string()));
1825        }
1826        if let Some(ref addr) = self.addr {
1827            args.push(bulk("ADDR"));
1828            args.push(bulk(addr.as_str()));
1829        }
1830        if let Some(ref laddr) = self.laddr {
1831            args.push(bulk("LADDR"));
1832            args.push(bulk(laddr.as_str()));
1833        }
1834        if let Some(ref user) = self.user {
1835            args.push(bulk("USER"));
1836            args.push(bulk(user.as_str()));
1837        }
1838        if let Some(skipme) = self.skipme {
1839            args.push(bulk("SKIPME"));
1840            args.push(bulk(if skipme { "yes" } else { "no" }));
1841        }
1842        array(args)
1843    }
1844
1845    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1846        match frame {
1847            Frame::Integer(n) => Ok(n),
1848            other => Err(RedisError::UnexpectedResponse {
1849                expected: "integer",
1850                actual: format!("{other:?}"),
1851            }),
1852        }
1853    }
1854
1855    fn name(&self) -> &str {
1856        "CLIENT KILL"
1857    }
1858}
1859
1860/// CLIENT INFO
1861///
1862/// Returns information about the current client connection.
1863#[derive(Clone)]
1864pub struct ClientInfo;
1865
1866impl ClientInfo {
1867    /// Create a new [`ClientInfo`] command.
1868    pub fn new() -> Self {
1869        Self
1870    }
1871}
1872
1873impl Default for ClientInfo {
1874    fn default() -> Self {
1875        Self::new()
1876    }
1877}
1878
1879impl Command for ClientInfo {
1880    type Response = Bytes;
1881
1882    fn to_frame(&self) -> Frame {
1883        array(vec![bulk("CLIENT"), bulk("INFO")])
1884    }
1885
1886    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1887        match frame {
1888            // RESP3 returns CLIENT INFO as a verbatim string.
1889            Frame::BulkString(Some(data)) | Frame::VerbatimString(_, data) => Ok(data),
1890            other => Err(RedisError::UnexpectedResponse {
1891                expected: "bulk or verbatim string",
1892                actual: format!("{other:?}"),
1893            }),
1894        }
1895    }
1896
1897    fn name(&self) -> &str {
1898        "CLIENT INFO"
1899    }
1900}
1901
1902/// CLIENT NO-EVICT ON|OFF
1903///
1904/// Set the client eviction mode for the current connection. When enabled,
1905/// the current client will not be evicted even when the maxmemory-clients
1906/// threshold is reached.
1907#[derive(Clone)]
1908pub struct ClientNoEvict {
1909    enabled: bool,
1910}
1911
1912impl ClientNoEvict {
1913    /// Create a new [`ClientNoEvict`] command.
1914    pub fn new(enabled: bool) -> Self {
1915        Self { enabled }
1916    }
1917}
1918
1919impl Command for ClientNoEvict {
1920    type Response = ();
1921
1922    fn to_frame(&self) -> Frame {
1923        array(vec![
1924            bulk("CLIENT"),
1925            bulk("NO-EVICT"),
1926            bulk(if self.enabled { "ON" } else { "OFF" }),
1927        ])
1928    }
1929
1930    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1931        match frame {
1932            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1933            other => Err(RedisError::UnexpectedResponse {
1934                expected: "OK",
1935                actual: format!("{other:?}"),
1936            }),
1937        }
1938    }
1939
1940    fn name(&self) -> &str {
1941        "CLIENT NO-EVICT"
1942    }
1943}
1944
1945/// CLIENT NO-TOUCH ON|OFF
1946///
1947/// Control whether commands sent by the client affect LRU/LFU of accessed
1948/// keys. When enabled, accessed keys will not have their idle time or
1949/// frequency updated.
1950#[derive(Clone)]
1951pub struct ClientNoTouch {
1952    enabled: bool,
1953}
1954
1955impl ClientNoTouch {
1956    /// Create a new [`ClientNoTouch`] command.
1957    pub fn new(enabled: bool) -> Self {
1958        Self { enabled }
1959    }
1960}
1961
1962impl Command for ClientNoTouch {
1963    type Response = ();
1964
1965    fn to_frame(&self) -> Frame {
1966        array(vec![
1967            bulk("CLIENT"),
1968            bulk("NO-TOUCH"),
1969            bulk(if self.enabled { "ON" } else { "OFF" }),
1970        ])
1971    }
1972
1973    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
1974        match frame {
1975            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
1976            other => Err(RedisError::UnexpectedResponse {
1977                expected: "OK",
1978                actual: format!("{other:?}"),
1979            }),
1980        }
1981    }
1982
1983    fn name(&self) -> &str {
1984        "CLIENT NO-TOUCH"
1985    }
1986}
1987
1988/// Pause mode for CLIENT PAUSE.
1989#[derive(Clone)]
1990pub enum ClientPauseMode {
1991    /// Pause all client commands.
1992    All,
1993    /// Only pause write commands.
1994    Write,
1995}
1996
1997impl ClientPauseMode {
1998    fn as_str(&self) -> &str {
1999        match self {
2000            Self::All => "ALL",
2001            Self::Write => "WRITE",
2002        }
2003    }
2004}
2005
2006/// CLIENT PAUSE timeout \[WRITE|ALL\]
2007///
2008/// Suspend all clients for the specified amount of time (in milliseconds).
2009#[derive(Clone)]
2010pub struct ClientPause {
2011    timeout: u64,
2012    mode: Option<ClientPauseMode>,
2013}
2014
2015impl ClientPause {
2016    /// Create a new [`ClientPause`] command.
2017    pub fn new(timeout: u64) -> Self {
2018        Self {
2019            timeout,
2020            mode: None,
2021        }
2022    }
2023
2024    /// Set the pause mode.
2025    pub fn mode(mut self, mode: ClientPauseMode) -> Self {
2026        self.mode = Some(mode);
2027        self
2028    }
2029}
2030
2031impl Command for ClientPause {
2032    type Response = ();
2033
2034    fn to_frame(&self) -> Frame {
2035        let mut args = vec![
2036            bulk("CLIENT"),
2037            bulk("PAUSE"),
2038            bulk(self.timeout.to_string()),
2039        ];
2040        if let Some(ref mode) = self.mode {
2041            args.push(bulk(mode.as_str()));
2042        }
2043        array(args)
2044    }
2045
2046    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2047        match frame {
2048            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2049            other => Err(RedisError::UnexpectedResponse {
2050                expected: "OK",
2051                actual: format!("{other:?}"),
2052            }),
2053        }
2054    }
2055
2056    fn name(&self) -> &str {
2057        "CLIENT PAUSE"
2058    }
2059}
2060
2061/// CLIENT UNPAUSE
2062///
2063/// Resume clients that were paused by CLIENT PAUSE.
2064#[derive(Clone)]
2065pub struct ClientUnpause;
2066
2067impl ClientUnpause {
2068    /// Create a new [`ClientUnpause`] command.
2069    pub fn new() -> Self {
2070        Self
2071    }
2072}
2073
2074impl Default for ClientUnpause {
2075    fn default() -> Self {
2076        Self::new()
2077    }
2078}
2079
2080impl Command for ClientUnpause {
2081    type Response = ();
2082
2083    fn to_frame(&self) -> Frame {
2084        array(vec![bulk("CLIENT"), bulk("UNPAUSE")])
2085    }
2086
2087    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2088        match frame {
2089            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2090            other => Err(RedisError::UnexpectedResponse {
2091                expected: "OK",
2092                actual: format!("{other:?}"),
2093            }),
2094        }
2095    }
2096
2097    fn name(&self) -> &str {
2098        "CLIENT UNPAUSE"
2099    }
2100}
2101
2102// ---------------------------------------------------------------------------
2103// CONFIG subcommands
2104// ---------------------------------------------------------------------------
2105
2106/// CONFIG GET pattern
2107///
2108/// Returns configuration parameters matching the glob-style pattern.
2109/// The response is a list of key-value pairs.
2110#[derive(Clone)]
2111pub struct ConfigGet {
2112    pattern: String,
2113}
2114
2115impl ConfigGet {
2116    /// Create a new [`ConfigGet`] command.
2117    pub fn new(pattern: impl Into<String>) -> Self {
2118        Self {
2119            pattern: pattern.into(),
2120        }
2121    }
2122}
2123
2124impl Command for ConfigGet {
2125    type Response = Vec<(Bytes, Bytes)>;
2126
2127    fn to_frame(&self) -> Frame {
2128        array(vec![
2129            bulk("CONFIG"),
2130            bulk("GET"),
2131            bulk(self.pattern.as_str()),
2132        ])
2133    }
2134
2135    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2136        match frame {
2137            // RESP2: flat array of alternating key, value bulk strings
2138            Frame::Array(Some(frames)) => {
2139                if frames.len() % 2 != 0 {
2140                    return Err(RedisError::UnexpectedResponse {
2141                        expected: "array with even number of elements",
2142                        actual: format!("array with {} elements", frames.len()),
2143                    });
2144                }
2145                frames
2146                    .chunks(2)
2147                    .map(|pair| {
2148                        let key = match &pair[0] {
2149                            Frame::BulkString(Some(data)) => data.clone(),
2150                            other => {
2151                                return Err(RedisError::UnexpectedResponse {
2152                                    expected: "bulk string",
2153                                    actual: format!("{other:?}"),
2154                                });
2155                            }
2156                        };
2157                        let value = match &pair[1] {
2158                            Frame::BulkString(Some(data)) => data.clone(),
2159                            other => {
2160                                return Err(RedisError::UnexpectedResponse {
2161                                    expected: "bulk string",
2162                                    actual: format!("{other:?}"),
2163                                });
2164                            }
2165                        };
2166                        Ok((key, value))
2167                    })
2168                    .collect()
2169            }
2170            // RESP3: Map of key-value pairs
2171            Frame::Map(pairs) => pairs
2172                .into_iter()
2173                .map(|(k, v)| {
2174                    let key = match k {
2175                        Frame::BulkString(Some(data)) => data,
2176                        other => {
2177                            return Err(RedisError::UnexpectedResponse {
2178                                expected: "bulk string key",
2179                                actual: format!("{other:?}"),
2180                            });
2181                        }
2182                    };
2183                    let value = match v {
2184                        Frame::BulkString(Some(data)) => data,
2185                        other => {
2186                            return Err(RedisError::UnexpectedResponse {
2187                                expected: "bulk string value",
2188                                actual: format!("{other:?}"),
2189                            });
2190                        }
2191                    };
2192                    Ok((key, value))
2193                })
2194                .collect(),
2195            other => Err(RedisError::UnexpectedResponse {
2196                expected: "array or map",
2197                actual: format!("{other:?}"),
2198            }),
2199        }
2200    }
2201
2202    fn name(&self) -> &str {
2203        "CONFIG GET"
2204    }
2205}
2206
2207/// CONFIG SET param value \[param value ...\]
2208///
2209/// Set one or more configuration parameters to the given values.
2210#[derive(Clone)]
2211pub struct ConfigSet {
2212    pairs: Vec<(String, String)>,
2213}
2214
2215impl ConfigSet {
2216    /// Set a single configuration parameter.
2217    pub fn new(param: impl Into<String>, value: impl Into<String>) -> Self {
2218        Self {
2219            pairs: vec![(param.into(), value.into())],
2220        }
2221    }
2222
2223    /// Add an additional parameter-value pair.
2224    pub fn param(mut self, param: impl Into<String>, value: impl Into<String>) -> Self {
2225        self.pairs.push((param.into(), value.into()));
2226        self
2227    }
2228}
2229
2230impl Command for ConfigSet {
2231    type Response = ();
2232
2233    fn to_frame(&self) -> Frame {
2234        let mut args = vec![bulk("CONFIG"), bulk("SET")];
2235        for (param, value) in &self.pairs {
2236            args.push(bulk(param.as_str()));
2237            args.push(bulk(value.as_str()));
2238        }
2239        array(args)
2240    }
2241
2242    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2243        match frame {
2244            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2245            other => Err(RedisError::UnexpectedResponse {
2246                expected: "OK",
2247                actual: format!("{other:?}"),
2248            }),
2249        }
2250    }
2251
2252    fn name(&self) -> &str {
2253        "CONFIG SET"
2254    }
2255}
2256
2257/// CONFIG RESETSTAT
2258///
2259/// Reset the statistics reported by the INFO command.
2260#[derive(Clone)]
2261pub struct ConfigResetStat;
2262
2263impl ConfigResetStat {
2264    /// Create a new [`ConfigResetStat`] command.
2265    pub fn new() -> Self {
2266        Self
2267    }
2268}
2269
2270impl Default for ConfigResetStat {
2271    fn default() -> Self {
2272        Self::new()
2273    }
2274}
2275
2276impl Command for ConfigResetStat {
2277    type Response = ();
2278
2279    fn to_frame(&self) -> Frame {
2280        array(vec![bulk("CONFIG"), bulk("RESETSTAT")])
2281    }
2282
2283    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2284        match frame {
2285            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2286            other => Err(RedisError::UnexpectedResponse {
2287                expected: "OK",
2288                actual: format!("{other:?}"),
2289            }),
2290        }
2291    }
2292
2293    fn name(&self) -> &str {
2294        "CONFIG RESETSTAT"
2295    }
2296}
2297
2298/// CONFIG REWRITE
2299///
2300/// Rewrite the configuration file with the in-memory configuration.
2301#[derive(Clone)]
2302pub struct ConfigRewrite;
2303
2304impl ConfigRewrite {
2305    /// Create a new [`ConfigRewrite`] command.
2306    pub fn new() -> Self {
2307        Self
2308    }
2309}
2310
2311impl Default for ConfigRewrite {
2312    fn default() -> Self {
2313        Self::new()
2314    }
2315}
2316
2317impl Command for ConfigRewrite {
2318    type Response = ();
2319
2320    fn to_frame(&self) -> Frame {
2321        array(vec![bulk("CONFIG"), bulk("REWRITE")])
2322    }
2323
2324    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2325        match frame {
2326            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2327            other => Err(RedisError::UnexpectedResponse {
2328                expected: "OK",
2329                actual: format!("{other:?}"),
2330            }),
2331        }
2332    }
2333
2334    fn name(&self) -> &str {
2335        "CONFIG REWRITE"
2336    }
2337}
2338
2339/// CLIENT SETINFO LIB-NAME name
2340///
2341/// Set the client library name. Sent automatically on connection to
2342/// identify the client library to the Redis server.
2343#[derive(Clone)]
2344pub struct ClientSetInfoLibName {
2345    name: String,
2346}
2347
2348impl ClientSetInfoLibName {
2349    /// Create a new [`ClientSetInfoLibName`] command.
2350    pub fn new(name: impl Into<String>) -> Self {
2351        Self { name: name.into() }
2352    }
2353}
2354
2355impl Command for ClientSetInfoLibName {
2356    type Response = ();
2357
2358    fn to_frame(&self) -> Frame {
2359        array(vec![
2360            bulk("CLIENT"),
2361            bulk("SETINFO"),
2362            bulk("LIB-NAME"),
2363            bulk(self.name.as_str()),
2364        ])
2365    }
2366
2367    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2368        match frame {
2369            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2370            other => Err(RedisError::UnexpectedResponse {
2371                expected: "OK",
2372                actual: format!("{other:?}"),
2373            }),
2374        }
2375    }
2376
2377    fn name(&self) -> &str {
2378        "CLIENT SETINFO"
2379    }
2380}
2381
2382/// CLIENT SETINFO LIB-VER version
2383///
2384/// Set the client library version. Sent automatically on connection to
2385/// identify the client library version to the Redis server.
2386#[derive(Clone)]
2387pub struct ClientSetInfoLibVer {
2388    version: String,
2389}
2390
2391impl ClientSetInfoLibVer {
2392    /// Create a new [`ClientSetInfoLibVer`] command.
2393    pub fn new(version: impl Into<String>) -> Self {
2394        Self {
2395            version: version.into(),
2396        }
2397    }
2398}
2399
2400impl Command for ClientSetInfoLibVer {
2401    type Response = ();
2402
2403    fn to_frame(&self) -> Frame {
2404        array(vec![
2405            bulk("CLIENT"),
2406            bulk("SETINFO"),
2407            bulk("LIB-VER"),
2408            bulk(self.version.as_str()),
2409        ])
2410    }
2411
2412    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2413        match frame {
2414            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2415            other => Err(RedisError::UnexpectedResponse {
2416                expected: "OK",
2417                actual: format!("{other:?}"),
2418            }),
2419        }
2420    }
2421
2422    fn name(&self) -> &str {
2423        "CLIENT SETINFO"
2424    }
2425}
2426
2427/// ECHO message
2428///
2429/// Returns `message` back to the client. Useful for testing connectivity.
2430#[derive(Clone)]
2431pub struct Echo {
2432    message: CommandArg,
2433}
2434
2435impl Echo {
2436    /// Create a new [`Echo`] command.
2437    pub fn new(message: impl Into<CommandArg>) -> Self {
2438        Self {
2439            message: message.into(),
2440        }
2441    }
2442}
2443
2444impl Command for Echo {
2445    type Response = Bytes;
2446
2447    fn to_frame(&self) -> Frame {
2448        array(vec![bulk("ECHO"), bulk(&self.message)])
2449    }
2450
2451    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2452        match frame {
2453            Frame::BulkString(Some(data)) => Ok(data),
2454            other => Err(RedisError::UnexpectedResponse {
2455                expected: "bulk string",
2456                actual: format!("{other:?}"),
2457            }),
2458        }
2459    }
2460
2461    fn name(&self) -> &str {
2462        "ECHO"
2463    }
2464}
2465
2466/// FLUSHALL [ASYNC|SYNC]
2467///
2468/// Delete all keys in all databases.
2469#[derive(Clone)]
2470pub struct FlushAll {
2471    mode: Option<FlushMode>,
2472}
2473
2474impl FlushAll {
2475    /// Create a new [`FlushAll`] command.
2476    pub fn new() -> Self {
2477        Self { mode: None }
2478    }
2479
2480    /// Configure the `async_mode` option.
2481    pub fn async_mode(mut self) -> Self {
2482        self.mode = Some(FlushMode::Async);
2483        self
2484    }
2485
2486    /// Configure the `sync_mode` option.
2487    pub fn sync_mode(mut self) -> Self {
2488        self.mode = Some(FlushMode::Sync);
2489        self
2490    }
2491}
2492
2493impl Default for FlushAll {
2494    fn default() -> Self {
2495        Self::new()
2496    }
2497}
2498
2499impl Command for FlushAll {
2500    type Response = ();
2501
2502    fn to_frame(&self) -> Frame {
2503        let mut args = vec![bulk("FLUSHALL")];
2504        match &self.mode {
2505            Some(FlushMode::Async) => args.push(bulk("ASYNC")),
2506            Some(FlushMode::Sync) => args.push(bulk("SYNC")),
2507            None => {}
2508        }
2509        array(args)
2510    }
2511
2512    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2513        match frame {
2514            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2515            other => Err(RedisError::UnexpectedResponse {
2516                expected: "OK",
2517                actual: format!("{other:?}"),
2518            }),
2519        }
2520    }
2521
2522    fn name(&self) -> &str {
2523        "FLUSHALL"
2524    }
2525}
2526
2527/// SAVE
2528///
2529/// Synchronously save the dataset to disk.
2530#[derive(Clone)]
2531pub struct Save;
2532
2533impl Save {
2534    /// Create a new [`Save`] command.
2535    pub fn new() -> Self {
2536        Self
2537    }
2538}
2539
2540impl Default for Save {
2541    fn default() -> Self {
2542        Self::new()
2543    }
2544}
2545
2546impl Command for Save {
2547    type Response = ();
2548
2549    fn to_frame(&self) -> Frame {
2550        array(vec![bulk("SAVE")])
2551    }
2552
2553    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2554        match frame {
2555            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
2556            other => Err(RedisError::UnexpectedResponse {
2557                expected: "OK",
2558                actual: format!("{other:?}"),
2559            }),
2560        }
2561    }
2562
2563    fn name(&self) -> &str {
2564        "SAVE"
2565    }
2566}
2567
2568/// Save behavior for SHUTDOWN.
2569#[derive(Clone)]
2570pub enum ShutdownMode {
2571    /// Do not save the dataset before shutting down.
2572    NoSave,
2573    /// Force a save of the dataset before shutting down.
2574    Save,
2575}
2576
2577/// SHUTDOWN \[NOSAVE | SAVE\] \[NOW\] \[FORCE\] \[ABORT\]
2578///
2579/// Shuts down the server. On a successful shutdown the connection is closed and
2580/// no reply is received; this command therefore treats both an absent reply and
2581/// an `OK` reply as success.
2582#[derive(Clone)]
2583pub struct Shutdown {
2584    mode: Option<ShutdownMode>,
2585    now: bool,
2586    force: bool,
2587    abort: bool,
2588}
2589
2590impl Shutdown {
2591    /// Create a new [`Shutdown`] command.
2592    pub fn new() -> Self {
2593        Self {
2594            mode: None,
2595            now: false,
2596            force: false,
2597            abort: false,
2598        }
2599    }
2600
2601    /// Skip saving the dataset (NOSAVE).
2602    pub fn nosave(mut self) -> Self {
2603        self.mode = Some(ShutdownMode::NoSave);
2604        self
2605    }
2606
2607    /// Force a save of the dataset (SAVE).
2608    pub fn save_mode(mut self) -> Self {
2609        self.mode = Some(ShutdownMode::Save);
2610        self
2611    }
2612
2613    /// Skip the graceful shutdown delay (NOW).
2614    pub fn now(mut self) -> Self {
2615        self.now = true;
2616        self
2617    }
2618
2619    /// Force shutdown even if there are errors (FORCE).
2620    pub fn force(mut self) -> Self {
2621        self.force = true;
2622        self
2623    }
2624
2625    /// Abort an in-progress shutdown (ABORT).
2626    pub fn abort(mut self) -> Self {
2627        self.abort = true;
2628        self
2629    }
2630}
2631
2632impl Default for Shutdown {
2633    fn default() -> Self {
2634        Self::new()
2635    }
2636}
2637
2638impl Command for Shutdown {
2639    type Response = ();
2640
2641    fn to_frame(&self) -> Frame {
2642        let mut args = vec![bulk("SHUTDOWN")];
2643        match &self.mode {
2644            Some(ShutdownMode::NoSave) => args.push(bulk("NOSAVE")),
2645            Some(ShutdownMode::Save) => args.push(bulk("SAVE")),
2646            None => {}
2647        }
2648        if self.now {
2649            args.push(bulk("NOW"));
2650        }
2651        if self.force {
2652            args.push(bulk("FORCE"));
2653        }
2654        if self.abort {
2655            args.push(bulk("ABORT"));
2656        }
2657        array(args)
2658    }
2659
2660    fn parse_response(&self, _frame: Frame) -> Result<Self::Response, RedisError> {
2661        // A successful SHUTDOWN closes the connection without a reply. Any frame
2662        // received (e.g. an OK from SHUTDOWN ABORT) is treated as success.
2663        Ok(())
2664    }
2665
2666    fn name(&self) -> &str {
2667        "SHUTDOWN"
2668    }
2669}
2670
2671/// ROLE
2672///
2673/// Returns the role of the instance in the context of replication. The response
2674/// structure varies by role, so the raw `Frame` is returned.
2675#[derive(Clone)]
2676pub struct Role;
2677
2678impl Role {
2679    /// Create a new [`Role`] command.
2680    pub fn new() -> Self {
2681        Self
2682    }
2683}
2684
2685impl Default for Role {
2686    fn default() -> Self {
2687        Self::new()
2688    }
2689}
2690
2691impl Command for Role {
2692    type Response = Frame;
2693
2694    fn to_frame(&self) -> Frame {
2695        array(vec![bulk("ROLE")])
2696    }
2697
2698    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2699        Ok(frame)
2700    }
2701
2702    fn name(&self) -> &str {
2703        "ROLE"
2704    }
2705}
2706
2707/// HELLO \[protover \[AUTH username password\] \[SETNAME clientname\]\]
2708///
2709/// Switches the connection's protocol and returns a map of server properties.
2710/// The response is returned as a raw `Frame` (map or array depending on the
2711/// negotiated protocol version).
2712#[derive(Clone)]
2713pub struct Hello {
2714    protover: Option<u8>,
2715    auth: Option<(String, CommandArg)>,
2716    setname: Option<String>,
2717}
2718
2719impl Hello {
2720    /// Create a new [`Hello`] command.
2721    pub fn new() -> Self {
2722        Self {
2723            protover: None,
2724            auth: None,
2725            setname: None,
2726        }
2727    }
2728
2729    /// Set the protocol version to negotiate.
2730    pub fn proto(mut self, version: u8) -> Self {
2731        self.protover = Some(version);
2732        self
2733    }
2734
2735    /// Authenticate while switching protocols.
2736    pub fn auth(mut self, username: impl Into<String>, password: impl Into<CommandArg>) -> Self {
2737        self.auth = Some((username.into(), password.into()));
2738        self
2739    }
2740
2741    /// Set the connection name.
2742    pub fn setname(mut self, name: impl Into<String>) -> Self {
2743        self.setname = Some(name.into());
2744        self
2745    }
2746}
2747
2748impl Default for Hello {
2749    fn default() -> Self {
2750        Self::new()
2751    }
2752}
2753
2754impl Command for Hello {
2755    type Response = Frame;
2756
2757    fn to_frame(&self) -> Frame {
2758        let mut args = vec![bulk("HELLO")];
2759        if let Some(version) = self.protover {
2760            args.push(bulk(version.to_string()));
2761        }
2762        if let Some((ref user, ref pass)) = self.auth {
2763            args.push(bulk("AUTH"));
2764            args.push(bulk(user.as_str()));
2765            args.push(bulk(pass));
2766        }
2767        if let Some(ref name) = self.setname {
2768            args.push(bulk("SETNAME"));
2769            args.push(bulk(name.as_str()));
2770        }
2771        array(args)
2772    }
2773
2774    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2775        Ok(frame)
2776    }
2777
2778    fn name(&self) -> &str {
2779        "HELLO"
2780    }
2781}
2782
2783/// RESET
2784///
2785/// Resets the connection to its initial state. Returns the simple string
2786/// `"RESET"`.
2787#[derive(Clone)]
2788pub struct Reset;
2789
2790impl Reset {
2791    /// Create a new [`Reset`] command.
2792    pub fn new() -> Self {
2793        Self
2794    }
2795}
2796
2797impl Default for Reset {
2798    fn default() -> Self {
2799        Self::new()
2800    }
2801}
2802
2803impl Command for Reset {
2804    type Response = String;
2805
2806    fn to_frame(&self) -> Frame {
2807        array(vec![bulk("RESET")])
2808    }
2809
2810    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2811        match frame {
2812            Frame::SimpleString(s) => Ok(String::from_utf8_lossy(&s).into_owned()),
2813            other => Err(RedisError::UnexpectedResponse {
2814                expected: "simple string",
2815                actual: format!("{other:?}"),
2816            }),
2817        }
2818    }
2819
2820    fn name(&self) -> &str {
2821        "RESET"
2822    }
2823}
2824
2825/// COMMAND INFO command-name \[command-name ...\]
2826///
2827/// Returns details about the specified commands. The response is a nested,
2828/// command-specific structure returned as a raw `Frame`.
2829#[derive(Clone)]
2830pub struct CommandInfo {
2831    commands: Vec<String>,
2832}
2833
2834impl CommandInfo {
2835    /// Create a new [`CommandInfo`] command.
2836    pub fn new(cmd: impl Into<String>) -> Self {
2837        Self {
2838            commands: vec![cmd.into()],
2839        }
2840    }
2841
2842    /// Add another command to query.
2843    pub fn command(mut self, c: impl Into<String>) -> Self {
2844        self.commands.push(c.into());
2845        self
2846    }
2847}
2848
2849impl Command for CommandInfo {
2850    type Response = Frame;
2851
2852    fn to_frame(&self) -> Frame {
2853        let mut args = vec![bulk("COMMAND"), bulk("INFO")];
2854        for c in &self.commands {
2855            args.push(bulk(c.as_str()));
2856        }
2857        array(args)
2858    }
2859
2860    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2861        Ok(frame)
2862    }
2863
2864    fn name(&self) -> &str {
2865        "COMMAND INFO"
2866    }
2867}
2868
2869/// COMMAND GETKEYS command \[arg ...\]
2870///
2871/// Returns the keys that would be accessed by the given command invocation.
2872#[derive(Clone)]
2873pub struct CommandGetKeys {
2874    command: String,
2875    args: Vec<CommandArg>,
2876}
2877
2878impl CommandGetKeys {
2879    /// Create a new [`CommandGetKeys`] command.
2880    pub fn new(cmd: impl Into<String>) -> Self {
2881        Self {
2882            command: cmd.into(),
2883            args: Vec::new(),
2884        }
2885    }
2886
2887    /// Add an argument to the command invocation being analyzed.
2888    pub fn arg(mut self, a: impl Into<CommandArg>) -> Self {
2889        self.args.push(a.into());
2890        self
2891    }
2892}
2893
2894impl Command for CommandGetKeys {
2895    type Response = Vec<Bytes>;
2896
2897    fn to_frame(&self) -> Frame {
2898        let mut args = vec![
2899            bulk("COMMAND"),
2900            bulk("GETKEYS"),
2901            bulk(self.command.as_str()),
2902        ];
2903        for a in &self.args {
2904            args.push(bulk(a));
2905        }
2906        array(args)
2907    }
2908
2909    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
2910        match frame {
2911            Frame::Array(Some(frames)) => frames
2912                .into_iter()
2913                .map(|f| match f {
2914                    Frame::BulkString(Some(data)) => Ok(data),
2915                    other => Err(RedisError::UnexpectedResponse {
2916                        expected: "bulk string",
2917                        actual: format!("{other:?}"),
2918                    }),
2919                })
2920                .collect(),
2921            other => Err(RedisError::UnexpectedResponse {
2922                expected: "array",
2923                actual: format!("{other:?}"),
2924            }),
2925        }
2926    }
2927
2928    fn name(&self) -> &str {
2929        "COMMAND GETKEYS"
2930    }
2931}
2932
2933/// One key and its access flags returned by [`CommandGetKeysAndFlags`].
2934#[derive(Debug, Clone, PartialEq, Eq)]
2935pub struct CommandKeyFlags {
2936    /// The binary-safe key extracted from the inspected command invocation.
2937    pub key: Bytes,
2938    /// Redis key-spec flags such as `RW`, `access`, `update`, or `delete`.
2939    pub flags: Vec<Bytes>,
2940}
2941
2942/// COMMAND GETKEYSANDFLAGS command \[arg \[arg ...\]\]
2943///
2944/// Asks Redis to extract both keys and key-access flags from an arbitrary
2945/// command invocation.
2946#[derive(Debug, Clone)]
2947pub struct CommandGetKeysAndFlags {
2948    command: Bytes,
2949    args: Vec<Bytes>,
2950}
2951
2952impl CommandGetKeysAndFlags {
2953    /// Create an inspection request for `command`.
2954    pub fn new(command: impl AsRef<[u8]>) -> Self {
2955        Self {
2956            command: Bytes::copy_from_slice(command.as_ref()),
2957            args: Vec::new(),
2958        }
2959    }
2960
2961    /// Append one binary-safe argument from the inspected invocation.
2962    pub fn arg(mut self, argument: impl AsRef<[u8]>) -> Self {
2963        self.args.push(Bytes::copy_from_slice(argument.as_ref()));
2964        self
2965    }
2966
2967    /// Append multiple binary-safe arguments from the inspected invocation.
2968    pub fn args<A, I>(mut self, arguments: I) -> Self
2969    where
2970        A: AsRef<[u8]>,
2971        I: IntoIterator<Item = A>,
2972    {
2973        self.args.extend(
2974            arguments
2975                .into_iter()
2976                .map(|argument| Bytes::copy_from_slice(argument.as_ref())),
2977        );
2978        self
2979    }
2980
2981    fn parse_bytes(frame: Frame) -> Result<Bytes, RedisError> {
2982        match frame {
2983            Frame::BulkString(Some(value)) | Frame::SimpleString(value) => Ok(value),
2984            other => Err(RedisError::UnexpectedResponse {
2985                expected: "bulk or simple string",
2986                actual: format!("{other:?}"),
2987            }),
2988        }
2989    }
2990
2991    fn parse_flags(frame: Frame) -> Result<Vec<Bytes>, RedisError> {
2992        let flags = match frame {
2993            Frame::Array(Some(flags)) | Frame::Set(flags) => flags,
2994            other => {
2995                return Err(RedisError::UnexpectedResponse {
2996                    expected: "array or set of flags",
2997                    actual: format!("{other:?}"),
2998                });
2999            }
3000        };
3001        flags.into_iter().map(Self::parse_bytes).collect()
3002    }
3003}
3004
3005impl Command for CommandGetKeysAndFlags {
3006    type Response = Vec<CommandKeyFlags>;
3007
3008    fn to_frame(&self) -> Frame {
3009        let mut args = vec![
3010            bulk("COMMAND"),
3011            bulk("GETKEYSANDFLAGS"),
3012            bulk(&self.command),
3013        ];
3014        args.extend(self.args.iter().map(bulk));
3015        array(args)
3016    }
3017
3018    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3019        let entries = match frame {
3020            Frame::Array(Some(entries)) => entries,
3021            Frame::Array(None) => return Ok(Vec::new()),
3022            other => {
3023                return Err(RedisError::UnexpectedResponse {
3024                    expected: "array of key/flag pairs",
3025                    actual: format!("{other:?}"),
3026                });
3027            }
3028        };
3029
3030        entries
3031            .into_iter()
3032            .map(|entry| {
3033                let mut fields = match entry {
3034                    Frame::Array(Some(fields)) if fields.len() == 2 => fields.into_iter(),
3035                    other => {
3036                        return Err(RedisError::UnexpectedResponse {
3037                            expected: "two-element key/flag array",
3038                            actual: format!("{other:?}"),
3039                        });
3040                    }
3041                };
3042                let key = Self::parse_bytes(fields.next().expect("length checked"))?;
3043                let flags = Self::parse_flags(fields.next().expect("length checked"))?;
3044                Ok(CommandKeyFlags { key, flags })
3045            })
3046            .collect()
3047    }
3048
3049    fn name(&self) -> &str {
3050        "COMMAND GETKEYSANDFLAGS"
3051    }
3052
3053    fn idempotent(&self) -> bool {
3054        true
3055    }
3056}
3057
3058/// Reply mode for CLIENT REPLY.
3059#[derive(Clone)]
3060pub enum ClientReplyMode {
3061    /// Select the `On` mode.
3062    On,
3063    /// Select the `Off` mode.
3064    Off,
3065    /// Select the `Skip` mode.
3066    Skip,
3067}
3068
3069impl ClientReplyMode {
3070    fn as_str(&self) -> &str {
3071        match self {
3072            Self::On => "ON",
3073            Self::Off => "OFF",
3074            Self::Skip => "SKIP",
3075        }
3076    }
3077}
3078
3079/// CLIENT REPLY ON|OFF|SKIP
3080///
3081/// Controls whether the server replies to commands from the current
3082/// connection.
3083#[derive(Clone)]
3084pub struct ClientReply {
3085    mode: ClientReplyMode,
3086}
3087
3088impl ClientReply {
3089    /// Create a new [`ClientReply`] command.
3090    pub fn new(mode: ClientReplyMode) -> Self {
3091        Self { mode }
3092    }
3093}
3094
3095impl Command for ClientReply {
3096    type Response = ();
3097
3098    fn to_frame(&self) -> Frame {
3099        array(vec![
3100            bulk("CLIENT"),
3101            bulk("REPLY"),
3102            bulk(self.mode.as_str()),
3103        ])
3104    }
3105
3106    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3107        match frame {
3108            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
3109            other => Err(RedisError::UnexpectedResponse {
3110                expected: "OK",
3111                actual: format!("{other:?}"),
3112            }),
3113        }
3114    }
3115
3116    fn name(&self) -> &str {
3117        "CLIENT REPLY"
3118    }
3119}
3120
3121/// CLIENT TRACKINGINFO
3122///
3123/// Returns information about the current connection's server-assisted
3124/// client-side caching state. Returned as a raw `Frame` map.
3125#[derive(Clone)]
3126pub struct ClientTrackingInfo;
3127
3128impl ClientTrackingInfo {
3129    /// Create a new [`ClientTrackingInfo`] command.
3130    pub fn new() -> Self {
3131        Self
3132    }
3133}
3134
3135impl Default for ClientTrackingInfo {
3136    fn default() -> Self {
3137        Self::new()
3138    }
3139}
3140
3141impl Command for ClientTrackingInfo {
3142    type Response = Frame;
3143
3144    fn to_frame(&self) -> Frame {
3145        array(vec![bulk("CLIENT"), bulk("TRACKINGINFO")])
3146    }
3147
3148    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3149        Ok(frame)
3150    }
3151
3152    fn name(&self) -> &str {
3153        "CLIENT TRACKINGINFO"
3154    }
3155}
3156
3157/// Mode for CLIENT UNBLOCK.
3158#[derive(Clone)]
3159pub enum UnblockMode {
3160    /// Select the `Timeout` mode.
3161    Timeout,
3162    /// Select the `Error` mode.
3163    Error,
3164}
3165
3166impl UnblockMode {
3167    fn as_str(&self) -> &str {
3168        match self {
3169            Self::Timeout => "TIMEOUT",
3170            Self::Error => "ERROR",
3171        }
3172    }
3173}
3174
3175/// CLIENT UNBLOCK client-id \[TIMEOUT | ERROR\]
3176///
3177/// Unblocks a different connection that is blocked in a blocking command.
3178/// Returns `1` if the client was unblocked, `0` otherwise.
3179#[derive(Clone)]
3180pub struct ClientUnblock {
3181    client_id: i64,
3182    mode: Option<UnblockMode>,
3183}
3184
3185impl ClientUnblock {
3186    /// Create a new [`ClientUnblock`] command.
3187    pub fn new(client_id: i64) -> Self {
3188        Self {
3189            client_id,
3190            mode: None,
3191        }
3192    }
3193
3194    /// Set the unblock mode (TIMEOUT or ERROR).
3195    pub fn mode(mut self, m: UnblockMode) -> Self {
3196        self.mode = Some(m);
3197        self
3198    }
3199}
3200
3201impl Command for ClientUnblock {
3202    type Response = i64;
3203
3204    fn to_frame(&self) -> Frame {
3205        let mut args = vec![
3206            bulk("CLIENT"),
3207            bulk("UNBLOCK"),
3208            bulk(self.client_id.to_string()),
3209        ];
3210        if let Some(ref mode) = self.mode {
3211            args.push(bulk(mode.as_str()));
3212        }
3213        array(args)
3214    }
3215
3216    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3217        match frame {
3218            Frame::Integer(n) => Ok(n),
3219            other => Err(RedisError::UnexpectedResponse {
3220                expected: "integer",
3221                actual: format!("{other:?}"),
3222            }),
3223        }
3224    }
3225
3226    fn name(&self) -> &str {
3227        "CLIENT UNBLOCK"
3228    }
3229}
3230
3231/// CLIENT CACHING YES|NO
3232///
3233/// Controls tracking of keys in the next command when client tracking is in
3234/// OPTIN or OPTOUT mode.
3235#[derive(Clone)]
3236pub struct ClientCaching {
3237    yes: bool,
3238}
3239
3240impl ClientCaching {
3241    /// Create a new [`ClientCaching`] command.
3242    pub fn new(yes: bool) -> Self {
3243        Self { yes }
3244    }
3245}
3246
3247impl Command for ClientCaching {
3248    type Response = ();
3249
3250    fn to_frame(&self) -> Frame {
3251        array(vec![
3252            bulk("CLIENT"),
3253            bulk("CACHING"),
3254            bulk(if self.yes { "yes" } else { "no" }),
3255        ])
3256    }
3257
3258    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3259        match frame {
3260            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
3261            other => Err(RedisError::UnexpectedResponse {
3262                expected: "OK",
3263                actual: format!("{other:?}"),
3264            }),
3265        }
3266    }
3267
3268    fn name(&self) -> &str {
3269        "CLIENT CACHING"
3270    }
3271}
3272
3273/// CLIENT GETREDIR
3274///
3275/// Returns the client ID this connection's client-side-caching invalidation
3276/// messages are redirected to. Returns `-1` when tracking is disabled and `0`
3277/// when no redirection is set.
3278#[derive(Clone)]
3279pub struct ClientGetRedir;
3280
3281impl ClientGetRedir {
3282    /// Create a new [`ClientGetRedir`] command.
3283    pub fn new() -> Self {
3284        Self
3285    }
3286}
3287
3288impl Default for ClientGetRedir {
3289    fn default() -> Self {
3290        Self::new()
3291    }
3292}
3293
3294impl Command for ClientGetRedir {
3295    type Response = i64;
3296
3297    fn to_frame(&self) -> Frame {
3298        array(vec![bulk("CLIENT"), bulk("GETREDIR")])
3299    }
3300
3301    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3302        match frame {
3303            Frame::Integer(n) => Ok(n),
3304            other => Err(RedisError::UnexpectedResponse {
3305                expected: "integer",
3306                actual: format!("{other:?}"),
3307            }),
3308        }
3309    }
3310
3311    fn name(&self) -> &str {
3312        "CLIENT GETREDIR"
3313    }
3314
3315    fn idempotent(&self) -> bool {
3316        true
3317    }
3318}
3319
3320/// Metrics collected by [`HotkeysStart`].
3321#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3322pub enum HotkeysMetrics {
3323    /// Track hotkeys by CPU time.
3324    Cpu,
3325    /// Track hotkeys by network bytes.
3326    Net,
3327    /// Track hotkeys by both CPU time and network bytes.
3328    CpuAndNet,
3329}
3330
3331/// HOTKEYS START METRICS count \[CPU\] \[NET\] \[COUNT k\]
3332/// \[DURATION seconds\] \[SAMPLE ratio\] \[SLOTS count slot \[slot ...\]\]
3333///
3334/// Starts a Redis 8.6+ hotkey tracking session. The metrics count and optional
3335/// slots count are calculated automatically from the typed options.
3336#[derive(Clone)]
3337pub struct HotkeysStart {
3338    metrics: HotkeysMetrics,
3339    count: Option<u8>,
3340    duration: Option<u32>,
3341    sample: Option<u32>,
3342    slots: Option<Vec<u16>>,
3343}
3344
3345impl HotkeysStart {
3346    /// Create a hotkey tracking command for the selected metrics.
3347    pub fn new(metrics: HotkeysMetrics) -> Self {
3348        Self {
3349            metrics,
3350            count: None,
3351            duration: None,
3352            sample: None,
3353            slots: None,
3354        }
3355    }
3356
3357    /// Set the maximum number of hotkeys returned for each metric.
3358    ///
3359    /// Redis accepts values from 1 through 64 and defaults to 10.
3360    pub fn count(mut self, count: u8) -> Self {
3361        self.count = Some(count);
3362        self
3363    }
3364
3365    /// Stop tracking automatically after this many seconds.
3366    ///
3367    /// Redis accepts values from 1 through 1,000,000. When omitted, tracking
3368    /// continues until [`HotkeysStop`] is executed.
3369    pub fn duration(mut self, seconds: u32) -> Self {
3370        self.duration = Some(seconds);
3371        self
3372    }
3373
3374    /// Sample each key with probability `1 / ratio`.
3375    ///
3376    /// Redis requires a positive ratio and defaults to 1 (every key).
3377    pub fn sample(mut self, ratio: u32) -> Self {
3378        self.sample = Some(ratio);
3379        self
3380    }
3381
3382    /// Restrict tracking to the supplied cluster hash slots.
3383    ///
3384    /// Redis only accepts this option in cluster mode. The slot count is
3385    /// calculated automatically.
3386    pub fn slots(mut self, slots: impl IntoIterator<Item = u16>) -> Self {
3387        self.slots = Some(slots.into_iter().collect());
3388        self
3389    }
3390}
3391
3392impl Command for HotkeysStart {
3393    type Response = ();
3394
3395    fn to_frame(&self) -> Frame {
3396        let mut args = vec![bulk("HOTKEYS"), bulk("START"), bulk("METRICS")];
3397        match self.metrics {
3398            HotkeysMetrics::Cpu => {
3399                args.push(bulk("1"));
3400                args.push(bulk("CPU"));
3401            }
3402            HotkeysMetrics::Net => {
3403                args.push(bulk("1"));
3404                args.push(bulk("NET"));
3405            }
3406            HotkeysMetrics::CpuAndNet => {
3407                args.push(bulk("2"));
3408                args.push(bulk("CPU"));
3409                args.push(bulk("NET"));
3410            }
3411        }
3412        if let Some(count) = self.count {
3413            args.push(bulk("COUNT"));
3414            args.push(bulk(count.to_string()));
3415        }
3416        if let Some(seconds) = self.duration {
3417            args.push(bulk("DURATION"));
3418            args.push(bulk(seconds.to_string()));
3419        }
3420        if let Some(ratio) = self.sample {
3421            args.push(bulk("SAMPLE"));
3422            args.push(bulk(ratio.to_string()));
3423        }
3424        if let Some(ref slots) = self.slots {
3425            args.push(bulk("SLOTS"));
3426            args.push(bulk(slots.len().to_string()));
3427            args.extend(slots.iter().map(|slot| bulk(slot.to_string())));
3428        }
3429        array(args)
3430    }
3431
3432    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3433        match frame {
3434            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
3435            other => Err(RedisError::UnexpectedResponse {
3436                expected: "OK",
3437                actual: format!("{other:?}"),
3438            }),
3439        }
3440    }
3441
3442    fn name(&self) -> &str {
3443        "HOTKEYS START"
3444    }
3445}
3446
3447/// HOTKEYS STOP
3448///
3449/// Stops hotkey tracking while preserving the collected data. Returns `true`
3450/// when an active session was stopped and `false` when no session was active.
3451#[derive(Clone)]
3452pub struct HotkeysStop;
3453
3454impl HotkeysStop {
3455    /// Create a new [`HotkeysStop`] command.
3456    pub fn new() -> Self {
3457        Self
3458    }
3459}
3460
3461impl Default for HotkeysStop {
3462    fn default() -> Self {
3463        Self::new()
3464    }
3465}
3466
3467impl Command for HotkeysStop {
3468    type Response = bool;
3469
3470    fn to_frame(&self) -> Frame {
3471        array(vec![bulk("HOTKEYS"), bulk("STOP")])
3472    }
3473
3474    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3475        match frame {
3476            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(true),
3477            Frame::Null | Frame::BulkString(None) | Frame::Array(None) => Ok(false),
3478            other => Err(RedisError::UnexpectedResponse {
3479                expected: "OK or null",
3480                actual: format!("{other:?}"),
3481            }),
3482        }
3483    }
3484
3485    fn name(&self) -> &str {
3486        "HOTKEYS STOP"
3487    }
3488}
3489
3490/// Inclusive Redis Cluster hash-slot range reported by [`HotkeysGet`].
3491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3492pub struct HotkeysSlotRange {
3493    /// First hash slot in the inclusive range.
3494    pub start: u16,
3495    /// Last hash slot in the inclusive range.
3496    pub end: u16,
3497}
3498
3499/// A key and its measured CPU time in microseconds.
3500#[derive(Debug, Clone, PartialEq, Eq)]
3501pub struct HotkeyCpuTime {
3502    /// Sampled key.
3503    pub key: Bytes,
3504    /// CPU time attributed to the key, in microseconds.
3505    pub microseconds: i64,
3506}
3507
3508/// A key and its measured network traffic in bytes.
3509#[derive(Debug, Clone, PartialEq, Eq)]
3510pub struct HotkeyNetBytes {
3511    /// Sampled key.
3512    pub key: Bytes,
3513    /// Network traffic attributed to the key, in bytes.
3514    pub bytes: i64,
3515}
3516
3517/// Statistics for one node in a [`HotkeysGet`] response.
3518///
3519/// Metric-specific and cluster-selection fields are `None` when the
3520/// corresponding START option was not enabled.
3521#[derive(Debug, Clone, PartialEq, Eq)]
3522pub struct HotkeysStats {
3523    /// Whether the server is currently collecting hot-key samples.
3524    pub tracking_active: bool,
3525    /// Configured command-sampling ratio.
3526    pub sample_ratio: i64,
3527    /// Cluster hash-slot ranges included in collection.
3528    pub selected_slots: Vec<HotkeysSlotRange>,
3529    /// CPU time for sampled commands in selected slots, in microseconds.
3530    pub sampled_commands_selected_slots_us: Option<i64>,
3531    /// CPU time for all commands in selected slots, in microseconds.
3532    pub all_commands_selected_slots_us: Option<i64>,
3533    /// CPU time for all commands in all slots, in microseconds.
3534    pub all_commands_all_slots_us: i64,
3535    /// Network bytes for sampled commands in selected slots.
3536    pub net_bytes_sampled_commands_selected_slots: Option<i64>,
3537    /// Network bytes for all commands in selected slots.
3538    pub net_bytes_all_commands_selected_slots: Option<i64>,
3539    /// Network bytes for all commands in all slots.
3540    pub net_bytes_all_commands_all_slots: i64,
3541    /// Collection start time as Unix epoch milliseconds.
3542    pub collection_start_time_unix_ms: i64,
3543    /// Elapsed collection time in milliseconds.
3544    pub collection_duration_ms: i64,
3545    /// Total user-mode CPU time, in milliseconds, when requested.
3546    pub total_cpu_time_user_ms: Option<i64>,
3547    /// Total system-mode CPU time, in milliseconds, when requested.
3548    pub total_cpu_time_sys_ms: Option<i64>,
3549    /// Total network traffic, in bytes, when requested.
3550    pub total_net_bytes: Option<i64>,
3551    /// Sampled keys ordered by attributed CPU time, when requested.
3552    pub by_cpu_time_us: Option<Vec<HotkeyCpuTime>>,
3553    /// Sampled keys ordered by attributed network traffic, when requested.
3554    pub by_net_bytes: Option<Vec<HotkeyNetBytes>>,
3555}
3556
3557/// HOTKEYS GET
3558///
3559/// Returns the current or most recent Redis 8.6+ hotkey tracking results.
3560/// Redis wraps each node's statistics in an outer array so aggregated servers
3561/// can return multiple entries. A null reply means no session has been started
3562/// or the previous data was reset.
3563#[derive(Clone)]
3564pub struct HotkeysGet;
3565
3566impl HotkeysGet {
3567    /// Create a new [`HotkeysGet`] command.
3568    pub fn new() -> Self {
3569        Self
3570    }
3571}
3572
3573impl Default for HotkeysGet {
3574    fn default() -> Self {
3575        Self::new()
3576    }
3577}
3578
3579impl Command for HotkeysGet {
3580    type Response = Option<Vec<HotkeysStats>>;
3581
3582    fn to_frame(&self) -> Frame {
3583        array(vec![bulk("HOTKEYS"), bulk("GET")])
3584    }
3585
3586    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3587        parse_hotkeys_results(frame)
3588    }
3589
3590    fn name(&self) -> &str {
3591        "HOTKEYS GET"
3592    }
3593
3594    fn idempotent(&self) -> bool {
3595        true
3596    }
3597}
3598
3599/// HOTKEYS RESET
3600///
3601/// Releases the resources used for hotkey tracking. Redis requires an active
3602/// session to be stopped first.
3603#[derive(Clone)]
3604pub struct HotkeysReset;
3605
3606impl HotkeysReset {
3607    /// Create a new [`HotkeysReset`] command.
3608    pub fn new() -> Self {
3609        Self
3610    }
3611}
3612
3613impl Default for HotkeysReset {
3614    fn default() -> Self {
3615        Self::new()
3616    }
3617}
3618
3619impl Command for HotkeysReset {
3620    type Response = ();
3621
3622    fn to_frame(&self) -> Frame {
3623        array(vec![bulk("HOTKEYS"), bulk("RESET")])
3624    }
3625
3626    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3627        match frame {
3628            Frame::SimpleString(s) if &s[..] == b"OK" => Ok(()),
3629            other => Err(RedisError::UnexpectedResponse {
3630                expected: "OK",
3631                actual: format!("{other:?}"),
3632            }),
3633        }
3634    }
3635
3636    fn name(&self) -> &str {
3637        "HOTKEYS RESET"
3638    }
3639}
3640
3641/// HOTKEYS HELP
3642///
3643/// Returns helpful text describing the Redis 8.6.1+ HOTKEYS subcommands.
3644#[derive(Clone)]
3645pub struct HotkeysHelp;
3646
3647impl HotkeysHelp {
3648    /// Create a new [`HotkeysHelp`] command.
3649    pub fn new() -> Self {
3650        Self
3651    }
3652}
3653
3654impl Default for HotkeysHelp {
3655    fn default() -> Self {
3656        Self::new()
3657    }
3658}
3659
3660impl Command for HotkeysHelp {
3661    type Response = Vec<Bytes>;
3662
3663    fn to_frame(&self) -> Frame {
3664        array(vec![bulk("HOTKEYS"), bulk("HELP")])
3665    }
3666
3667    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
3668        crate::help::parse_help_lines(frame)
3669    }
3670
3671    fn name(&self) -> &str {
3672        "HOTKEYS HELP"
3673    }
3674
3675    fn idempotent(&self) -> bool {
3676        true
3677    }
3678}
3679
3680fn parse_hotkeys_results(frame: Frame) -> Result<Option<Vec<HotkeysStats>>, RedisError> {
3681    let results = match frame {
3682        Frame::Null | Frame::BulkString(None) | Frame::Array(None) => return Ok(None),
3683        Frame::Array(Some(results)) => results,
3684        other => {
3685            return Err(RedisError::UnexpectedResponse {
3686                expected: "array of HOTKEYS results or null",
3687                actual: format!("{other:?}"),
3688            });
3689        }
3690    };
3691
3692    results
3693        .iter()
3694        .map(parse_hotkeys_stats)
3695        .collect::<Result<Vec<_>, _>>()
3696        .map(Some)
3697}
3698
3699fn parse_hotkeys_stats(frame: &Frame) -> Result<HotkeysStats, RedisError> {
3700    let fields = hotkeys_field_pairs(frame)?;
3701
3702    let mut tracking_active = None;
3703    let mut sample_ratio = None;
3704    let mut selected_slots = None;
3705    let mut sampled_commands_selected_slots_us = None;
3706    let mut all_commands_selected_slots_us = None;
3707    let mut all_commands_all_slots_us = None;
3708    let mut net_bytes_sampled_commands_selected_slots = None;
3709    let mut net_bytes_all_commands_selected_slots = None;
3710    let mut net_bytes_all_commands_all_slots = None;
3711    let mut collection_start_time_unix_ms = None;
3712    let mut collection_duration_ms = None;
3713    let mut total_cpu_time_user_ms = None;
3714    let mut total_cpu_time_sys_ms = None;
3715    let mut total_net_bytes = None;
3716    let mut by_cpu_time_us = None;
3717    let mut by_net_bytes = None;
3718
3719    for (field, value) in fields {
3720        let name = hotkeys_bytes(field, "HOTKEYS field name")?;
3721        match &name[..] {
3722            b"tracking-active" => {
3723                tracking_active = Some(match hotkeys_integer(value, "tracking-active integer")? {
3724                    0 => false,
3725                    1 => true,
3726                    other => {
3727                        return Err(RedisError::UnexpectedResponse {
3728                            expected: "tracking-active integer 0 or 1",
3729                            actual: other.to_string(),
3730                        });
3731                    }
3732                });
3733            }
3734            b"sample-ratio" => sample_ratio = Some(hotkeys_integer(value, "sample-ratio integer")?),
3735            b"selected-slots" => selected_slots = Some(parse_hotkeys_slots(value)?),
3736            // Redis 8.6.0 used the singular "command"; later patches fixed
3737            // the response field to match the documented plural spelling.
3738            b"sampled-command-selected-slots-us" | b"sampled-commands-selected-slots-us" => {
3739                sampled_commands_selected_slots_us = Some(hotkeys_integer(
3740                    value,
3741                    "sampled-commands-selected-slots-us integer",
3742                )?)
3743            }
3744            b"all-commands-selected-slots-us" => {
3745                all_commands_selected_slots_us = Some(hotkeys_integer(
3746                    value,
3747                    "all-commands-selected-slots-us integer",
3748                )?)
3749            }
3750            b"all-commands-all-slots-us" => {
3751                all_commands_all_slots_us =
3752                    Some(hotkeys_integer(value, "all-commands-all-slots-us integer")?)
3753            }
3754            b"net-bytes-sampled-commands-selected-slots" => {
3755                net_bytes_sampled_commands_selected_slots = Some(hotkeys_integer(
3756                    value,
3757                    "net-bytes-sampled-commands-selected-slots integer",
3758                )?)
3759            }
3760            b"net-bytes-all-commands-selected-slots" => {
3761                net_bytes_all_commands_selected_slots = Some(hotkeys_integer(
3762                    value,
3763                    "net-bytes-all-commands-selected-slots integer",
3764                )?)
3765            }
3766            b"net-bytes-all-commands-all-slots" => {
3767                net_bytes_all_commands_all_slots = Some(hotkeys_integer(
3768                    value,
3769                    "net-bytes-all-commands-all-slots integer",
3770                )?)
3771            }
3772            b"collection-start-time-unix-ms" => {
3773                collection_start_time_unix_ms = Some(hotkeys_integer(
3774                    value,
3775                    "collection-start-time-unix-ms integer",
3776                )?)
3777            }
3778            b"collection-duration-ms" => {
3779                collection_duration_ms =
3780                    Some(hotkeys_integer(value, "collection-duration-ms integer")?)
3781            }
3782            b"total-cpu-time-user-ms" => {
3783                total_cpu_time_user_ms =
3784                    Some(hotkeys_integer(value, "total-cpu-time-user-ms integer")?)
3785            }
3786            b"total-cpu-time-sys-ms" => {
3787                total_cpu_time_sys_ms =
3788                    Some(hotkeys_integer(value, "total-cpu-time-sys-ms integer")?)
3789            }
3790            b"total-net-bytes" => {
3791                total_net_bytes = Some(hotkeys_integer(value, "total-net-bytes integer")?)
3792            }
3793            b"by-cpu-time-us" => {
3794                by_cpu_time_us = Some(
3795                    parse_hotkey_measurements(value, "by-cpu-time-us array")?
3796                        .into_iter()
3797                        .map(|(key, microseconds)| HotkeyCpuTime { key, microseconds })
3798                        .collect(),
3799                )
3800            }
3801            b"by-net-bytes" => {
3802                by_net_bytes = Some(
3803                    parse_hotkey_measurements(value, "by-net-bytes array")?
3804                        .into_iter()
3805                        .map(|(key, bytes)| HotkeyNetBytes { key, bytes })
3806                        .collect(),
3807                )
3808            }
3809            _ => {}
3810        }
3811    }
3812
3813    Ok(HotkeysStats {
3814        tracking_active: required_hotkeys_field(tracking_active, "tracking-active")?,
3815        sample_ratio: required_hotkeys_field(sample_ratio, "sample-ratio")?,
3816        selected_slots: required_hotkeys_field(selected_slots, "selected-slots")?,
3817        sampled_commands_selected_slots_us,
3818        all_commands_selected_slots_us,
3819        all_commands_all_slots_us: required_hotkeys_field(
3820            all_commands_all_slots_us,
3821            "all-commands-all-slots-us",
3822        )?,
3823        net_bytes_sampled_commands_selected_slots,
3824        net_bytes_all_commands_selected_slots,
3825        net_bytes_all_commands_all_slots: required_hotkeys_field(
3826            net_bytes_all_commands_all_slots,
3827            "net-bytes-all-commands-all-slots",
3828        )?,
3829        collection_start_time_unix_ms: required_hotkeys_field(
3830            collection_start_time_unix_ms,
3831            "collection-start-time-unix-ms",
3832        )?,
3833        collection_duration_ms: required_hotkeys_field(
3834            collection_duration_ms,
3835            "collection-duration-ms",
3836        )?,
3837        total_cpu_time_user_ms,
3838        total_cpu_time_sys_ms,
3839        total_net_bytes,
3840        by_cpu_time_us,
3841        by_net_bytes,
3842    })
3843}
3844
3845fn hotkeys_field_pairs(frame: &Frame) -> Result<Vec<(&Frame, &Frame)>, RedisError> {
3846    match frame {
3847        Frame::Map(pairs) => Ok(pairs.iter().map(|(key, value)| (key, value)).collect()),
3848        Frame::Array(Some(items)) => {
3849            if items.len() % 2 != 0 {
3850                return Err(RedisError::UnexpectedResponse {
3851                    expected: "even number of HOTKEYS field-value elements",
3852                    actual: format!("{} elements", items.len()),
3853                });
3854            }
3855            Ok(items
3856                .as_chunks::<2>()
3857                .0
3858                .iter()
3859                .map(|pair| (&pair[0], &pair[1]))
3860                .collect())
3861        }
3862        other => Err(RedisError::UnexpectedResponse {
3863            expected: "HOTKEYS field-value array or map",
3864            actual: format!("{other:?}"),
3865        }),
3866    }
3867}
3868
3869fn parse_hotkeys_slots(frame: &Frame) -> Result<Vec<HotkeysSlotRange>, RedisError> {
3870    let ranges = match frame {
3871        Frame::Array(Some(ranges)) => ranges,
3872        other => {
3873            return Err(RedisError::UnexpectedResponse {
3874                expected: "array of HOTKEYS slot ranges",
3875                actual: format!("{other:?}"),
3876            });
3877        }
3878    };
3879
3880    ranges
3881        .iter()
3882        .map(|range| {
3883            let values = match range {
3884                Frame::Array(Some(values)) if matches!(values.len(), 1 | 2) => values,
3885                other => {
3886                    return Err(RedisError::UnexpectedResponse {
3887                        expected: "one- or two-integer HOTKEYS slot range",
3888                        actual: format!("{other:?}"),
3889                    });
3890                }
3891            };
3892            let start = hotkeys_slot(&values[0])?;
3893            let end = if values.len() == 2 {
3894                hotkeys_slot(&values[1])?
3895            } else {
3896                start
3897            };
3898            Ok(HotkeysSlotRange { start, end })
3899        })
3900        .collect()
3901}
3902
3903fn hotkeys_slot(frame: &Frame) -> Result<u16, RedisError> {
3904    match frame {
3905        Frame::Integer(slot) if (0..=16_383).contains(slot) => Ok(*slot as u16),
3906        other => Err(RedisError::UnexpectedResponse {
3907            expected: "Redis Cluster slot integer from 0 through 16383",
3908            actual: format!("{other:?}"),
3909        }),
3910    }
3911}
3912
3913fn parse_hotkey_measurements(
3914    frame: &Frame,
3915    expected: &'static str,
3916) -> Result<Vec<(Bytes, i64)>, RedisError> {
3917    let items = match frame {
3918        Frame::Array(Some(items)) => items,
3919        other => {
3920            return Err(RedisError::UnexpectedResponse {
3921                expected,
3922                actual: format!("{other:?}"),
3923            });
3924        }
3925    };
3926    if items.len() % 2 != 0 {
3927        return Err(RedisError::UnexpectedResponse {
3928            expected: "even number of HOTKEYS key-measurement elements",
3929            actual: format!("{} elements", items.len()),
3930        });
3931    }
3932
3933    items
3934        .as_chunks::<2>()
3935        .0
3936        .iter()
3937        .map(|pair| {
3938            Ok((
3939                hotkeys_bytes(&pair[0], "HOTKEYS key")?,
3940                hotkeys_integer(&pair[1], "HOTKEYS measurement integer")?,
3941            ))
3942        })
3943        .collect()
3944}
3945
3946fn hotkeys_bytes(frame: &Frame, expected: &'static str) -> Result<Bytes, RedisError> {
3947    match frame {
3948        Frame::BulkString(Some(bytes)) | Frame::SimpleString(bytes) => Ok(bytes.clone()),
3949        other => Err(RedisError::UnexpectedResponse {
3950            expected,
3951            actual: format!("{other:?}"),
3952        }),
3953    }
3954}
3955
3956fn hotkeys_integer(frame: &Frame, expected: &'static str) -> Result<i64, RedisError> {
3957    match frame {
3958        Frame::Integer(value) => Ok(*value),
3959        other => Err(RedisError::UnexpectedResponse {
3960            expected,
3961            actual: format!("{other:?}"),
3962        }),
3963    }
3964}
3965
3966fn required_hotkeys_field<T>(value: Option<T>, field: &'static str) -> Result<T, RedisError> {
3967    value.ok_or_else(|| RedisError::UnexpectedResponse {
3968        expected: field,
3969        actual: "missing HOTKEYS field".to_string(),
3970    })
3971}
3972
3973/// CLIENT HELP
3974///
3975/// Returns helpful text describing the CLIENT subcommands.
3976#[derive(Clone)]
3977pub struct ClientHelp;
3978
3979impl ClientHelp {
3980    /// Create a new [`ClientHelp`] command.
3981    pub fn new() -> Self {
3982        Self
3983    }
3984}
3985
3986impl Default for ClientHelp {
3987    fn default() -> Self {
3988        Self::new()
3989    }
3990}
3991
3992impl Command for ClientHelp {
3993    type Response = Vec<Bytes>;
3994
3995    fn to_frame(&self) -> Frame {
3996        array(vec![bulk("CLIENT"), bulk("HELP")])
3997    }
3998
3999    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
4000        crate::help::parse_help_lines(frame)
4001    }
4002
4003    fn name(&self) -> &str {
4004        "CLIENT HELP"
4005    }
4006
4007    fn idempotent(&self) -> bool {
4008        true
4009    }
4010}
4011
4012/// COMMAND HELP
4013///
4014/// Returns helpful text describing the COMMAND subcommands.
4015#[derive(Clone)]
4016pub struct CommandHelp;
4017
4018impl CommandHelp {
4019    /// Create a new [`CommandHelp`] command.
4020    pub fn new() -> Self {
4021        Self
4022    }
4023}
4024
4025impl Default for CommandHelp {
4026    fn default() -> Self {
4027        Self::new()
4028    }
4029}
4030
4031impl Command for CommandHelp {
4032    type Response = Vec<Bytes>;
4033
4034    fn to_frame(&self) -> Frame {
4035        array(vec![bulk("COMMAND"), bulk("HELP")])
4036    }
4037
4038    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
4039        crate::help::parse_help_lines(frame)
4040    }
4041
4042    fn name(&self) -> &str {
4043        "COMMAND HELP"
4044    }
4045
4046    fn idempotent(&self) -> bool {
4047        true
4048    }
4049}
4050
4051/// CONFIG HELP
4052///
4053/// Returns helpful text describing the CONFIG subcommands.
4054#[derive(Clone)]
4055pub struct ConfigHelp;
4056
4057impl ConfigHelp {
4058    /// Create a new [`ConfigHelp`] command.
4059    pub fn new() -> Self {
4060        Self
4061    }
4062}
4063
4064impl Default for ConfigHelp {
4065    fn default() -> Self {
4066        Self::new()
4067    }
4068}
4069
4070impl Command for ConfigHelp {
4071    type Response = Vec<Bytes>;
4072
4073    fn to_frame(&self) -> Frame {
4074        array(vec![bulk("CONFIG"), bulk("HELP")])
4075    }
4076
4077    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
4078        crate::help::parse_help_lines(frame)
4079    }
4080
4081    fn name(&self) -> &str {
4082        "CONFIG HELP"
4083    }
4084
4085    fn idempotent(&self) -> bool {
4086        true
4087    }
4088}
4089
4090/// MODULE HELP
4091///
4092/// Returns helpful text describing the MODULE subcommands.
4093#[derive(Clone)]
4094pub struct ModuleHelp;
4095
4096impl ModuleHelp {
4097    /// Create a new [`ModuleHelp`] command.
4098    pub fn new() -> Self {
4099        Self
4100    }
4101}
4102
4103impl Default for ModuleHelp {
4104    fn default() -> Self {
4105        Self::new()
4106    }
4107}
4108
4109impl Command for ModuleHelp {
4110    type Response = Vec<Bytes>;
4111
4112    fn to_frame(&self) -> Frame {
4113        array(vec![bulk("MODULE"), bulk("HELP")])
4114    }
4115
4116    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
4117        crate::help::parse_help_lines(frame)
4118    }
4119
4120    fn name(&self) -> &str {
4121        "MODULE HELP"
4122    }
4123
4124    fn idempotent(&self) -> bool {
4125        true
4126    }
4127}
4128
4129/// LOLWUT \[VERSION version\]
4130///
4131/// Returns the Redis version and, depending on the server, a piece of
4132/// generative art rendered as text. Primarily a fun diagnostic that also
4133/// reports the server version string.
4134#[derive(Clone)]
4135pub struct Lolwut {
4136    version: Option<u32>,
4137}
4138
4139impl Lolwut {
4140    /// Create a new [`Lolwut`] command.
4141    pub fn new() -> Self {
4142        Self { version: None }
4143    }
4144
4145    /// Request a specific art version via the `VERSION` argument.
4146    pub fn version(mut self, version: u32) -> Self {
4147        self.version = Some(version);
4148        self
4149    }
4150}
4151
4152impl Default for Lolwut {
4153    fn default() -> Self {
4154        Self::new()
4155    }
4156}
4157
4158impl Command for Lolwut {
4159    type Response = String;
4160
4161    fn to_frame(&self) -> Frame {
4162        let mut args = vec![bulk("LOLWUT")];
4163        if let Some(version) = self.version {
4164            args.push(bulk("VERSION"));
4165            args.push(bulk(version.to_string()));
4166        }
4167        array(args)
4168    }
4169
4170    fn parse_response(&self, frame: Frame) -> Result<Self::Response, RedisError> {
4171        match frame {
4172            // RESP3 returns LOLWUT as a verbatim string.
4173            Frame::BulkString(Some(s)) | Frame::VerbatimString(_, s) => {
4174                Ok(String::from_utf8_lossy(&s).into_owned())
4175            }
4176            other => Err(RedisError::UnexpectedResponse {
4177                expected: "bulk or verbatim string",
4178                actual: format!("{other:?}"),
4179            }),
4180        }
4181    }
4182
4183    fn name(&self) -> &str {
4184        "LOLWUT"
4185    }
4186
4187    fn idempotent(&self) -> bool {
4188        true
4189    }
4190}
4191
4192#[cfg(test)]
4193mod tests {
4194    use super::*;
4195    use redis_tower_core::Command;
4196    use redis_tower_protocol::Frame;
4197    use redis_tower_protocol::helpers::{array, bulk};
4198
4199    // -- Ping --
4200
4201    #[test]
4202    fn ping_no_message_to_frame() {
4203        let cmd = Ping::new();
4204        assert_eq!(cmd.to_frame(), array(vec![bulk("PING")]));
4205    }
4206
4207    #[test]
4208    fn ping_with_message_to_frame() {
4209        let cmd = Ping::with_message("hello");
4210        assert_eq!(cmd.to_frame(), array(vec![bulk("PING"), bulk("hello")]));
4211    }
4212
4213    #[test]
4214    fn ping_parse_pong() {
4215        let cmd = Ping::new();
4216        let frame = Frame::SimpleString(Bytes::from("PONG"));
4217        assert_eq!(cmd.parse_response(frame).unwrap(), "PONG");
4218    }
4219
4220    #[test]
4221    fn ping_parse_bulk_string() {
4222        let cmd = Ping::with_message("hello");
4223        let frame = Frame::BulkString(Some(Bytes::from("hello")));
4224        assert_eq!(cmd.parse_response(frame).unwrap(), "hello");
4225    }
4226
4227    #[test]
4228    fn ping_parse_error_on_integer() {
4229        let cmd = Ping::new();
4230        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
4231    }
4232
4233    // -- Monitor --
4234
4235    #[test]
4236    fn monitor_to_frame_parse_and_metadata() {
4237        let cmd = Monitor::new();
4238        assert_eq!(cmd.to_frame(), array(vec![bulk("MONITOR")]));
4239        assert_eq!(cmd.name(), "MONITOR");
4240        assert!(cmd.is_blocking());
4241        assert!(!cmd.idempotent());
4242        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
4243            .unwrap();
4244        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
4245    }
4246
4247    // -- FlushDb --
4248
4249    #[test]
4250    fn flushdb_to_frame() {
4251        let cmd = FlushDb::new();
4252        assert_eq!(cmd.to_frame(), array(vec![bulk("FLUSHDB")]));
4253    }
4254
4255    #[test]
4256    fn flushdb_async_to_frame() {
4257        let cmd = FlushDb::new().async_mode();
4258        assert_eq!(cmd.to_frame(), array(vec![bulk("FLUSHDB"), bulk("ASYNC")]));
4259    }
4260
4261    #[test]
4262    fn flushdb_sync_to_frame() {
4263        let cmd = FlushDb::new().sync_mode();
4264        assert_eq!(cmd.to_frame(), array(vec![bulk("FLUSHDB"), bulk("SYNC")]));
4265    }
4266
4267    #[test]
4268    fn flushdb_parse_ok() {
4269        let cmd = FlushDb::new();
4270        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
4271            .unwrap();
4272    }
4273
4274    #[test]
4275    fn flushdb_parse_error_on_integer() {
4276        let cmd = FlushDb::new();
4277        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
4278    }
4279
4280    // -- DbSize --
4281
4282    #[test]
4283    fn dbsize_to_frame() {
4284        let cmd = DbSize::new();
4285        assert_eq!(cmd.to_frame(), array(vec![bulk("DBSIZE")]));
4286    }
4287
4288    #[test]
4289    fn dbsize_parse_integer() {
4290        let cmd = DbSize::new();
4291        assert_eq!(cmd.parse_response(Frame::Integer(42)).unwrap(), 42);
4292    }
4293
4294    // -- Select --
4295
4296    #[test]
4297    fn select_to_frame() {
4298        let cmd = Select::new(3);
4299        assert_eq!(cmd.to_frame(), array(vec![bulk("SELECT"), bulk("3")]));
4300    }
4301
4302    // -- Auth --
4303
4304    #[test]
4305    fn auth_password_to_frame() {
4306        let cmd = Auth::password("secret");
4307        assert_eq!(cmd.to_frame(), array(vec![bulk("AUTH"), bulk("secret")]));
4308    }
4309
4310    #[test]
4311    fn auth_credentials_to_frame() {
4312        let cmd = Auth::credentials("user", "pass");
4313        assert_eq!(
4314            cmd.to_frame(),
4315            array(vec![bulk("AUTH"), bulk("user"), bulk("pass")])
4316        );
4317    }
4318
4319    // -- Info --
4320
4321    #[test]
4322    fn info_no_section_to_frame() {
4323        let cmd = Info::new();
4324        assert_eq!(cmd.to_frame(), array(vec![bulk("INFO")]));
4325    }
4326
4327    #[test]
4328    fn info_with_section_to_frame() {
4329        let cmd = Info::new().section("memory");
4330        assert_eq!(cmd.to_frame(), array(vec![bulk("INFO"), bulk("memory")]));
4331    }
4332
4333    #[test]
4334    fn info_parse_bulk_string() {
4335        let cmd = Info::new();
4336        let frame = Frame::BulkString(Some(Bytes::from("# Server\nredis_version:7.0\n")));
4337        let result = cmd.parse_response(frame).unwrap();
4338        assert!(result.contains("redis_version"));
4339    }
4340
4341    #[test]
4342    fn info_parse_error_on_integer() {
4343        let cmd = Info::new();
4344        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
4345    }
4346
4347    #[test]
4348    fn info_parse_verbatim_string_resp3() {
4349        // Under RESP3 INFO comes back as a verbatim string (=...txt:...).
4350        let cmd = Info::new();
4351        let frame = Frame::VerbatimString(
4352            Bytes::from("txt"),
4353            Bytes::from("# Server\nredis_version:7.4\n"),
4354        );
4355        let result = cmd.parse_response(frame).unwrap();
4356        assert!(result.contains("redis_version"));
4357    }
4358
4359    #[test]
4360    fn command_docs_parse_map_resp3() {
4361        // Under RESP3 COMMAND DOCS comes back as a map; it flattens to the
4362        // RESP2 key/value array shape.
4363        let cmd = CommandDocs::new().command("get");
4364        let frame = Frame::Map(vec![(bulk("get"), Frame::Array(Some(vec![])))]);
4365        let out = cmd.parse_response(frame).unwrap();
4366        assert_eq!(out.len(), 2);
4367        assert_eq!(out[0], bulk("get"));
4368    }
4369
4370    #[test]
4371    fn client_info_parse_verbatim_string_resp3() {
4372        let cmd = ClientInfo;
4373        let frame = Frame::VerbatimString(Bytes::from("txt"), Bytes::from("id=3 addr=127.0.0.1"));
4374        let out = cmd.parse_response(frame).unwrap();
4375        assert_eq!(&out[..], b"id=3 addr=127.0.0.1");
4376    }
4377
4378    #[test]
4379    fn client_list_parse_verbatim_string_resp3() {
4380        let cmd = ClientList::new();
4381        let frame = Frame::VerbatimString(Bytes::from("txt"), Bytes::from("id=3 addr=127.0.0.1\n"));
4382        let out = cmd.parse_response(frame).unwrap();
4383        assert_eq!(&out[..], b"id=3 addr=127.0.0.1\n");
4384    }
4385
4386    // -- ClientId --
4387
4388    #[test]
4389    fn client_id_to_frame() {
4390        let cmd = ClientId::new();
4391        assert_eq!(cmd.to_frame(), array(vec![bulk("CLIENT"), bulk("ID")]));
4392    }
4393
4394    #[test]
4395    fn client_id_parse_integer() {
4396        let cmd = ClientId::new();
4397        assert_eq!(cmd.parse_response(Frame::Integer(42)).unwrap(), 42);
4398    }
4399
4400    // -- ClientGetName --
4401
4402    #[test]
4403    fn client_getname_to_frame() {
4404        let cmd = ClientGetName::new();
4405        assert_eq!(cmd.to_frame(), array(vec![bulk("CLIENT"), bulk("GETNAME")]));
4406    }
4407
4408    #[test]
4409    fn client_getname_parse_name() {
4410        let cmd = ClientGetName::new();
4411        let frame = Frame::BulkString(Some(Bytes::from("myconn")));
4412        assert_eq!(
4413            cmd.parse_response(frame).unwrap(),
4414            Some(Bytes::from("myconn"))
4415        );
4416    }
4417
4418    #[test]
4419    fn client_getname_parse_null() {
4420        let cmd = ClientGetName::new();
4421        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
4422    }
4423
4424    // -- ClientSetName --
4425
4426    #[test]
4427    fn client_setname_to_frame() {
4428        let cmd = ClientSetName::new("myconn");
4429        assert_eq!(
4430            cmd.to_frame(),
4431            array(vec![bulk("CLIENT"), bulk("SETNAME"), bulk("myconn")])
4432        );
4433    }
4434
4435    // -- ConfigGet --
4436
4437    #[test]
4438    fn config_get_to_frame() {
4439        let cmd = ConfigGet::new("maxmemory");
4440        assert_eq!(
4441            cmd.to_frame(),
4442            array(vec![bulk("CONFIG"), bulk("GET"), bulk("maxmemory")])
4443        );
4444    }
4445
4446    #[test]
4447    fn config_get_parse_flat_array() {
4448        let cmd = ConfigGet::new("maxmemory");
4449        let frame = array(vec![
4450            Frame::BulkString(Some(Bytes::from("maxmemory"))),
4451            Frame::BulkString(Some(Bytes::from("0"))),
4452        ]);
4453        let result = cmd.parse_response(frame).unwrap();
4454        assert_eq!(result, vec![(Bytes::from("maxmemory"), Bytes::from("0"))]);
4455    }
4456
4457    #[test]
4458    fn config_get_parse_error_on_odd_array() {
4459        let cmd = ConfigGet::new("*");
4460        let frame = array(vec![Frame::BulkString(Some(Bytes::from("only_one")))]);
4461        assert!(cmd.parse_response(frame).is_err());
4462    }
4463
4464    // -- ConfigSet --
4465
4466    #[test]
4467    fn config_set_to_frame() {
4468        let cmd = ConfigSet::new("hz", "100");
4469        assert_eq!(
4470            cmd.to_frame(),
4471            array(vec![bulk("CONFIG"), bulk("SET"), bulk("hz"), bulk("100")])
4472        );
4473    }
4474
4475    #[test]
4476    fn config_set_parse_ok() {
4477        let cmd = ConfigSet::new("hz", "100");
4478        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
4479            .unwrap();
4480    }
4481
4482    // -- Time --
4483
4484    #[test]
4485    fn time_to_frame() {
4486        let cmd = Time::new();
4487        assert_eq!(cmd.to_frame(), array(vec![bulk("TIME")]));
4488    }
4489
4490    #[test]
4491    fn time_parse_response() {
4492        let cmd = Time::new();
4493        let frame = array(vec![
4494            Frame::BulkString(Some(Bytes::from("1700000000"))),
4495            Frame::BulkString(Some(Bytes::from("123456"))),
4496        ]);
4497        let (secs, micros) = cmd.parse_response(frame).unwrap();
4498        assert_eq!(secs, 1700000000);
4499        assert_eq!(micros, 123456);
4500    }
4501
4502    #[test]
4503    fn time_parse_error_on_wrong_length() {
4504        let cmd = Time::new();
4505        let frame = array(vec![Frame::BulkString(Some(Bytes::from("123")))]);
4506        assert!(cmd.parse_response(frame).is_err());
4507    }
4508
4509    // -- CommandOverview --
4510
4511    #[test]
4512    fn command_overview_preserves_resp2_and_resp3_shapes() {
4513        let cmd = CommandOverview::new();
4514        assert_eq!(cmd.to_frame(), array(vec![bulk("COMMAND")]));
4515        assert_eq!(cmd.name(), "COMMAND");
4516        assert!(cmd.idempotent());
4517        let resp2 = array(vec![array(vec![bulk("get")])]);
4518        assert_eq!(cmd.parse_response(resp2.clone()).unwrap(), resp2);
4519        let resp3 = Frame::Map(vec![(bulk("get"), array(vec![]))]);
4520        assert_eq!(cmd.parse_response(resp3.clone()).unwrap(), resp3);
4521        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
4522    }
4523
4524    // -- CommandCount --
4525
4526    #[test]
4527    fn command_count_to_frame() {
4528        let cmd = CommandCount::new();
4529        assert_eq!(cmd.to_frame(), array(vec![bulk("COMMAND"), bulk("COUNT")]));
4530    }
4531
4532    // -- ClientTracking --
4533
4534    // -- ClientSetInfoLibName --
4535
4536    #[test]
4537    fn client_setinfo_lib_name_to_frame() {
4538        let cmd = ClientSetInfoLibName::new("redis-tower");
4539        assert_eq!(
4540            cmd.to_frame(),
4541            array(vec![
4542                bulk("CLIENT"),
4543                bulk("SETINFO"),
4544                bulk("LIB-NAME"),
4545                bulk("redis-tower"),
4546            ])
4547        );
4548    }
4549
4550    #[test]
4551    fn client_setinfo_lib_name_parse_ok() {
4552        let cmd = ClientSetInfoLibName::new("redis-tower");
4553        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
4554            .unwrap();
4555    }
4556
4557    #[test]
4558    fn client_setinfo_lib_name_parse_error_on_integer() {
4559        let cmd = ClientSetInfoLibName::new("redis-tower");
4560        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
4561    }
4562
4563    #[test]
4564    fn client_setinfo_lib_name_name() {
4565        let cmd = ClientSetInfoLibName::new("redis-tower");
4566        assert_eq!(cmd.name(), "CLIENT SETINFO");
4567    }
4568
4569    // -- ClientSetInfoLibVer --
4570
4571    #[test]
4572    fn client_setinfo_lib_ver_to_frame() {
4573        let cmd = ClientSetInfoLibVer::new("0.1.0");
4574        assert_eq!(
4575            cmd.to_frame(),
4576            array(vec![
4577                bulk("CLIENT"),
4578                bulk("SETINFO"),
4579                bulk("LIB-VER"),
4580                bulk("0.1.0"),
4581            ])
4582        );
4583    }
4584
4585    #[test]
4586    fn client_setinfo_lib_ver_parse_ok() {
4587        let cmd = ClientSetInfoLibVer::new("0.1.0");
4588        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
4589            .unwrap();
4590    }
4591
4592    #[test]
4593    fn client_setinfo_lib_ver_parse_error_on_integer() {
4594        let cmd = ClientSetInfoLibVer::new("0.1.0");
4595        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
4596    }
4597
4598    #[test]
4599    fn client_setinfo_lib_ver_name() {
4600        let cmd = ClientSetInfoLibVer::new("0.1.0");
4601        assert_eq!(cmd.name(), "CLIENT SETINFO");
4602    }
4603
4604    // -- ClientTracking --
4605
4606    #[test]
4607    fn client_tracking_on_bcast_to_frame() {
4608        let cmd = ClientTracking::on().bcast().prefix("user:");
4609        let frame = cmd.to_frame();
4610        match frame {
4611            Frame::Array(Some(args)) => {
4612                assert_eq!(args[0], bulk("CLIENT"));
4613                assert_eq!(args[1], bulk("TRACKING"));
4614                assert_eq!(args[2], bulk("ON"));
4615                assert!(args.contains(&bulk("BCAST")));
4616                assert!(args.contains(&bulk("PREFIX")));
4617                assert!(args.contains(&bulk("user:")));
4618            }
4619            _ => panic!("expected array"),
4620        }
4621    }
4622
4623    #[test]
4624    fn client_tracking_redirect_noloop_to_frame() {
4625        let cmd = ClientTracking::on().redirect(42).noloop();
4626        assert_eq!(
4627            cmd.to_frame(),
4628            array(vec![
4629                bulk("CLIENT"),
4630                bulk("TRACKING"),
4631                bulk("ON"),
4632                bulk("REDIRECT"),
4633                bulk("42"),
4634                bulk("NOLOOP"),
4635            ])
4636        );
4637    }
4638
4639    #[test]
4640    fn client_tracking_prefix_is_binary_safe() {
4641        let prefix = [0, 0xff, b':'];
4642        let cmd = ClientTracking::on().prefix(prefix);
4643        assert_eq!(
4644            cmd.to_frame(),
4645            array(vec![
4646                bulk("CLIENT"),
4647                bulk("TRACKING"),
4648                bulk("ON"),
4649                bulk("BCAST"),
4650                bulk("PREFIX"),
4651                bulk(prefix),
4652            ])
4653        );
4654    }
4655
4656    #[test]
4657    fn client_tracking_mode_builders_keep_modes_compatible() {
4658        let optin = ClientTracking::on().bcast().prefix("ignored:").optin();
4659        assert_eq!(
4660            optin.to_frame(),
4661            array(vec![
4662                bulk("CLIENT"),
4663                bulk("TRACKING"),
4664                bulk("ON"),
4665                bulk("OPTIN"),
4666            ])
4667        );
4668
4669        let bcast = ClientTracking::on().optout().prefix("active:");
4670        assert_eq!(
4671            bcast.to_frame(),
4672            array(vec![
4673                bulk("CLIENT"),
4674                bulk("TRACKING"),
4675                bulk("ON"),
4676                bulk("BCAST"),
4677                bulk("PREFIX"),
4678                bulk("active:"),
4679            ])
4680        );
4681    }
4682
4683    #[test]
4684    fn client_tracking_off_omits_incompatible_options() {
4685        let cmd = ClientTracking::off()
4686            .redirect(42)
4687            .noloop()
4688            .prefix("unused:");
4689        assert_eq!(
4690            cmd.to_frame(),
4691            array(vec![bulk("CLIENT"), bulk("TRACKING"), bulk("OFF")])
4692        );
4693    }
4694
4695    // -- Echo --
4696
4697    #[test]
4698    fn echo_to_frame() {
4699        let cmd = Echo::new("hello");
4700        assert_eq!(cmd.to_frame(), array(vec![bulk("ECHO"), bulk("hello")]));
4701    }
4702
4703    #[test]
4704    fn echo_parse_response() {
4705        let cmd = Echo::new("hello");
4706        let frame = Frame::BulkString(Some(Bytes::from("hello")));
4707        assert_eq!(cmd.parse_response(frame).unwrap(), Bytes::from("hello"));
4708    }
4709
4710    // -- FlushAll --
4711
4712    #[test]
4713    fn flushall_to_frame() {
4714        let cmd = FlushAll::new();
4715        assert_eq!(cmd.to_frame(), array(vec![bulk("FLUSHALL")]));
4716    }
4717
4718    #[test]
4719    fn flushall_async_to_frame() {
4720        let cmd = FlushAll::new().async_mode();
4721        assert_eq!(cmd.to_frame(), array(vec![bulk("FLUSHALL"), bulk("ASYNC")]));
4722    }
4723
4724    #[test]
4725    fn flushall_parse_ok() {
4726        let cmd = FlushAll::new();
4727        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
4728            .unwrap();
4729    }
4730
4731    // -- Save --
4732
4733    #[test]
4734    fn save_to_frame() {
4735        let cmd = Save::new();
4736        assert_eq!(cmd.to_frame(), array(vec![bulk("SAVE")]));
4737    }
4738
4739    // -- Shutdown --
4740
4741    #[test]
4742    fn shutdown_to_frame() {
4743        let cmd = Shutdown::new().nosave().now().force();
4744        assert_eq!(
4745            cmd.to_frame(),
4746            array(vec![
4747                bulk("SHUTDOWN"),
4748                bulk("NOSAVE"),
4749                bulk("NOW"),
4750                bulk("FORCE"),
4751            ])
4752        );
4753    }
4754
4755    #[test]
4756    fn shutdown_abort_to_frame() {
4757        let cmd = Shutdown::new().abort();
4758        assert_eq!(cmd.to_frame(), array(vec![bulk("SHUTDOWN"), bulk("ABORT")]));
4759    }
4760
4761    #[test]
4762    fn shutdown_parse_any() {
4763        let cmd = Shutdown::new();
4764        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
4765            .unwrap();
4766        cmd.parse_response(Frame::Null).unwrap();
4767    }
4768
4769    // -- Role --
4770
4771    #[test]
4772    fn role_to_frame() {
4773        let cmd = Role::new();
4774        assert_eq!(cmd.to_frame(), array(vec![bulk("ROLE")]));
4775    }
4776
4777    #[test]
4778    fn role_parse_passthrough() {
4779        let cmd = Role::new();
4780        let frame = array(vec![Frame::BulkString(Some(Bytes::from("master")))]);
4781        assert_eq!(cmd.parse_response(frame.clone()).unwrap(), frame);
4782    }
4783
4784    // -- Hello --
4785
4786    #[test]
4787    fn hello_bare_to_frame() {
4788        let cmd = Hello::new();
4789        assert_eq!(cmd.to_frame(), array(vec![bulk("HELLO")]));
4790    }
4791
4792    #[test]
4793    fn hello_full_to_frame() {
4794        let cmd = Hello::new().proto(3).auth("user", "pass").setname("conn");
4795        assert_eq!(
4796            cmd.to_frame(),
4797            array(vec![
4798                bulk("HELLO"),
4799                bulk("3"),
4800                bulk("AUTH"),
4801                bulk("user"),
4802                bulk("pass"),
4803                bulk("SETNAME"),
4804                bulk("conn"),
4805            ])
4806        );
4807    }
4808
4809    // -- Reset --
4810
4811    #[test]
4812    fn reset_to_frame() {
4813        let cmd = Reset::new();
4814        assert_eq!(cmd.to_frame(), array(vec![bulk("RESET")]));
4815    }
4816
4817    #[test]
4818    fn reset_parse_response() {
4819        let cmd = Reset::new();
4820        let frame = Frame::SimpleString(Bytes::from("RESET"));
4821        assert_eq!(cmd.parse_response(frame).unwrap(), "RESET");
4822    }
4823
4824    // -- CommandInfo --
4825
4826    #[test]
4827    fn command_info_to_frame() {
4828        let cmd = CommandInfo::new("get").command("set");
4829        assert_eq!(
4830            cmd.to_frame(),
4831            array(vec![
4832                bulk("COMMAND"),
4833                bulk("INFO"),
4834                bulk("get"),
4835                bulk("set"),
4836            ])
4837        );
4838    }
4839
4840    // -- CommandGetKeys --
4841
4842    #[test]
4843    fn command_getkeys_to_frame() {
4844        let cmd = CommandGetKeys::new("SET").arg("k").arg("v");
4845        assert_eq!(
4846            cmd.to_frame(),
4847            array(vec![
4848                bulk("COMMAND"),
4849                bulk("GETKEYS"),
4850                bulk("SET"),
4851                bulk("k"),
4852                bulk("v"),
4853            ])
4854        );
4855    }
4856
4857    #[test]
4858    fn command_getkeys_parse_array() {
4859        let cmd = CommandGetKeys::new("SET");
4860        let frame = array(vec![Frame::BulkString(Some(Bytes::from("k")))]);
4861        assert_eq!(cmd.parse_response(frame).unwrap(), vec![Bytes::from("k")]);
4862    }
4863
4864    // -- CommandGetKeysAndFlags --
4865
4866    #[test]
4867    fn command_getkeysandflags_serializes_binary_safe_arguments() {
4868        let cmd = CommandGetKeysAndFlags::new("MSET").arg(b"key\0one").args([
4869            b"value-one".as_slice(),
4870            b"key-two".as_slice(),
4871            b"value-two".as_slice(),
4872        ]);
4873        assert_eq!(
4874            cmd.to_frame(),
4875            array(vec![
4876                bulk("COMMAND"),
4877                bulk("GETKEYSANDFLAGS"),
4878                bulk("MSET"),
4879                bulk(b"key\0one"),
4880                bulk("value-one"),
4881                bulk("key-two"),
4882                bulk("value-two"),
4883            ])
4884        );
4885        assert_eq!(cmd.name(), "COMMAND GETKEYSANDFLAGS");
4886        assert!(cmd.idempotent());
4887    }
4888
4889    #[test]
4890    fn command_getkeysandflags_parses_array_and_resp3_set_flags() {
4891        let cmd = CommandGetKeysAndFlags::new("MSET");
4892        let response = array(vec![
4893            array(vec![
4894                bulk(b"key\0one"),
4895                array(vec![bulk("RW"), bulk("access"), bulk("update")]),
4896            ]),
4897            array(vec![
4898                bulk("key-two"),
4899                Frame::Set(vec![bulk("RW"), bulk("access")]),
4900            ]),
4901        ]);
4902        assert_eq!(
4903            cmd.parse_response(response).unwrap(),
4904            vec![
4905                CommandKeyFlags {
4906                    key: Bytes::from_static(b"key\0one"),
4907                    flags: vec![
4908                        Bytes::from("RW"),
4909                        Bytes::from("access"),
4910                        Bytes::from("update")
4911                    ],
4912                },
4913                CommandKeyFlags {
4914                    key: Bytes::from("key-two"),
4915                    flags: vec![Bytes::from("RW"), Bytes::from("access")],
4916                },
4917            ]
4918        );
4919        assert_eq!(
4920            cmd.parse_response(Frame::Array(None)).unwrap(),
4921            Vec::<CommandKeyFlags>::new()
4922        );
4923    }
4924
4925    #[test]
4926    fn command_getkeysandflags_rejects_malformed_entries() {
4927        let cmd = CommandGetKeysAndFlags::new("GET");
4928        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
4929        assert!(
4930            cmd.parse_response(array(vec![array(vec![bulk("only-key")])]))
4931                .is_err()
4932        );
4933        assert!(
4934            cmd.parse_response(array(vec![array(vec![bulk("key"), Frame::Integer(1)])]))
4935                .is_err()
4936        );
4937    }
4938
4939    // -- ClientReply --
4940
4941    #[test]
4942    fn client_reply_to_frame() {
4943        let cmd = ClientReply::new(ClientReplyMode::Skip);
4944        assert_eq!(
4945            cmd.to_frame(),
4946            array(vec![bulk("CLIENT"), bulk("REPLY"), bulk("SKIP")])
4947        );
4948    }
4949
4950    // -- ClientTrackingInfo --
4951
4952    #[test]
4953    fn client_trackinginfo_to_frame() {
4954        let cmd = ClientTrackingInfo::new();
4955        assert_eq!(
4956            cmd.to_frame(),
4957            array(vec![bulk("CLIENT"), bulk("TRACKINGINFO")])
4958        );
4959    }
4960
4961    // -- ClientUnblock --
4962
4963    #[test]
4964    fn client_unblock_to_frame() {
4965        let cmd = ClientUnblock::new(42).mode(UnblockMode::Error);
4966        assert_eq!(
4967            cmd.to_frame(),
4968            array(vec![
4969                bulk("CLIENT"),
4970                bulk("UNBLOCK"),
4971                bulk("42"),
4972                bulk("ERROR"),
4973            ])
4974        );
4975    }
4976
4977    #[test]
4978    fn client_unblock_parse_integer() {
4979        let cmd = ClientUnblock::new(42);
4980        assert_eq!(cmd.parse_response(Frame::Integer(1)).unwrap(), 1);
4981    }
4982
4983    // -- ClientCaching --
4984
4985    #[test]
4986    fn client_caching_to_frame() {
4987        let cmd = ClientCaching::new(true);
4988        assert_eq!(
4989            cmd.to_frame(),
4990            array(vec![bulk("CLIENT"), bulk("CACHING"), bulk("yes")])
4991        );
4992    }
4993
4994    #[test]
4995    fn client_caching_no_to_frame() {
4996        let cmd = ClientCaching::new(false);
4997        assert_eq!(
4998            cmd.to_frame(),
4999            array(vec![bulk("CLIENT"), bulk("CACHING"), bulk("no")])
5000        );
5001    }
5002
5003    // -- ModuleList --
5004
5005    #[test]
5006    fn module_list_to_frame() {
5007        let cmd = ModuleList::new();
5008        assert_eq!(cmd.to_frame(), array(vec![bulk("MODULE"), bulk("LIST")]));
5009        assert!(cmd.idempotent());
5010    }
5011
5012    #[test]
5013    fn module_list_parse_passthrough() {
5014        let cmd = ModuleList::new();
5015        let reply = array(vec![array(vec![bulk("name"), bulk("ReJSON")])]);
5016        assert_eq!(cmd.parse_response(reply.clone()).unwrap(), reply);
5017    }
5018
5019    #[test]
5020    fn module_load_serializes_binary_safe_arguments_and_parses_ok() {
5021        let cmd = ModuleLoad::new(b"/tmp/module\0name.so")
5022            .arg(b"first\0arg")
5023            .args([b"second".as_slice(), b"third".as_slice()]);
5024        assert_eq!(
5025            cmd.to_frame(),
5026            array(vec![
5027                bulk("MODULE"),
5028                bulk("LOAD"),
5029                bulk(b"/tmp/module\0name.so"),
5030                bulk(b"first\0arg"),
5031                bulk("second"),
5032                bulk("third"),
5033            ])
5034        );
5035        assert_eq!(cmd.name(), "MODULE LOAD");
5036        assert!(!cmd.idempotent());
5037        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
5038            .unwrap();
5039        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
5040    }
5041
5042    #[test]
5043    fn module_loadex_orders_configs_before_args() {
5044        let cmd = ModuleLoadEx::new("/tmp/module.so")
5045            .config(b"setting\0name", b"setting\0value")
5046            .config("threads", "4")
5047            .arg(b"arg\0one")
5048            .args([b"arg-two".as_slice()]);
5049        assert_eq!(
5050            cmd.to_frame(),
5051            array(vec![
5052                bulk("MODULE"),
5053                bulk("LOADEX"),
5054                bulk("/tmp/module.so"),
5055                bulk("CONFIG"),
5056                bulk(b"setting\0name"),
5057                bulk(b"setting\0value"),
5058                bulk("CONFIG"),
5059                bulk("threads"),
5060                bulk("4"),
5061                bulk("ARGS"),
5062                bulk(b"arg\0one"),
5063                bulk("arg-two"),
5064            ])
5065        );
5066        assert_eq!(cmd.name(), "MODULE LOADEX");
5067        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
5068            .unwrap();
5069    }
5070
5071    #[test]
5072    fn module_unload_serializes_binary_safe_name_and_parses_ok() {
5073        let cmd = ModuleUnload::new(b"module\0name");
5074        assert_eq!(
5075            cmd.to_frame(),
5076            array(vec![bulk("MODULE"), bulk("UNLOAD"), bulk(b"module\0name")])
5077        );
5078        assert_eq!(cmd.name(), "MODULE UNLOAD");
5079        assert!(!cmd.idempotent());
5080        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
5081            .unwrap();
5082        assert!(cmd.parse_response(Frame::Null).is_err());
5083    }
5084
5085    // -- HOTKEYS --
5086
5087    #[test]
5088    fn hotkeys_start_cpu_to_frame() {
5089        let cmd = HotkeysStart::new(HotkeysMetrics::Cpu);
5090        assert_eq!(
5091            cmd.to_frame(),
5092            array(vec![
5093                bulk("HOTKEYS"),
5094                bulk("START"),
5095                bulk("METRICS"),
5096                bulk("1"),
5097                bulk("CPU"),
5098            ])
5099        );
5100        assert_eq!(cmd.name(), "HOTKEYS START");
5101    }
5102
5103    #[test]
5104    fn hotkeys_start_net_to_frame() {
5105        let cmd = HotkeysStart::new(HotkeysMetrics::Net);
5106        assert_eq!(
5107            cmd.to_frame(),
5108            array(vec![
5109                bulk("HOTKEYS"),
5110                bulk("START"),
5111                bulk("METRICS"),
5112                bulk("1"),
5113                bulk("NET"),
5114            ])
5115        );
5116    }
5117
5118    #[test]
5119    fn hotkeys_start_all_options_to_frame() {
5120        let cmd = HotkeysStart::new(HotkeysMetrics::CpuAndNet)
5121            .count(25)
5122            .duration(60)
5123            .sample(10)
5124            .slots([3, 7, 8]);
5125        assert_eq!(
5126            cmd.to_frame(),
5127            array(vec![
5128                bulk("HOTKEYS"),
5129                bulk("START"),
5130                bulk("METRICS"),
5131                bulk("2"),
5132                bulk("CPU"),
5133                bulk("NET"),
5134                bulk("COUNT"),
5135                bulk("25"),
5136                bulk("DURATION"),
5137                bulk("60"),
5138                bulk("SAMPLE"),
5139                bulk("10"),
5140                bulk("SLOTS"),
5141                bulk("3"),
5142                bulk("3"),
5143                bulk("7"),
5144                bulk("8"),
5145            ])
5146        );
5147    }
5148
5149    #[test]
5150    fn hotkeys_start_parse_ok_and_rejects_other_frames() {
5151        let cmd = HotkeysStart::new(HotkeysMetrics::Cpu);
5152        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
5153            .unwrap();
5154        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
5155    }
5156
5157    #[test]
5158    fn hotkeys_stop_to_frame_and_parse_status() {
5159        let cmd = HotkeysStop::new();
5160        assert_eq!(cmd.to_frame(), array(vec![bulk("HOTKEYS"), bulk("STOP")]));
5161        assert_eq!(cmd.name(), "HOTKEYS STOP");
5162        assert!(
5163            cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
5164                .unwrap()
5165        );
5166        assert!(!cmd.parse_response(Frame::Null).unwrap());
5167        assert!(!cmd.parse_response(Frame::BulkString(None)).unwrap());
5168        assert!(cmd.parse_response(Frame::Integer(0)).is_err());
5169    }
5170
5171    #[test]
5172    fn hotkeys_reset_to_frame_and_parse_ok() {
5173        let cmd = HotkeysReset::new();
5174        assert_eq!(cmd.to_frame(), array(vec![bulk("HOTKEYS"), bulk("RESET")]));
5175        assert_eq!(cmd.name(), "HOTKEYS RESET");
5176        cmd.parse_response(Frame::SimpleString(Bytes::from("OK")))
5177            .unwrap();
5178        assert!(cmd.parse_response(Frame::Null).is_err());
5179    }
5180
5181    #[test]
5182    fn hotkeys_get_to_frame_and_parse_null() {
5183        let cmd = HotkeysGet::new();
5184        assert_eq!(cmd.to_frame(), array(vec![bulk("HOTKEYS"), bulk("GET")]));
5185        assert_eq!(cmd.name(), "HOTKEYS GET");
5186        assert!(cmd.idempotent());
5187        assert_eq!(cmd.parse_response(Frame::Null).unwrap(), None);
5188        assert_eq!(cmd.parse_response(Frame::BulkString(None)).unwrap(), None);
5189    }
5190
5191    #[test]
5192    fn hotkeys_get_parse_resp2_full_result() {
5193        let cmd = HotkeysGet::new();
5194        let reply = array(vec![array(vec![
5195            bulk("tracking-active"),
5196            Frame::Integer(0),
5197            bulk("sample-ratio"),
5198            Frame::Integer(10),
5199            bulk("selected-slots"),
5200            array(vec![
5201                array(vec![Frame::Integer(0), Frame::Integer(3)]),
5202                array(vec![Frame::Integer(7)]),
5203            ]),
5204            // Compatibility spelling emitted by Redis 8.6.0.
5205            bulk("sampled-command-selected-slots-us"),
5206            Frame::Integer(11),
5207            bulk("all-commands-selected-slots-us"),
5208            Frame::Integer(22),
5209            bulk("all-commands-all-slots-us"),
5210            Frame::Integer(33),
5211            bulk("net-bytes-sampled-commands-selected-slots"),
5212            Frame::Integer(44),
5213            bulk("net-bytes-all-commands-selected-slots"),
5214            Frame::Integer(55),
5215            bulk("net-bytes-all-commands-all-slots"),
5216            Frame::Integer(66),
5217            bulk("collection-start-time-unix-ms"),
5218            Frame::Integer(1_700_000_000_000),
5219            bulk("collection-duration-ms"),
5220            Frame::Integer(5_000),
5221            bulk("total-cpu-time-user-ms"),
5222            Frame::Integer(77),
5223            bulk("total-cpu-time-sys-ms"),
5224            Frame::Integer(88),
5225            bulk("total-net-bytes"),
5226            Frame::Integer(99),
5227            bulk("by-cpu-time-us"),
5228            array(vec![
5229                bulk("hot:key:1"),
5230                Frame::Integer(101),
5231                bulk("hot:key:2"),
5232                Frame::Integer(51),
5233            ]),
5234            bulk("by-net-bytes"),
5235            array(vec![bulk("hot:key:1"), Frame::Integer(2_048)]),
5236        ])]);
5237
5238        assert_eq!(
5239            cmd.parse_response(reply).unwrap(),
5240            Some(vec![HotkeysStats {
5241                tracking_active: false,
5242                sample_ratio: 10,
5243                selected_slots: vec![
5244                    HotkeysSlotRange { start: 0, end: 3 },
5245                    HotkeysSlotRange { start: 7, end: 7 },
5246                ],
5247                sampled_commands_selected_slots_us: Some(11),
5248                all_commands_selected_slots_us: Some(22),
5249                all_commands_all_slots_us: 33,
5250                net_bytes_sampled_commands_selected_slots: Some(44),
5251                net_bytes_all_commands_selected_slots: Some(55),
5252                net_bytes_all_commands_all_slots: 66,
5253                collection_start_time_unix_ms: 1_700_000_000_000,
5254                collection_duration_ms: 5_000,
5255                total_cpu_time_user_ms: Some(77),
5256                total_cpu_time_sys_ms: Some(88),
5257                total_net_bytes: Some(99),
5258                by_cpu_time_us: Some(vec![
5259                    HotkeyCpuTime {
5260                        key: Bytes::from("hot:key:1"),
5261                        microseconds: 101,
5262                    },
5263                    HotkeyCpuTime {
5264                        key: Bytes::from("hot:key:2"),
5265                        microseconds: 51,
5266                    },
5267                ]),
5268                by_net_bytes: Some(vec![HotkeyNetBytes {
5269                    key: Bytes::from("hot:key:1"),
5270                    bytes: 2_048,
5271                }]),
5272            }])
5273        );
5274    }
5275
5276    #[test]
5277    fn hotkeys_get_parse_resp3_map() {
5278        let cmd = HotkeysGet::new();
5279        let reply = array(vec![Frame::Map(vec![
5280            (bulk("tracking-active"), Frame::Integer(1)),
5281            (bulk("sample-ratio"), Frame::Integer(1)),
5282            (
5283                bulk("selected-slots"),
5284                array(vec![array(vec![Frame::Integer(0), Frame::Integer(16_383)])]),
5285            ),
5286            (bulk("all-commands-all-slots-us"), Frame::Integer(103)),
5287            (
5288                bulk("net-bytes-all-commands-all-slots"),
5289                Frame::Integer(2_042),
5290            ),
5291            (
5292                bulk("collection-start-time-unix-ms"),
5293                Frame::Integer(1_770_824_933_147),
5294            ),
5295            (bulk("collection-duration-ms"), Frame::Integer(250)),
5296            (bulk("total-cpu-time-user-ms"), Frame::Integer(23)),
5297            (bulk("total-cpu-time-sys-ms"), Frame::Integer(7)),
5298            (
5299                bulk("by-cpu-time-us"),
5300                array(vec![bulk("counter"), Frame::Integer(29)]),
5301            ),
5302            // Unknown fields are ignored for compatibility with future Redis
5303            // additions.
5304            (bulk("future-field"), Frame::Integer(1)),
5305        ])]);
5306
5307        let stats = cmd.parse_response(reply).unwrap().unwrap().remove(0);
5308        assert!(stats.tracking_active);
5309        assert_eq!(stats.sample_ratio, 1);
5310        assert_eq!(
5311            stats.selected_slots,
5312            vec![HotkeysSlotRange {
5313                start: 0,
5314                end: 16_383,
5315            }]
5316        );
5317        assert_eq!(stats.all_commands_all_slots_us, 103);
5318        assert_eq!(stats.net_bytes_all_commands_all_slots, 2_042);
5319        assert_eq!(stats.total_cpu_time_user_ms, Some(23));
5320        assert_eq!(
5321            stats.by_cpu_time_us,
5322            Some(vec![HotkeyCpuTime {
5323                key: Bytes::from("counter"),
5324                microseconds: 29,
5325            }])
5326        );
5327        assert_eq!(stats.total_net_bytes, None);
5328        assert_eq!(stats.by_net_bytes, None);
5329    }
5330
5331    #[test]
5332    fn hotkeys_get_parse_multiple_node_results() {
5333        fn node(active: i64, start: i64) -> Frame {
5334            Frame::Map(vec![
5335                (bulk("tracking-active"), Frame::Integer(active)),
5336                (bulk("sample-ratio"), Frame::Integer(1)),
5337                (bulk("selected-slots"), array(vec![])),
5338                (bulk("all-commands-all-slots-us"), Frame::Integer(0)),
5339                (bulk("net-bytes-all-commands-all-slots"), Frame::Integer(0)),
5340                (bulk("collection-start-time-unix-ms"), Frame::Integer(start)),
5341                (bulk("collection-duration-ms"), Frame::Integer(0)),
5342            ])
5343        }
5344
5345        let results = HotkeysGet::new()
5346            .parse_response(array(vec![node(1, 100), node(0, 200)]))
5347            .unwrap()
5348            .unwrap();
5349        assert_eq!(results.len(), 2);
5350        assert!(results[0].tracking_active);
5351        assert!(!results[1].tracking_active);
5352    }
5353
5354    #[test]
5355    fn hotkeys_get_rejects_malformed_responses() {
5356        let cmd = HotkeysGet::new();
5357        assert!(cmd.parse_response(Frame::Integer(1)).is_err());
5358        assert!(
5359            cmd.parse_response(array(vec![array(vec![
5360                bulk("tracking-active"),
5361                Frame::Integer(1),
5362                bulk("sample-ratio"),
5363            ])]))
5364            .is_err()
5365        );
5366        assert!(
5367            cmd.parse_response(array(vec![Frame::Map(vec![
5368                (bulk("tracking-active"), Frame::Integer(2)),
5369                (bulk("sample-ratio"), Frame::Integer(1)),
5370            ])]))
5371            .is_err()
5372        );
5373        assert!(
5374            cmd.parse_response(array(vec![Frame::Map(vec![
5375                (bulk("tracking-active"), Frame::Integer(1)),
5376                (bulk("sample-ratio"), Frame::Integer(1)),
5377                (
5378                    bulk("selected-slots"),
5379                    array(vec![array(vec![Frame::Integer(16_384)])]),
5380                ),
5381            ])]))
5382            .is_err()
5383        );
5384    }
5385
5386    #[test]
5387    fn hotkeys_help_to_frame_and_parse_lines() {
5388        let cmd = HotkeysHelp::new();
5389        assert_eq!(cmd.to_frame(), array(vec![bulk("HOTKEYS"), bulk("HELP")]));
5390        assert_eq!(cmd.name(), "HOTKEYS HELP");
5391        assert!(cmd.idempotent());
5392        let lines = cmd
5393            .parse_response(array(vec![bulk("START"), bulk("STOP")]))
5394            .unwrap();
5395        assert_eq!(lines, vec![Bytes::from("START"), Bytes::from("STOP")]);
5396    }
5397
5398    // -- CLIENT GETREDIR --
5399
5400    #[test]
5401    fn client_getredir_to_frame() {
5402        let cmd = ClientGetRedir::new();
5403        assert_eq!(
5404            cmd.to_frame(),
5405            array(vec![bulk("CLIENT"), bulk("GETREDIR")])
5406        );
5407        assert!(cmd.idempotent());
5408    }
5409
5410    #[test]
5411    fn client_getredir_parse_integer() {
5412        let cmd = ClientGetRedir::new();
5413        assert_eq!(cmd.parse_response(Frame::Integer(-1)).unwrap(), -1);
5414    }
5415
5416    // -- HELP subcommands --
5417
5418    #[test]
5419    fn help_subcommands_to_frame() {
5420        assert_eq!(
5421            ClientHelp::new().to_frame(),
5422            array(vec![bulk("CLIENT"), bulk("HELP")])
5423        );
5424        assert_eq!(
5425            CommandHelp::new().to_frame(),
5426            array(vec![bulk("COMMAND"), bulk("HELP")])
5427        );
5428        assert_eq!(
5429            ConfigHelp::new().to_frame(),
5430            array(vec![bulk("CONFIG"), bulk("HELP")])
5431        );
5432        assert_eq!(
5433            ModuleHelp::new().to_frame(),
5434            array(vec![bulk("MODULE"), bulk("HELP")])
5435        );
5436        assert!(ClientHelp::new().idempotent());
5437    }
5438
5439    #[test]
5440    fn client_help_parse_lines() {
5441        let cmd = ClientHelp::new();
5442        let reply = array(vec![bulk("CLIENT <subcommand>"), bulk("ID")]);
5443        let lines = cmd.parse_response(reply).unwrap();
5444        assert_eq!(lines.len(), 2);
5445        assert_eq!(&lines[1][..], b"ID");
5446    }
5447
5448    // -- LOLWUT --
5449
5450    #[test]
5451    fn lolwut_to_frame() {
5452        assert_eq!(Lolwut::new().to_frame(), array(vec![bulk("LOLWUT")]));
5453        assert_eq!(
5454            Lolwut::new().version(5).to_frame(),
5455            array(vec![bulk("LOLWUT"), bulk("VERSION"), bulk("5")])
5456        );
5457    }
5458
5459    #[test]
5460    fn lolwut_parse_strings() {
5461        let cmd = Lolwut::new();
5462        assert_eq!(
5463            cmd.parse_response(Frame::BulkString(Some(Bytes::from("Redis ver. 7.4.0"))))
5464                .unwrap(),
5465            "Redis ver. 7.4.0"
5466        );
5467        assert_eq!(
5468            cmd.parse_response(Frame::VerbatimString(
5469                Bytes::from("txt"),
5470                Bytes::from("Redis ver. 8.0.0")
5471            ))
5472            .unwrap(),
5473            "Redis ver. 8.0.0"
5474        );
5475    }
5476}