1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
use crate::{
    resp::{
        cmd, Array, BulkString, CommandArgs, FromValue, IntoArgs, SingleArgOrCollection, Value,
    },
    CommandResult, Error, PrepareCommand, Result,
};
use std::collections::HashMap;

/// A group of Redis commands related to connection management
///
/// # See Also
/// [Redis Connection Management Commands](https://redis.io/commands/?group=connection)
pub trait ConnectionCommands<T>: PrepareCommand<T> {
    /// Authenticates the current connection.
    ///
    /// # Errors
    /// a Redis error if the password, or username/password pair, is invalid.
    ///
    /// # See Also
    /// [<https://redis.io/commands/auth/>](https://redis.io/commands/auth/)
    #[must_use]
    fn auth<U, P>(&self, username: Option<U>, password: P) -> CommandResult<T, ()>
    where
        U: Into<BulkString>,
        P: Into<BulkString>,
    {
        self.prepare_command(cmd("AUTH").arg(username).arg(password))
    }

    /// This command controls the tracking of the keys in the next command executed by the connection,
    /// when tracking is enabled in OPTIN or OPTOUT mode.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-caching/>](https://redis.io/commands/client-caching/)
    #[must_use]
    fn client_caching(&self, mode: ClientCachingMode) -> CommandResult<T, Option<()>> {
        self.prepare_command(cmd("CLIENT").arg("CACHING").arg(mode))
    }

    /// Returns the name of the current connection as set by [CLIENT SETNAME].
    ///
    /// # Return
    /// The connection name, or a None if no name is set.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-getname/>](https://redis.io/commands/client-getname/)
    #[must_use]
    fn client_getname<CN>(&self) -> CommandResult<T, Option<CN>>
    where
        CN: FromValue,
    {
        self.prepare_command(cmd("CLIENT").arg("GETNAME"))
    }

    /// This command returns the client ID we are redirecting our tracking notifications to.
    ///
    /// # Return
    /// the ID of the client we are redirecting the notifications to.
    /// The command returns -1 if client tracking is not enabled,
    /// or 0 if client tracking is enabled but we are not redirecting the notifications to any client.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-getredir/>](https://redis.io/commands/client-getredir/)
    #[must_use]
    fn client_getredir(&self) -> CommandResult<T, i64> {
        self.prepare_command(cmd("CLIENT").arg("GETREDIR"))
    }

    /// The command just returns the ID of the current connection.
    ///
    /// # Return
    /// The id of the client.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-id/>](https://redis.io/commands/client-id/)
    #[must_use]
    fn client_id(&self) -> CommandResult<T, i64> {
        self.prepare_command(cmd("CLIENT").arg("ID"))
    }

