redisgo 0.1.3

A simple and ergonomic Redis client wrapper for 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
//! # RedisGo
//!
//! A simple and ergonomic Redis client wrapper for Rust.
//!
//! RedisGo provides a convenient API for common Redis operations such as
//! setting, getting, deleting keys, and more. It uses a singleton pattern
//! for easy access throughout your application.
//!
//! ## Quick Start
//!
//! Set the `REDIS_URL` environment variable or create a `.env` file:
//!
//! ```text
//! REDIS_URL=redis://127.0.0.1/
//! ```
//!
//! Then use the library:
//!
//! ```rust,no_run
//! use redisgo::RedisGo;
//!
//! fn main() -> redis::RedisResult<()> {
//!     // Set a value
//!     RedisGo::set("my_key", "my_value")?;
//!
//!     // Get a value
//!     let value = RedisGo::get("my_key")?;
//!     println!("Value: {:?}", value);
//!
//!     // Delete a key
//!     RedisGo::delete("my_key")?;
//!
//!     Ok(())
//! }
//! ```

use redis::{Commands, Connection, RedisResult};
use std::env;
use std::fs;
use std::sync::OnceLock;

// Lazy static singleton
static REDIS_GO: OnceLock<RedisGo> = OnceLock::new();

/// Load `REDIS_URL` from environment or `.env` file
fn get_redis_url() -> Option<String> {
    // First check environment variable
    if let Ok(url) = env::var("REDIS_URL") {
        return Some(url);
    }

    // Fall back to .env file
    if let Ok(content) = fs::read_to_string(".env") {
        for line in content.lines() {
            let line = line.trim();
            if line.starts_with('#') || line.is_empty() {
                continue;
            }
            if let Some((k, v)) = line.split_once('=') {
                if k.trim() == "REDIS_URL" {
                    return Some(v.trim().to_string());
                }
            }
        }
    }

    None
}

/// The main Redis client wrapper providing simplified access to Redis operations.
///
/// `RedisGo` manages a Redis connection and provides both static methods for
/// convenient access via a global singleton, and instance methods for more
/// control over the connection lifecycle.
///
/// # Example
///
/// ```rust,no_run
/// use redisgo::RedisGo;
///
/// // Using static methods (recommended for most cases)
/// RedisGo::set("key", "value").unwrap();
/// let value = RedisGo::get("key").unwrap();
///
/// // Using instance methods
/// use redisgo::get_redisgo;
/// let redis = get_redisgo();
/// let status = redis.get_connection_status();
/// ```
pub struct RedisGo {
    client: Option<redis::Client>,
    connection: std::sync::Mutex<Option<Connection>>,
}

impl RedisGo {
    /// Creates a new `RedisGo` instance.
    ///
    /// This method loads the `REDIS_URL` from the environment or a `.env` file
    /// and initializes the Redis client.
    ///
    /// # Errors
    ///
    /// Returns `Ok` even if the Redis URL is not set (client will be `None`).
    /// Connection errors will occur when attempting to use the client.
    pub fn new() -> RedisResult<Self> {
        let redis_url = get_redis_url();

        let client = match redis_url {
            Some(url) => redis::Client::open(url).ok(),
            None => None,
        };

        Ok(RedisGo {
            client,
            connection: std::sync::Mutex::new(None),
        })
    }

