bootrust 0.1.0

An elegant macroless data access layer abstraction, simple and easy-use object-relational mapping powered by the Serde serialization framework. 一个优雅的无宏的数据访问层抽象, 由serde序列化框架提供支持的简单易用的对象关系映射
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
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
use async_trait::async_trait;
use bb8::Pool;
use bb8_redis::RedisConnectionManager;
use redis::{AsyncCommands, ErrorKind, RedisError};
use serde::{de::DeserializeOwned, Serialize};
use std::marker::PhantomData;
use std::time::Duration;

// data cache object
#[async_trait]
pub trait Dco<T>
where
    T: 'static + Sized + Sync + Send + Serialize + DeserializeOwned,
{
    type Error;

    async fn get(&self, key: &str) -> Result<Option<T>, Self::Error>;
    async fn set(&self, key: &str, value: T, ttl: Option<Duration>) -> Result<(), Self::Error>;
    async fn del(&self, key: &str) -> Result<(), Self::Error>;
    async fn exists(&self, key: &str) -> Result<bool, Self::Error>;
}

pub struct RedisCache<T> {
    pool: Pool<RedisConnectionManager>,
    _table: PhantomData<T>,
}

impl<T> RedisCache<T> {
    pub async fn new(url: &str) -> Result<Self, RedisError> {
        let manager = RedisConnectionManager::new(url)?;
        let pool = Pool::builder().build(manager).await?;
        Ok(RedisCache {
            pool: pool,
            _table: PhantomData,
        })
    }
}

#[async_trait]
impl<T> Dco<T> for RedisCache<T>
where
    T: 'static + Sized + Sync + Send + Serialize + DeserializeOwned,
{
    type Error = RedisError;

    async fn get(&self, key: &str) -> Result<Option<T>, Self::Error> {
        let mut conn = match self.pool.get().await {
            Ok(conn) => conn,
            _ => {
                return Err(RedisError::from((
                    ErrorKind::ClientError,
                    "error getting connect",
                )))
            }
        };

        let result: Option<Vec<u8>> = conn.get(key).await?;
        match result {
            Some(bytes) => {
                let value: T = bincode::deserialize(&bytes).map_err(|e| {
                    redis::RedisError::from((
                        redis::ErrorKind::TypeError,
                        "Deserialization error",
                        e.to_string(),
                    ))
                })?;
                Ok(Some(value))
            }
            None => Ok(None),
        }
    }

    async fn set(&self, key: &str, value: T, ttl: Option<Duration>) -> Result<(), Self::Error> {
        let mut conn = match self.pool.get().await {
            Ok(conn) => conn,
            _ => {
                return Err(RedisError::from((
                    ErrorKind::ClientError,
                    "error getting connect",
                )))
            }
        };

        let bytes = bincode::serialize(&value).map_err(|e| {
            redis::RedisError::from((
                redis::ErrorKind::TypeError,
                "Serialization error",
                e.to_string(),
            ))
        })?;

        match ttl {
            Some(duration) => conn.set_ex(key, bytes, duration.as_secs() as u64).await,
            None => conn.set(key, bytes).await,
        }
    }

    async fn del(&self, key: &str) -> Result<(), Self::Error> {
        let mut conn = match self.pool.get().await {
            Ok(conn) => conn,
            _ => {
                return Err(RedisError::from((
                    ErrorKind::ClientError,
                    "error getting connect",
                )))
            }
        };
        conn.del(key).await
    }

    async fn exists(&self, key: &str) -> Result<bool, Self::Error> {
        // let mut conn = self.pool.get().await.map_err(redis::RedisError::from)?;
        let mut conn = match self.pool.get().await {
            Ok(conn) => conn,
            _ => {
                return Err(RedisError::from((
                    ErrorKind::ClientError,
                    "error getting connect",
                )))
            }
        };

        conn.exists(key).await
    }
}

pub trait CachedData = 'static + Sized + Sync + Send + Serialize + DeserializeOwned;
#[async_trait]
pub trait CacheDb {
    type Error;

    async fn get<T: CachedData>(&self, key: &str) -> Result<Option<T>, Self::Error>;
    async fn set<T: CachedData>(
        &self,
        key: &str,
        value: T,
        ttl: Option<Duration>,
    ) -> Result<(), Self::Error>;
    async fn del<T: CachedData>(&self, key: &str) -> Result<(), Self::Error>;
    async fn exists<T: CachedData>(&self, key: &str) -> Result<bool, Self::Error>;
}

pub struct Redis {
    pool: Pool<RedisConnectionManager>,
}