    /// The command returns information and statistics about the current client connection
    /// in a mostly human readable format.
    ///
    /// # Return
    /// A ClientInfo struct with additional properties
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-info/>](https://redis.io/commands/client-info/)
    #[must_use]
    fn client_info(&self) -> CommandResult<T, ClientInfo> {
        self.prepare_command(cmd("CLIENT").arg("INFO"))
    }

    /// Closes a given clients connection based on a filter list
    ///
    /// # Return
    /// the number of clients killed.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-kill/>](https://redis.io/commands/client-kill/)
    #[must_use]
    fn client_kill(&self, options: ClientKillOptions) -> CommandResult<T, usize> {
        self.prepare_command(cmd("CLIENT").arg("KILL").arg(options))
    }

    /// Returns information and statistics about the client connections server in a mostly human readable format.
    ///
    /// # Return
    /// A Vec of ClientInfo structs with additional properties
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-list/>](https://redis.io/commands/client-list/)
    #[must_use]
    fn client_list(&self, options: ClientListOptions) -> CommandResult<T, ClientListResult> {
        self.prepare_command(cmd("CLIENT").arg("LIST").arg(options))
    }

    ///  sets the [`client eviction`](https://redis.io/docs/reference/clients/#client-eviction) mode for the current connection.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-no-evict/>](https://redis.io/commands/client-no-evict/)
    #[must_use]
    fn client_no_evict(&self, no_evict: bool) -> CommandResult<T, ()> {
        self.prepare_command(
            cmd("CLIENT")
                .arg("NO-EVICT")
                .arg(if no_evict { "ON" } else { "OFF" }),
        )
    }

    /// Connections control command able to suspend all the Redis clients
    /// for the specified amount of time (in milliseconds).
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-pause/>](https://redis.io/commands/client-pause/)
    #[must_use]
    fn client_pause(&self, timeout: u64, mode: ClientPauseMode) -> CommandResult<T, ()> {
        self.prepare_command(cmd("CLIENT").arg("PAUSE").arg(timeout).arg(mode))
    }

    /// Sometimes it can be useful for clients to completely disable replies from the Redis server.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-reply/>](https://redis.io/commands/client-reply/)
    #[must_use]
    fn client_reply(&self, mode: ClientReplyMode) -> CommandResult<T, ()> {
        self.prepare_command(cmd("CLIENT").arg("REPLY").arg(mode))
    }

    /// Assigns a name to the current connection.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-setname/>](https://redis.io/commands/client-setname/)
    #[must_use]
    fn client_setname<CN>(&self, connection_name: CN) -> CommandResult<T, ()>
    where
        CN: Into<BulkString>,
    {
        self.prepare_command(cmd("CLIENT").arg("SETNAME").arg(connection_name))
    }

    /// This command enables the tracking feature of the Redis server,
    /// that is used for [`server assisted client side caching`](https://redis.io/topics/client-side-caching).
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-tracking/>](https://redis.io/commands/client-tracking/)
    #[must_use]
    fn client_tracking(
        &self,
        status: ClientTrackingStatus,
        options: ClientTrackingOptions,
    ) -> CommandResult<T, ()> {
        self.prepare_command(
            cmd("CLIENT")
                .arg("TRACKING")
                .arg(status)
                .arg(options),
        )
    }

    /// This command enables the tracking feature of the Redis server,
    /// that is used for [`server assisted client side caching`](https://redis.io/topics/client-side-caching).
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-tracking/>](https://redis.io/commands/client-tracking/)
    #[must_use]
    fn client_trackinginfo(&self) -> CommandResult<T, ClientTrackingInfo> {
        self.prepare_command(cmd("CLIENT").arg("TRACKINGINFO"))
    }

    /// This command can unblock, from a different connection, 
    /// a client blocked in a blocking operation, 
    /// such as for instance `BRPOP` or `XREAD` or `WAIT`.
    /// 
    /// # Return
    /// * `true` - This command can unblock, from a different connection, a client blocked in a blocking operation, such as for instance BRPOP or XREAD or WAIT.
    /// * `false` - if the client wasn't unblocked.
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-unblock/>](https://redis.io/commands/client-unblock/)
    #[must_use]
    fn client_unblock(&self, client_id: i64, mode: ClientUnblockMode) -> CommandResult<T, bool> {
        self.prepare_command(cmd("CLIENT").arg("UNBLOCK").arg(client_id).arg(mode))
    }

    /// Used to resume command processing for all clients that were 
    /// paused by [`client_pause`](crate::ConnectionCommands::client_pause).
    ///
    /// # See Also
    /// [<https://redis.io/commands/client-unpause/>](https://redis.io/commands/client-unpause/)
    #[must_use]
    fn client_unpause(&self) -> CommandResult<T, bool> {
        self.prepare_command(cmd("CLIENT").arg("UNPAUSE"))
    }   

    /// Returns `message`.
    ///
    /// # See Also
    /// [<https://redis.io/commands/echo/>](https://redis.io/commands/echo/)
    #[must_use]
    fn echo<M, R>(&self, message: M) -> CommandResult<T, R>
    where
        M: Into<BulkString>,
        R: FromValue,
    {
        self.prepare_command(cmd("ECHO").arg(message))
    }

    /// Switch to a different protocol,
    /// optionally authenticating and setting the connection's name,
    /// or provide a contextual client report.
    ///
    /// # See Also
    /// [<https://redis.io/commands/hello/>](https://redis.io/commands/hello/)
    #[must_use]
    fn hello(&self, options: HelloOptions) -> CommandResult<T, HelloResult> {
        self.prepare_command(cmd("HELLO").arg(options))
    }

    /// Returns PONG if no argument is provided, otherwise return a copy of the argument as a bulk.
    ///
    /// # See Also
    /// [<https://redis.io/commands/ping/>](https://redis.io/commands/ping/)
    #[must_use]
    fn ping<R>(&self, options: PingOptions) -> CommandResult<T, R>
    where
        R: FromValue,
    {
        self.prepare_command(cmd("PING").arg(options))
    }

    /// Ask the server to close the connection.
    ///
    /// # See Also
    /// [<https://redis.io/commands/quit/>](https://redis.io/commands/quit/)
    #[must_use]
    fn quit(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("QUIT"))
    }

    /// This command performs a full reset of the connection's server-side context,
    /// mimicking the effect of disconnecting and reconnecting again.
    ///
    /// # See Also
    /// [<https://redis.io/commands/reset/>](https://redis.io/commands/reset/)
    #[must_use]
    fn reset(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("RESET"))
    }

    /// Select the Redis logical database having the specified zero-based numeric index.
    ///
    /// # See Also
    /// [<https://redis.io/commands/reset/>](https://redis.io/commands/reset/)
    #[must_use]
    fn select(&self, index: usize) -> CommandResult<T, ()> {
        self.prepare_command(cmd("SELECT").arg(index))
    }
}