    fn get_connection(&self) -> RedisResult<std::sync::MutexGuard<'_, Option<Connection>>> {
        let mut conn_guard = self.connection.lock().unwrap();
        if conn_guard.is_none() {
            if let Some(client) = &self.client {
                *conn_guard = Some(client.get_connection()?);
            } else {
                return Err(redis::RedisError::from((
                    redis::ErrorKind::Io,
                    "Redis client not initialized",
                )));
            }
        }
        Ok(conn_guard)
    }

    fn execute_with_connection<F, T>(&self, operation: F) -> RedisResult<T>
    where
        F: FnOnce(&mut Connection) -> RedisResult<T>,
    {
        let mut conn_guard = self.get_connection()?;
        if let Some(ref mut conn) = *conn_guard {
            operation(conn)
        } else {
            Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Connection not initialized",
            )))
        }
    }

    /// Sets a key-value pair in Redis.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to set
    /// * `value` - The value to associate with the key
    ///
    /// # Errors
    ///
    /// Returns an error if the Redis client is not initialized or the operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use redisgo::RedisGo;
    /// RedisGo::set("my_key", "my_value").unwrap();
    /// ```
    pub fn set(key: &str, value: &str) -> RedisResult<()> {
        let redisgo = get_redisgo();
        if redisgo.client.is_none() {
            return Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Redis client not initialized",
            )));
        }
        redisgo.execute_with_connection(|conn| conn.set(key, value))
    }
    /// Sets a key-value pair in Redis with an optional time-to-live (TTL).
    ///
    /// # Arguments
    ///
    /// * `key` - The key to set
    /// * `value` - The value to associate with the key
    /// * `ttl` - Optional TTL in seconds. If `None`, the key won't expire.
    ///
    /// # Errors
    ///
    /// Returns an error if the Redis client is not initialized or the operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use redisgo::RedisGo;
    /// // Set a key that expires in 60 seconds
    /// RedisGo::set_with_ttl("temp_key", "temp_value", Some(60)).unwrap();
    /// ```
    pub fn set_with_ttl(key: &str, value: &str, ttl: Option<usize>) -> RedisResult<()> {
        let redisgo = get_redisgo();
        if redisgo.client.is_none() {
            return Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Redis client not initialized",
            )));
        }
        redisgo.execute_with_connection(|conn| {
            if let Some(ttl) = ttl.map(|t| t.try_into().unwrap()) {
                conn.set_ex(key, value, ttl)
            } else {
                conn.set(key, value)
            }
        })
    }

    /// Gets a value from Redis by key.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to retrieve
    ///
    /// # Returns
    ///
    /// Returns `Ok(Some(value))` if the key exists, `Ok(None)` if it doesn't.
    ///
    /// # Errors
    ///
    /// Returns an error if the Redis client is not initialized or the operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use redisgo::RedisGo;
    /// if let Some(value) = RedisGo::get("my_key").unwrap() {
    ///     println!("Value: {}", value);
    /// }
    /// ```
    pub fn get(key: &str) -> RedisResult<Option<String>> {
        let redisgo = get_redisgo();
        if redisgo.client.is_none() {
            return Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Redis client not initialized",
            )));
        }
        redisgo.execute_with_connection(|conn| conn.get(key))
    }

    /// Deletes a key from Redis.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to delete
    ///
    /// # Errors
    ///
    /// Returns an error if the Redis client is not initialized or the operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use redisgo::RedisGo;
    /// RedisGo::delete("my_key").unwrap();
    /// ```
    pub fn delete(key: &str) -> RedisResult<()> {
        let redisgo = get_redisgo();
        if redisgo.client.is_none() {
            return Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Redis client not initialized",
            )));
        }
        redisgo.execute_with_connection(|conn| conn.del(key))
    }

    /// Checks if a key exists in Redis.
    ///
    /// # Arguments
    ///
    /// * `key` - The key to check
    ///
    /// # Returns
    ///
    /// Returns `true` if the key exists, `false` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if the Redis client is not initialized or the operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use redisgo::RedisGo;
    /// if RedisGo::exists("my_key").unwrap() {
    ///     println!("Key exists!");
    /// }
    /// ```
    pub fn exists(key: &str) -> RedisResult<bool> {
        let redisgo = get_redisgo();
        if redisgo.client.is_none() {
            return Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Redis client not initialized",
            )));
        }
        redisgo.execute_with_connection(|conn| conn.exists(key))
    }

    /// Flushes all keys from all databases.
    ///
    /// **Warning:** This will delete ALL data in Redis. Use with caution!
    ///
    /// # Errors
    ///
    /// Returns an error if the Redis client is not initialized or the operation fails.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use redisgo::RedisGo;
    /// RedisGo::flush_all().unwrap();
    /// ```
    pub fn flush_all() -> RedisResult<()> {
        let redisgo = get_redisgo();
        if redisgo.client.is_none() {
            return Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Redis client not initialized",
            )));
        }
        redisgo.execute_with_connection(|conn| conn.flushall())
    }

    /// Returns a reference to the underlying Redis client.
    ///
    /// # Panics
    ///
    /// Panics if the Redis client is not initialized.
    pub fn get_client(&self) -> &redis::Client {
        self.client.as_ref().expect("Redis client not initialized")
    }

    /// Checks if a connection to Redis has been established.
    ///
    /// Note: This only checks if a connection object exists, not if the
    /// connection is still alive.
    pub fn is_connected(&self) -> bool {
        self.connection.lock().unwrap().is_some()
    }

    /// Sends a PING command to Redis and returns the response.
    ///
    /// # Returns
    ///
    /// Returns "PONG" if the connection is healthy.
    ///
    /// # Errors
    ///
    /// Returns an error if the Redis client is not initialized or the connection fails.
    pub fn ping(&self) -> RedisResult<String> {
        if self.client.is_none() {
            return Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Redis client not initialized",
            )));
        }
        let mut conn_guard = self.get_connection()?;
        if let Some(ref mut conn) = *conn_guard {
            conn.ping()
        } else {
            Err(redis::RedisError::from((
                redis::ErrorKind::Io,
                "Connection not initialized",
            )))
        }
    }

    /// Returns the current connection status as a human-readable string.
    pub fn get_connection_status(&self) -> String {
        if self.is_connected() {
            "Connected".to_string()
        } else {
            "Not connected".to_string()
        }
    }

    /// Returns information about the Redis client configuration.
    pub fn get_client_info(&self) -> String {
        format!("Client Info: {:?}", self.client.as_ref().map(|c| c.get_connection_info()))
    }
}

impl Default for RedisGo {
    fn default() -> Self {
        Self::new().expect("Failed to initialize RedisGo")
    }
}

/// Returns a reference to the global `RedisGo` singleton instance.
///
/// This function initializes the singleton on first call and returns
/// the same instance on subsequent calls.
///
/// # Panics
///
/// Panics if the `RedisGo` instance cannot be created.
///
/// # Example
///
/// ```rust,no_run
/// use redisgo::get_redisgo;
///
/// let redis = get_redisgo();
/// println!("Status: {}", redis.get_connection_status());
/// ```
pub fn get_redisgo() -> &'static RedisGo {
    REDIS_GO.get_or_init(|| RedisGo::new().expect("Failed to initialize RedisGo"))
}