impl Redis {
    pub async fn new(url: &str) -> Result<Self, RedisError> {
        let manager = RedisConnectionManager::new(url)?;
        let pool = Pool::builder().build(manager).await?;
        Ok(Redis { pool: pool })
    }
}

pub async fn auto_config() -> impl CacheDb {
    Redis::new(
        &std::env::var("BOOTRUST_REDIS_URL")
            .unwrap_or_else(|_| "redis://root@127.0.0.1:6379/1".to_string()),
    )
    .await
    .unwrap()
}

#[async_trait]
impl CacheDb for Redis {
    type Error = RedisError;

    async fn get<T: CachedData>(&self, key: &str) -> Result<Option<T>, Self::Error> {
        let mut conn = match self.pool.get().await {
            Ok(conn) => conn,
            _ => {
                return Err(RedisError::from((
                    ErrorKind::ClientError,
                    "error getting connect",
                )))
            }
        };

        let result: Option<Vec<u8>> = conn.get(key).await?;
        match result {
            Some(bytes) => {
                let value: T = bincode::deserialize(&bytes).map_err(|e| {
                    redis::RedisError::from((
                        redis::ErrorKind::TypeError,
                        "Deserialization error",
                        e.to_string(),
                    ))
                })?;
                Ok(Some(value))
            }
            None => Ok(None),
        }
    }

    async fn set<T: CachedData>(
        &self,
        key: &str,
        value: T,
        ttl: Option<Duration>,
    ) -> Result<(), Self::Error> {
        let mut conn = match self.pool.get().await {
            Ok(conn) => conn,
            _ => {
                return Err(RedisError::from((
                    ErrorKind::ClientError,
                    "error getting connect",
                )))
            }
        };

        let bytes = bincode::serialize(&value).map_err(|e| {
            redis::RedisError::from((
                redis::ErrorKind::TypeError,
                "Serialization error",
                e.to_string(),
            ))
        })?;

        match ttl {
            Some(duration) => conn.set_ex(key, bytes, duration.as_secs() as u64).await,
            None => conn.set(key, bytes).await,
        }
    }

    async fn del<T: CachedData>(&self, key: &str) -> Result<(), Self::Error> {
        let mut conn = match self.pool.get().await {
            Ok(conn) => conn,
            _ => {
                return Err(RedisError::from((
                    ErrorKind::ClientError,
                    "error getting connect",
                )))
            }
        };
        conn.del(key).await
    }

    async fn exists<T: CachedData>(&self, key: &str) -> Result<bool, Self::Error> {
        // let mut conn = self.pool.get().await.map_err(redis::RedisError::from)?;
        let mut conn = match self.pool.get().await {
            Ok(conn) => conn,
            _ => {
                return Err(RedisError::from((
                    ErrorKind::ClientError,
                    "error getting connect",
                )))
            }
        };

        conn.exists(key).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};
    use serial_test::serial;
    use std::time::Duration;
    use tokio::time::sleep; // Import sleep for testing TTL

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct TestData {
        a: i32,
        b: String,
    }