/// Client caching mode for the [`client_caching`](crate::ConnectionCommands::client_caching) command.
pub enum ClientCachingMode {
    Yes,
    No,
}

impl IntoArgs for ClientCachingMode {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(match self {
            ClientCachingMode::Yes => BulkString::Str("YES"),
            ClientCachingMode::No => BulkString::Str("NO"),
        })
    }
}

/// Client info results for the [`client_info`](crate::ConnectionCommands::client_info)
/// & [`client_list`](crate::ConnectionCommands::client_list) commands.
#[derive(Debug)]
pub struct ClientInfo {
    /// a unique 64-bit client ID
    pub id: i64,

    /// address/port of the client
    pub addr: String,

    /// address/port of local address client connected to (bind address)
    pub laddr: String,

    /// file descriptor corresponding to the socket
    pub fd: u32,

    /// the name set by the client with [`client_setname`](crate::ConnectionCommands::client_setname)
    pub name: String,

    /// total duration of the connection in seconds
    pub age: u32,

    /// idle time of the connection in seconds
    pub idle: u32,

    /// client flags (see [`client-list`](https://redis.io/commands/client-list/))
    pub flags: String,

    /// current database ID
    pub db: usize,

    /// number of channel subscriptions
    pub sub: usize,

    /// number of pattern matching subscriptions
    pub psub: usize,

    /// number of shard channel subscriptions. Added in Redis 7.0.3
    pub ssub: usize,

    /// number of commands in a MULTI/EXEC context
    pub multi: usize,

    /// query buffer length (0 means no query pending)
    pub qbuf: usize,

    /// free space of the query buffer (0 means the buffer is full)
    pub qbuf_free: usize,

    /// incomplete arguments for the next command (already extracted from query buffer)
    pub argv_mem: usize,

    /// memory is used up by buffered multi commands. Added in Redis 7.0
    pub multi_mem: usize,

    /// output buffer length
    pub obl: usize,

    /// output list length (replies are queued in this list when the buffer is full)
    pub oll: usize,

    /// output buffer memory usage
    pub omem: usize,

    ///  total memory consumed by this client in its various buffers
    pub tot_mem: usize,

    /// file descriptor events (r or w)
    pub events: String,

    /// last command played
    pub cmd: String,

    /// the authenticated username of the client
    pub user: String,

    /// client id of current client tracking redirection
    pub redir: i64,

    /// client RESP protocol version
    pub resp: i32,

    /// additional arguments that may be added in future versions of Redis
    pub additional_arguments: HashMap<String, String>,
}

