redis-asyncx 0.1.0

An asynchronous Redis client library and a Redis CLI built in Rust.
Documentation
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
//! A Redis CLI application.
//!
//! This application is a simple command-line interface for interacting with a Redis database.
//! It allows users to connect to a Redis server, send commands, and receive responses.
//! It is built using the `redis-async` lib crate in this repository, which provides a high-level API for working with Redis.
//! The CLI can operate in both interactive and non-interactive modes.
//! In interactive mode, users can enter commands directly into the terminal.
//! In non-interactive mode, commands can be passed as arguments.
//! The application supports various Redis commands, including:
//! - `HELLO`: Switch RESP protocol version.
//! - `PING`: Check if the server is alive.
//! - `GET`: Retrieve the value of a key.
//! - `SET`: Set the value of a key.
//! - `DEL`: Delete a key.
//! - `EXISTS`: Check if a key exists.
//! - `INFO`: Get information about the server.
//! - `FLUSHDB`: Flush the current database.
//! - `FLUSHALL`: Flush all databases.
//! - `KEYS`: Get all keys matching a pattern.
//! - `SCAN`: Scan the keys in the database.
//! - `HGET`: Get the value of a field in a hash.
//! - `HSET`: Set the value of a field in a hash.
//! - `HDEL`: Delete a field in a hash.
//! - `HGETALL`: Get all fields and values in a hash.
//! - `LPUSH`: Push a value onto a list.
//! - `RPUSH`: Push a value onto a list.
//! - `LPOP`: Pop a value from a list.
//! - `RPOP`: Pop a value from a list.
//! - `LRANGE`: Get a range of values from a list.
//! - `SADD`: Add a member to a set.
//! - `SREM`: Remove a member from a set.
//! - `SMEMBERS`: Get all members of a set.
//! - `ZADD`: Add a member to a sorted set.
//! - `ZREM`: Remove a member from a sorted set.
//! - `ZRANGE`: Get a range of members from a sorted set.
//! - `ZRANK`: Get the rank of a member in a sorted set.
//! - `ZREVRANK`: Get the reverse rank of a member in a sorted set.
//! - `ZCARD`: Get the number of members in a sorted set.
//! - `ZCOUNT`: Get the number of members in a sorted set with scores within a given range.
//! - `ZINCRBY`: Increment the score of a member in a sorted set.

use bytes::Bytes;
use clap::{Parser, Subcommand};
use colored::Colorize;
use redis_asyncx::{Client, Result};
use shlex::split;
use std::io::{self, Write};
use std::str;

#[derive(Parser, Debug)]
#[command(name = "redis-async-cli")]
#[command(version = "0.1.0")]
#[command(about = "redis-cli 0.1.0", long_about = None)]
struct Cli {
    #[arg(long, default_value = "127.0.0.1", help = "Redis server hostname.")]
    host: String,
    #[arg(short, long, default_value = "6379", help = "Redis server port.")]
    port: u16,
    #[command(flatten)]
    verbose: clap_verbosity_flag::Verbosity,
    // Redis command
    #[command(subcommand)]
    command: Option<RedisCommand>,
}

#[derive(Parser, Debug)]
struct CliInteractive {
    // Redis command
    #[command(subcommand)]
    command: Option<RedisCommand>,
}

