databeam/cachedb.rs
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
//! Redis connection manager
use redis::{Commands, ToRedisArgs};
use serde::{de::DeserializeOwned, Serialize};
#[allow(type_alias_bounds)]
pub type TimedObject<T: Serialize + DeserializeOwned> = (i64, T);
pub const EXPIRE_AT: i64 = 3_600_000;
#[derive(Clone)]
pub struct CacheDB {
pub client: redis::Client,
}
impl CacheDB {
pub async fn new() -> CacheDB {
return CacheDB {
client: redis::Client::open("redis://127.0.0.1:6379").unwrap(),
};
}
pub async fn get_con(&self) -> redis::Connection {
self.client.get_connection().unwrap()
}
/// Get a cache object by its identifier
///
/// # Arguments:
/// * `id` - `String` of the object's id
pub async fn get<I>(&self, id: I) -> Option<String>
where
I: ToRedisArgs,
{
match self.get_con().await.get(id) {
Ok(d) => Some(d),
Err(_) => None,
}
}
/// Set a cache object by its identifier and content
///
/// # Arguments:
/// * `id` - `String` of the object's id
/// * `content` - `String` of the object's content
pub async fn set<I>(&self, id: String, content: I) -> bool
where
I: ToRedisArgs,
{
let mut c = self.get_con().await;
let res: Result<String, redis::RedisError> = c.set(id, content);
match res {
Ok(_) => true,
Err(_) => false,
}
}
/// Update a cache object by its identifier and content
///
/// # Arguments:
/// * `id` - `String` of the object's id
/// * `content` - `String` of the object's content
pub async fn update<I>(&self, id: String, content: I) -> bool
where
I: ToRedisArgs,
{
self.set(id, content).await
}
/// Remove a cache object by its identifier
///
/// # Arguments:
/// * `id` - `String` of the object's id
pub async fn remove<I>(&self, id: I) -> bool
where
I: ToRedisArgs,
{
let mut c = self.get_con().await;
let res: Result<String, redis::RedisError> = c.del(id);
match res {
Ok(_) => true,
Err(_) => false,
}
}
/// Remove a cache object by its identifier('s start)
///
/// # Arguments:
/// * `id` - `String` of the object's id('s start)
pub async fn remove_starting_with<I>(&self, id: I) -> bool
where
I: ToRedisArgs,
{
let mut c = self.get_con().await;
// get keys
let mut cmd = redis::cmd("DEL");
let keys: Result<Vec<String>, redis::RedisError> = c.keys(id);
for key in keys.unwrap() {
cmd.arg(key);
}
// remove
let res: Result<String, redis::RedisError> = cmd.query(&mut c);
match res {
Ok(_) => true,
Err(_) => false,
}
}
/// Increment a cache object by its identifier
///
/// # Arguments:
/// * `id` - `String` of the object's id
pub async fn incr<I>(&self, id: I) -> bool
where
I: ToRedisArgs,
{
let mut c = self.get_con().await;
let res: Result<String, redis::RedisError> = c.incr(id, 1);
match res {
Ok(_) => true,
Err(_) => false,
}
}
/// Decrement a cache object by its identifier
///
/// # Arguments:
/// * `id` - `String` of the object's id
pub async fn decr<I>(&self, id: I) -> bool
where
I: ToRedisArgs,
{
let mut c = self.get_con().await;
let res: Result<String, redis::RedisError> = c.decr(id, 1);
match res {
Ok(_) => true,
Err(_) => false,
}
}
/// Get a cache object by its identifier
///
/// # Arguments:
/// * `id` - `String` of the object's id
pub async fn get_timed<T, I>(&self, id: I) -> Option<TimedObject<T>>
where
T: Serialize + DeserializeOwned,
I: ToRedisArgs,
{
let mut c = self.get_con().await;
let res: Result<String, redis::RedisError> = c.get(&id);
match res {
Ok(d) => match serde_json::from_str::<TimedObject<T>>(&d) {
Ok(d) => {
// check time
let now = rainbeam_shared::epoch_timestamp(2024);
if now - d.0 >= EXPIRE_AT {
// expired key, remove and return None
self.remove(id).await;
return None;
}
// return
Some(d)
}
Err(_) => None,
},
Err(_) => None,
}
}
/// Set a cache object by its identifier and content
///
/// # Arguments:
/// * `id` - `String` of the object's id
/// * `content` - `String` of the object's content
pub async fn set_timed<T, I>(&self, id: I, content: T) -> bool
where
T: Serialize + DeserializeOwned,
I: ToRedisArgs,
{
let mut c = self.get_con().await;
let res: Result<String, redis::RedisError> = c.set(
id,
match serde_json::to_string::<TimedObject<T>>(&(
rainbeam_shared::epoch_timestamp(2024),
content,
)) {
Ok(s) => s,
Err(_) => return false,
},
);
match res {
Ok(_) => true,
Err(_) => false,
}
}
}