impl ClientInfo {
    pub fn from_line(line: &str) -> Result<ClientInfo> {
        // Each line is composed of a succession of property=value fields separated by a space character.
        let mut values: HashMap<String, String> = line
            .trim_end()
            .split(' ')
            .map(|kvp| {
                let mut iter = kvp.split('=');
                match (iter.next(), iter.next()) {
                    (Some(key), None) => (key.to_owned(), "".to_owned()),
                    (Some(key), Some(value)) => (key.to_owned(), value.to_owned()),
                    _ => ("".to_owned(), "".to_owned()),
                }
            })
            .collect();

        Ok(ClientInfo {
            id: values
                .remove("id")
                .map(|id| id.parse::<i64>().unwrap_or_default())
                .unwrap_or_default(),
            addr: values.remove("addr").unwrap_or_default(),
            laddr: values.remove("laddr").unwrap_or_default(),
            fd: values
                .remove("fd")
                .map(|id| id.parse::<u32>().unwrap_or_default())
                .unwrap_or_default(),
            name: values.remove("name").unwrap_or_default(),
            age: values
                .remove("age")
                .map(|id| id.parse::<u32>().unwrap_or_default())
                .unwrap_or_default(),
            idle: values
                .remove("idle")
                .map(|id| id.parse::<u32>().unwrap_or_default())
                .unwrap_or_default(),
            flags: values.remove("flags").unwrap_or_default(),
            db: values
                .remove("db")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            sub: values
                .remove("sub")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            psub: values
                .remove("psub")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            ssub: values
                .remove("ssub")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            multi: values
                .remove("multi")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            qbuf: values
                .remove("qbuf")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            qbuf_free: values
                .remove("qbuf-free")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            argv_mem: values
                .remove("argv-mem")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            multi_mem: values
                .remove("multi-mem")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            obl: values
                .remove("obl")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            oll: values
                .remove("oll")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            omem: values
                .remove("omem")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            tot_mem: values
                .remove("tot-mem")
                .map(|id| id.parse::<usize>().unwrap_or_default())
                .unwrap_or_default(),
            events: values.remove("events").unwrap_or_default(),
            cmd: values.remove("cmd").unwrap_or_default(),
            user: values.remove("user").unwrap_or_default(),
            redir: values
                .remove("redir")
                .map(|id| id.parse::<i64>().unwrap_or_default())
                .unwrap_or_default(),
            resp: values
                .remove("resp")
                .map(|id| id.parse::<i32>().unwrap_or_default())
                .unwrap_or_default(),
            additional_arguments: values,
        })
    }
}

impl FromValue for ClientInfo {
    fn from_value(value: Value) -> Result<Self> {
        ClientInfo::from_line(&value.into::<String>()?)
    }
}

/// Client type options for the [client_list](crate::ConnectionCommands::client_list) command.
pub enum ClientType {
    Normal,
    Master,
    Replica,
    PubSub,
}

impl IntoArgs for ClientType {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(match self {
            ClientType::Normal => BulkString::Str("NORMAL"),
            ClientType::Master => BulkString::Str("MASTER"),
            ClientType::Replica => BulkString::Str("REPLICA"),
            ClientType::PubSub => BulkString::Str("PUBSUB"),
        })
    }
}

/// Options for the [client_list](crate::ConnectionCommands::client_list) command.
#[derive(Default)]
pub struct ClientListOptions {
    command_args: CommandArgs,
}

impl IntoArgs for ClientListOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

impl ClientListOptions {
    #[must_use]
    pub fn client_type(self, client_type: ClientType) -> Self {
        Self {
            command_args: self.command_args.arg("TYPE").arg(client_type),
        }
    }

    pub fn client_ids<II>(self, client_ids: II) -> Self
    where
        II: SingleArgOrCollection<i64>,
    {
        Self {
            command_args: self.command_args.arg("ID").arg(client_ids),
        }
    }
}

/// Result for the [`client_list`](crate::ConnectionCommands::client_list) command.
#[derive(Debug)]
pub struct ClientListResult {
    pub client_infos: Vec<ClientInfo>,
}

impl FromValue for ClientListResult {
    fn from_value(value: Value) -> Result<Self> {
        let lines: String = value.into()?;

        let client_infos: Result<Vec<ClientInfo>> = lines
            .split('\n')
            .map(ClientInfo::from_line)
            .collect();

        Ok(Self {
            client_infos: client_infos?,
        })
    }
}

/// Options for the [`client-kill`](crate::ConnectionCommands::client-kill) command.
#[derive(Default)]
pub struct ClientKillOptions {
    command_args: CommandArgs,
}

impl ClientKillOptions {
    #[must_use]
    pub fn id(self, client_id: i64) -> Self {
        Self {
            command_args: self.command_args.arg("ID").arg(client_id),
        }
    }

    #[must_use]
    pub fn client_type(self, client_type: ClientType) -> Self {
        Self {
            command_args: self.command_args.arg("TYPE").arg(client_type),
        }
    }