/// This enum represents the various commands that can be executed in the CLI.
/// Each variant corresponds to a Redis command and its associated arguments.
#[derive(Subcommand, Debug, Clone)]
enum RedisCommand {
    /// Switch RESP protocol version.
    Hello {
        /// RESP protocol version to switch to.
        proto: Option<u8>,
    },
    /// Check if the server is alive.
    Ping {
        /// Message to send to the server.
        message: Option<Bytes>,
    },
    /// Get the value of a key.
    Get {
        /// Key to retrieve.
        key: String,
    },
    /// Set the value of a key.
    Set {
        /// Key to set.
        key: String,
        /// Value to set.
        value: Bytes,
    },
    /// Delete a key.
    Del {
        /// Keys to delete.
        keys: Vec<String>,
    },
    /// Check if a key exists.
    Exists {
        /// Keys to check.
        keys: Vec<String>,
    },
    /// Expire a key after a given number of seconds.
    Expire {
        /// Key to expire.
        key: String,
        /// Number of seconds to expire the key after.
        seconds: i64,
    },
    /// Get the time to live of a key.
    Ttl {
        /// Key to check.
        key: String,
    },
    /// Increment the value of a key.
    Incr {
        /// Key to increment.
        key: String,
    },
    /// Decrement the value of a key.
    Decr {
        /// Key to decrement.
        key: String,
    },
    /// Push a value onto a list. Left push.
    Lpush {
        /// Key of the list.
        key: String,
        /// Values to push onto the list.
        values: Vec<String>,
    },
    /// Push a value onto a list. Right push.
    Rpush {
        /// Key of the list.
        key: String,
        /// Values to push onto the list.
        values: Vec<String>,
    },
    /// Pop values from a list. Left pop.
    Lpop {
        /// Key of the list.
        key: String,
        /// Number of elements to pop.
        /// If not specified, it will pop only one element.
        count: Option<u64>,
    },
    /// Pop values from a list. Right pop.
    Rpop {
        /// Key of the list.
        key: String,
        /// Number of elements to pop.
        /// If not specified, it will pop only one element.
        count: Option<u64>,
    },
    /// Get a range of values from a list.
    Lrange {
        /// Key of the list.
        key: String,
        /// Start index of the range.
        start: i64,
        /// End index of the range.
        end: i64,
    },
    /// Clear the screen.
    Clear,
}