    async fn setup_cache<T>() -> RedisCache<T> {
        // Use a different database number for testing to avoid conflicts
        // with any existing data in the default database.
        RedisCache::new("redis://root@127.0.0.1:6379/1")
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn test_set_get_del() {
        let cache = setup_cache().await;
        let key = "test_key";
        let value = TestData {
            a: 42,
            b: "hello".to_string(),
        };

        // Set the value
        cache.set(key, value, None).await.unwrap();

        // Get the value and check it
        let retrieved_value: Option<TestData> = cache.get(key).await.unwrap();
        assert_eq!(
            retrieved_value,
            Some(TestData {
                a: 42,
                b: "hello".to_string()
            })
        );

        // Delete the value
        cache.del(key).await.unwrap();

        // Get the value again, should be None
        let retrieved_value: Option<TestData> = cache.get(key).await.unwrap();
        assert_eq!(retrieved_value, None);
    }

    #[tokio::test]
    async fn test_set_get_with_ttl() {
        let cache = setup_cache().await;
        let key = "test_key_ttl";
        let value = TestData {
            a: 123,
            b: "world".to_string(),
        };
        let ttl = Duration::from_secs(1); // Short TTL for testing

        // Set the value with TTL
        cache.set(key, value, Some(ttl)).await.unwrap();

        // Get the value immediately, should be Some
        let retrieved_value: Option<TestData> = cache.get(key).await.unwrap();
        assert_eq!(
            retrieved_value,
            Some(TestData {
                a: 123,
                b: "world".to_string()
            })
        );

        // Wait for longer than the TTL
        sleep(Duration::from_secs(2)).await;

        // Get the value again, should be None
        let retrieved_value: Option<TestData> = cache.get(key).await.unwrap();
        assert_eq!(retrieved_value, None);
    }

    #[tokio::test]
    async fn test_exists() {
        let cache = setup_cache().await;
        let key = "test_key_exists";
        let non_existent_key = "non_existent_key";
        let value = TestData {
            a: 1,
            b: "exists".to_string(),
        };

        // Key shouldn't exist yet
        assert!(!cache.exists(key).await.unwrap());

        // Set the value
        cache.set(key, value, None).await.unwrap();

        // Now the key should exist
        assert!(cache.exists(key).await.unwrap());

        // Non-existent key should not exist
        assert!(!cache.exists(non_existent_key).await.unwrap());

        // Delete Key
        cache.del(key).await.unwrap();
        assert!(!cache.exists(key).await.unwrap());
    }

    #[tokio::test]
    async fn test_get_nonexistent() {
        let cache = setup_cache().await;
        let key = "nonexistent_key";

        // Get a non-existent key, should return None
        let retrieved_value: Option<TestData> = cache.get(key).await.unwrap();
        assert_eq!(retrieved_value, None);
    }

    #[tokio::test]
    async fn test_del_nonexistent() {
        let cache: RedisCache<TestData> = setup_cache().await;
        let key = "nonexistent_key_to_delete";

        // Delete a non-existent key.  Should not error.
        let result = cache.del(key).await;
        assert!(result.is_ok());
    }

    async fn setup_cache_db() -> Redis {
        // Use a different database number for testing to avoid conflicts
        // with any existing data in the default database.
        Redis::new("redis://root@127.0.0.1:6379/2").await.unwrap()
    }

    #[tokio::test]
    async fn test_db_set_get_del() {
        let cache = setup_cache_db().await;
        let key = "test_key";
        let value = TestData {
            a: 42,
            b: "hello".to_string(),
        };

        // Set the value
        cache.set(key, value, None).await.unwrap();

        // Get the value and check it
        let retrieved_value: Option<TestData> = cache.get(key).await.unwrap();
        assert_eq!(
            retrieved_value,
            Some(TestData {
                a: 42,
                b: "hello".to_string()
            })
        );

        // Delete the value
        cache.del::<TestData>(key).await.unwrap();

        // Get the value again, should be None
        let retrieved_value: Option<TestData> = cache.get(key).await.unwrap();
        assert_eq!(retrieved_value, None);
    }

    #[tokio::test]
    async fn test_db_set_get_with_ttl() {
        let cache = setup_cache_db().await;
        let key = "test_key_ttl";
        let value = TestData {
            a: 123,
            b: "world".to_string(),
        };
        let ttl = Duration::from_secs(1); // Short TTL for testing

        // Set the value with TTL
        cache.set::<TestData>(key, value, Some(ttl)).await.unwrap();

        // Get the value immediately, should be Some
        let retrieved_value: Option<TestData> = cache.get::<TestData>(key).await.unwrap();
        assert_eq!(
            retrieved_value,
            Some(TestData {
                a: 123,
                b: "world".to_string()
            })
        );

        // Wait for longer than the TTL
        sleep(Duration::from_secs(2)).await;

        // Get the value again, should be None
        let retrieved_value: Option<TestData> = cache.get(key).await.unwrap();
        assert_eq!(retrieved_value, None);
    }

    #[tokio::test]
    #[serial]
    async fn test_db_exists() {
        let cache = setup_cache().await;
        let key = "test_key_exists";
        let non_existent_key = "non_existent_key";
        let value = TestData {
            a: 1,
            b: "exists".to_string(),
        };

        // Key shouldn't exist yet
        assert!(!cache.exists(key).await.unwrap());

        // Set the value
        cache.set(key, value, None).await.unwrap();

        // Now the key should exist
        assert!(cache.exists(key).await.unwrap());

        // Non-existent key should not exist
        assert!(!cache.exists(non_existent_key).await.unwrap());

        // Delete Key
        cache.del(key).await.unwrap();
        assert!(!cache.exists(key).await.unwrap());
    }

    #[tokio::test]
    async fn test_db_get_nonexistent() {
        let cache = setup_cache_db().await;
        let key = "nonexistent_key";

        // Get a non-existent key, should return None
        let retrieved_value: Option<TestData> = cache.get::<TestData>(key).await.unwrap();
        assert_eq!(retrieved_value, None);
    }

    #[tokio::test]
    async fn test_db_del_nonexistent() {
        let cache: Redis = setup_cache_db().await;
        let key = "nonexistent_key_to_delete";

        // Delete a non-existent key.  Should not error.
        let result = cache.del::<TestData>(key).await;
        assert!(result.is_ok());
    }
}