    #[must_use]
    pub fn user<U: Into<BulkString>>(self, username: U) -> Self {
        Self {
            command_args: self.command_args.arg("USER").arg(username),
        }
    }

    /// Address in the format of `ip:port`
    ///
    /// The ip:port should match a line returned by the
    /// [`client_list`](crate::ConnectionCommands::client_list) command (addr field).
    #[must_use]
    pub fn addr<A: Into<BulkString>>(self, addr: A) -> Self {
        Self {
            command_args: self.command_args.arg("ADDR").arg(addr),
        }
    }

    /// Kill all clients connected to specified local (bind) address.
    #[must_use]
    pub fn laddr<A: Into<BulkString>>(self, laddr: A) -> Self {
        Self {
            command_args: self.command_args.arg("LADDR").arg(laddr),
        }
    }

    /// By default this option is set to yes, that is, the client calling the command will not get killed,
    /// however setting this option to no will have the effect of also killing the client calling the command.
    #[must_use]
    pub fn skip_me(self, skip_me: bool) -> Self {
        Self {
            command_args: self
                .command_args
                .arg("SKIPME")
                .arg(if skip_me { "YES" } else { "NO" }),
        }
    }
}

impl IntoArgs for ClientKillOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Mode options for the [`client_pause`](crate::ConnectionCommands::client_pause) command.
pub enum ClientPauseMode {
    /// Clients are only blocked if they attempt to execute a write command.
    Write,
    /// This is the default mode. All client commands are blocked.
    All,
}

impl IntoArgs for ClientPauseMode {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(match self {
            ClientPauseMode::Write => BulkString::Str("WRITE"),
            ClientPauseMode::All => BulkString::Str("ALL"),
        })
    }
}

impl Default for ClientPauseMode {
    fn default() -> Self {
        ClientPauseMode::All
    }
}

/// Mode options for the [`client_reply`](crate::ConnectionCommands::client_reply) command.
pub enum ClientReplyMode {
    On,
    Off,
    Skip,
}

impl IntoArgs for ClientReplyMode {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(match self {
            ClientReplyMode::On => BulkString::Str("ON"),
            ClientReplyMode::Off => BulkString::Str("OFF"),
            ClientReplyMode::Skip => BulkString::Str("SKIP"),
        })
    }
}

/// Status options for the [`client_tracking`](crate::ConnectionCommands::client_tracking) command.
pub enum ClientTrackingStatus {
    On,
    Off
}

impl IntoArgs for ClientTrackingStatus {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(match self {
            ClientTrackingStatus::On => BulkString::Str("ON"),
            ClientTrackingStatus::Off => BulkString::Str("OFF"),
        })
    }
}

/// Options for the [`client_tracking`](crate::ConnectionCommands::client_tracking) command.
#[derive(Default)]
pub struct ClientTrackingOptions {
    command_args: CommandArgs,
}

impl ClientTrackingOptions {
    #[must_use]
    /// send invalidation messages to the connection with the specified ID.
    pub fn redirect(self, client_id: i64) -> Self {
        Self {
            command_args: self.command_args.arg("REDIRECT").arg(client_id),
        }
    }

    /// enable tracking in broadcasting mode.
    pub fn broadcasting(self) -> Self {
        Self {
            command_args: self.command_args.arg("BCAST"),
        }
    }

    /// for broadcasting, register a given key prefix, so that notifications
    /// will be provided only for keys starting with this string.
    ///
    /// This option can be given multiple times to register multiple prefixes.
    pub fn prefix<P: Into<BulkString>>(self, prefix: P) -> Self {
        Self {
            command_args: self.command_args.arg("PREFIX").arg(prefix),
        }
    }

    /// when broadcasting is NOT active, normally don't track keys in read only commands,
    /// unless they are called immediately after a `CLIENT CACHING yes` command.
    pub fn optin(self) -> Self {
        Self {
            command_args: self.command_args.arg("OPTIN"),
        }
    }

    /// when broadcasting is NOT active, normally track keys in read only commands,
    /// unless they are called immediately after a `CLIENT CACHING no` command.
    pub fn optout(self) -> Self {
        Self {
            command_args: self.command_args.arg("OPTOUT"),
        }
    }