impl RedisCommand {
    async fn execute(&self, client: &mut Client) -> Result<()> {
        match self {
            RedisCommand::Hello { proto } => {
                let response = client.hello(*proto).await?;

                for (key, value) in response {
                    if let Ok(string) = str::from_utf8(&value) {
                        println!("\"{}\" => \"{}\"", key, string);
                    } else {
                        println!("\"{}\" => {:?}", key, value);
                    }
                }
            }
            RedisCommand::Ping { message } => {
                let message = message.as_deref();

                let response = client.ping(message).await?;
                if let Ok(string) = str::from_utf8(&response) {
                    // we need to format simple string and bulk string differently
                    // simple string: no quotes
                    // bulk string: with quotes
                    if message.is_some() {
                        println!("\"{}\"", string);
                    } else {
                        println!("PONG");
                    }
                } else {
                    println!("{response:?}");
                }
            }
            RedisCommand::Get { key } => {
                let response = client.get(key).await?;
                if let Some(value) = response {
                    if let Ok(string) = str::from_utf8(&value) {
                        println!("\"{}\"", string);
                    } else {
                        println!("{:?}", value);
                    }
                } else {
                    println!("(nil)");
                }
            }
            RedisCommand::Set { key, value } => {
                let response = client.set(key, value).await?;
                if let Some(value) = response {
                    if let Ok(string) = str::from_utf8(&value) {
                        println!("{}", string);
                    } else {
                        println!("{:?}", value);
                    }
                } else {
                    println!("(nil)");
                }
            }
            RedisCommand::Del { keys } => {
                let response = client
                    .del(keys.iter().map(String::as_str).collect::<Vec<&str>>())
                    .await?;
                println!("{response:?}");
            }
            RedisCommand::Exists { keys } => {
                let response = client
                    .exists(keys.iter().map(String::as_str).collect::<Vec<&str>>())
                    .await?;
                println!("(integer) {response}");
            }
            RedisCommand::Expire { key, seconds } => {
                let response = client.expire(key, *seconds).await?;
                println!("(integer) {response}");
            }
            RedisCommand::Ttl { key } => {
                let response = client.ttl(key).await?;
                println!("(integer) {response}");
            }
            RedisCommand::Incr { key } => {
                let response = client.incr(key).await?;
                println!("(integer) {response}");
            }
            RedisCommand::Decr { key } => {
                let response = client.decr(key).await?;
                println!("(integer) {response}");
            }
            RedisCommand::Lpush { key, values } => {
                let response = client
                    .lpush(key, values.iter().map(|s| s.as_bytes()).collect())
                    .await?;
                println!("(integer) {response}");
            }
            RedisCommand::Rpush { key, values } => {
                let response = client
                    .rpush(key, values.iter().map(|s| s.as_bytes()).collect())
                    .await?;
                println!("(integer) {response}");
            }
            RedisCommand::Lpop { key, count } => {
                match count {
                    Some(count) => {
                        // multiple pop
                        if let Some(response) = client.lpop_n(key, *count).await? {
                            for line in response {
                                if let Ok(string) = str::from_utf8(&line) {
                                    println!("\"{}\"", string);
                                } else {
                                    println!("{line:?}");
                                }
                            }
                        } else {
                            println!("(nil)");
                        }
                    }
                    None => {
                        // single pop
                        if let Some(response) = client.lpop(key).await? {
                            if let Ok(string) = str::from_utf8(&response) {
                                println!("\"{}\"", string);
                            } else {
                                println!("{response:?}");
                            }
                        } else {
                            println!("(nil)");
                        }
                    }
                }
            }
            RedisCommand::Rpop { key, count } => {
                match count {
                    Some(count) => {
                        // multiple pop
                        if let Some(response) = client.rpop_n(key, *count).await? {
                            for line in response {
                                if let Ok(string) = str::from_utf8(&line) {
                                    println!("\"{}\"", string);
                                } else {
                                    println!("{line:?}");
                                }
                            }
                        } else {
                            println!("(nil)");
                        }
                    }
                    None => {
                        // single pop
                        if let Some(response) = client.rpop(key).await? {
                            if let Ok(string) = str::from_utf8(&response) {
                                println!("\"{}\"", string);
                            } else {
                                println!("{response:?}");
                            }
                        } else {
                            println!("(nil)");
                        }
                    }
                }
            }
            RedisCommand::Lrange { key, start, end } => {
                let response = client.lrange(key, *start, *end).await?;
                for line in response {
                    if let Ok(string) = str::from_utf8(&line) {
                        println!("\"{}\"", string);
                    } else {
                        println!("{line:?}");
                    }
                }
            }
            RedisCommand::Clear => {
                clear_screen();
            }
        }

        Ok(())
    }
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<()> {
    // Collect raw arguments and normalize subcommands to lowercase
    let mut args: Vec<String> = std::env::args().collect();
    if args.len() > 1 {
        args[1] = args[1].to_lowercase(); // Normalize the subcommand
    }

    let cli = Cli::parse_from(&args);

    // Set up the address for the Redis server
    let mut addr = String::with_capacity(cli.host.len() + 1 + cli.port.to_string().len());
    addr.push_str(&cli.host);
    addr.push(':');
    addr.push_str(&cli.port.to_string());

    // Connect to the Redis server
    let mut client = Client::connect(&addr).await?;

    if let Some(command) = cli.command {
        // If a command is provided, execute it
        command.execute(&mut client).await?;
    } else {
        // Interactive mode if no command is provided
        println!("{}", "Interactive mode. Type 'exit' to quit.".green());

        loop {
            print!("{addr}> "); // Print the prompt
            io::stdout().flush().unwrap(); // Flush the buffer

            let mut input = String::new();
            std::io::stdin().read_line(&mut input)?;
            let input = input.trim();

            if input == "exit" {
                break;
            }

            let args = split(input).unwrap();
            if args.is_empty() {
                continue;
            }

            // Convert the first argument to lowercase
            let mut args = args.to_vec();
            let lowercased = args[0].to_lowercase();
            args[0] = lowercased;

            // we need to insert the command name at the beginning of the args vector
            // otherwise clap parser will not be able to parse the command
            args.insert(0, "".into());

            match CliInteractive::try_parse_from(args) {
                Ok(cli) => {
                    // If a command is provided, execute it
                    if let Some(command) = cli.command {
                        match command.execute(&mut client).await {
                            Ok(_) => {}
                            Err(e) => {
                                eprintln!("Error executing command: {e}");
                                // do not fail the program, just continue
                                continue;
                            }
                        }
                    } else {
                        println!("Unknown command: {input}");
                    }
                }
                Err(e) => {
                    eprintln!("Error parsing command: {e}");
                    // do not fail the program, just continue
                    continue;
                }
            };
        }
    }

    Ok(())
}

// TODO: catch signals like Ctrl+C and Ctrl+D
fn clear_screen() {
    print!("\x1B[2J\x1B[1;1H"); // Clears the screen and moves the cursor to the top-left
    std::io::stdout().flush().unwrap();
}