    /// don't send notifications about keys modified by this connection itself.
    pub fn no_loop(self) -> Self {
        Self {
            command_args: self.command_args.arg("NOLOOP"),
        }
    }
}

impl IntoArgs for ClientTrackingOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}


/// Result for the [`client_trackinginfo`](crate::ConnectionCommands::client_trackinginfo) command.
pub struct ClientTrackingInfo {
    /// A list of tracking flags used by the connection. 
    pub flags: Vec<String>,

    /// The client ID used for notifications redirection, or -1 when none.
    pub redirect: i64,

    /// A list of key prefixes for which notifications are sent to the client.
    pub prefixes: Vec<String>
}

impl FromValue for ClientTrackingInfo {
    fn from_value(value: Value) -> Result<Self> {
        fn into_result(values: &mut HashMap<String, Value>) -> Option<ClientTrackingInfo> {
            Some(ClientTrackingInfo {
                flags: values.remove("flags")?.into().ok()?,
                redirect: values.remove("redirect")?.into().ok()?,
                prefixes: values.remove("prefixes")?.into().ok()?,
            })
        }

        into_result(&mut value.into()?)
            .ok_or_else(|| Error::Client("Cannot parse 
            ".to_owned()))
    }
}

/// Mode options for the [`client_unblock`](crate::ConnectionCommands::client_unblock) command.
pub enum ClientUnblockMode {
    /// By default the client is unblocked as if the timeout of the command was reached,
    Timeout,
    /// the behavior is to unblock the client returning as error the fact that the client was force-unblocked.
    Error,
}

impl IntoArgs for ClientUnblockMode {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(match self {
            ClientUnblockMode::Timeout => BulkString::Str("TIMEOUT"),
            ClientUnblockMode::Error => BulkString::Str("ERROR"),
        })
    }
}

impl Default for ClientUnblockMode {
    fn default() -> Self {
        ClientUnblockMode::Timeout
    }
}

/// Options for the [`hello`](crate::ConnectionCommands::hello) command.
#[derive(Default)]
pub struct HelloOptions {
    command_args: CommandArgs,
}

impl HelloOptions {
    #[must_use]
    pub fn new(protover: usize) -> Self {
        Self {
            command_args: CommandArgs::default().arg(protover),
        }
    }

    #[must_use]
    pub fn auth<U, P>(self, username: U, password: P) -> Self
    where
        U: Into<BulkString>,
        P: Into<BulkString>,
    {
        Self {
            command_args: self.command_args.arg("AUTH").arg(username).arg(password),
        }
    }

    #[must_use]
    pub fn set_name<C>(self, client_name: C) -> Self
    where
        C: Into<BulkString>,
    {
        Self {
            command_args: self.command_args.arg("SETNAME").arg(client_name),
        }
    }
}

impl IntoArgs for HelloOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

pub struct HelloResult {
    pub server: String,
    pub version: String,
    pub proto: usize,
    pub id: i64,
    pub mode: String,
    pub role: String,
    pub modules: Vec<String>,
}

impl FromValue for HelloResult {
    fn from_value(value: Value) -> Result<Self> {
        match &value {
            Value::Array(Array::Vec(v)) if v.len() == 14 => {
                fn into_result(values: &mut HashMap<String, Value>) -> Option<HelloResult> {
                    Some(HelloResult {
                        server: values.remove("server")?.into().ok()?,
                        version: values.remove("version")?.into().ok()?,
                        proto: values.remove("proto")?.into().ok()?,
                        id: values.remove("id")?.into().ok()?,
                        mode: values.remove("mode")?.into().ok()?,
                        role: values.remove("role")?.into().ok()?,
                        modules: values.remove("modules")?.into().ok()?,
                    })
                }

                into_result(&mut value.into()?)
                    .ok_or_else(|| Error::Client("Cannot parse HelloResult".to_owned()))
            }
            _ => Err(Error::Client("Cannot parse HelloResult".to_owned())),
        }
    }
}

/// Options for the [`ping`](crate::ConnectionCommands::ping) command.
#[derive(Default)]
pub struct PingOptions {
    command_args: CommandArgs,
}

impl PingOptions {
    #[must_use]
    pub fn message<M: Into<BulkString>>(self, message: M) -> Self {
        Self {
            command_args: self.command_args.arg(message),
        }
    }
}

impl IntoArgs for PingOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}