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
use core::fmt::{Debug, Formatter};
use deadpool_redis::{redis, Pool, Runtime};
use snafu::prelude::Snafu;
#[derive(Clone)]
pub struct RedisPool {
pool: Pool,
key_folder: String,
}
impl Debug for RedisPool {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RedisPool")
.field("key_folder", &self.key_folder)
.finish()
}
}
#[derive(Debug, Clone, Copy, Snafu)]
pub enum CacheError {
#[snafu(display("Could not build configuration for cache."))]
CouldNotConfigure,
#[snafu(display("Could not connect to redis pool."))]
CouldNotConnect,
#[snafu(display("The operation on the redis cache failed."))]
OperationFailed,
}
impl RedisPool {
pub async fn new(config: crate::config::Config, key_folder: &str) -> Result<Self, ()> {
let cfg: deadpool_redis::Config = config.redis;
let Some(details) = cfg.url.clone() else {
cache_error!("(RedisPool new) no connection address found.");
return Err(());
};
cache_info!(
"(RedisPool new) creating pool with key folder '{}' at {:?}...",
key_folder,
details
);
match cfg.create_pool(Some(Runtime::Tokio1)) {
Ok(pool) => {
cache_info!("(RedisPool new) pool created.");
Ok(RedisPool {
pool,
key_folder: String::from(key_folder),
})
}
Err(e) => {
cache_error!("(RedisPool new) could not create pool: {}", e);
Err(())
}
}
}
pub async fn increment(&mut self, key: &str, expiration_ms: u32) -> Result<u32, CacheError> {
let key = format!("{}:{}", &self.key_folder, key);
cache_info!("(increment) entry with key {}.", &key);
let mut connection = match self.pool.get().await {
Ok(connection) => connection,
Err(e) => {
cache_error!("(increment) could not connect to redis deadpool: {e}");
return Err(CacheError::CouldNotConnect);
}
};
let mut result = match redis::pipe()
.atomic()
.cmd("INCR")
.arg(&[&key])
.cmd("PEXPIRE")
.arg(key)
.arg(expiration_ms)
.ignore()
.query_async::<_, _>(&mut connection)
.await
{
Ok(redis::Value::Bulk(val)) => val,
Ok(value) => {
cache_error!(
"(increment) Operation failed, unexpected redis response: {:?}",
value
);
return Err(CacheError::OperationFailed);
}
Err(e) => {
cache_error!("(increment) Operation failed, redis error: {}", e);
return Err(CacheError::OperationFailed);
}
};
let new_value = match result.pop() {
Some(redis::Value::Int(new_value)) => new_value,
Some(value) => {
cache_error!(
"(increment) Operation failed, unexpected redis response: {:?}",
value
);
return Err(CacheError::OperationFailed);
}
None => {
cache_error!("(increment) Operation failed, empty redis response array.");
return Err(CacheError::OperationFailed);
}
};
if new_value < 1 {
cache_error!(
"(increment) operation failed, unexpected value: {:?}",
new_value
);
return Err(CacheError::OperationFailed);
}
Ok(new_value as u32)
}
pub async fn multiple_set(
&mut self,
keyvals: Vec<(String, String)>,
expiration_ms: u32,
) -> Result<(), CacheError> {
let mut connection = match self.pool.get().await {
Ok(connection) => connection,
Err(e) => {
cache_error!("(get) could not connect to redis deadpool: {e}");
return Err(CacheError::CouldNotConnect);
}
};
let mut pipe = redis::pipe();
let mut pipe_ref = pipe.atomic();
for (key, value) in keyvals {
pipe_ref = pipe_ref
.pset_ex(key, value, expiration_ms as usize)
.ignore();
}
match pipe.query_async(&mut connection).await {
Ok(redis::Value::Okay) => Ok(()),
Ok(value) => {
cache_error!(
"(multiple_set) Operation failed, unexpected redis response: {:?}",
value
);
Err(CacheError::OperationFailed)
}
Err(e) => {
cache_error!("(multiple_set) Operation failed, redis error: {}", e);
Err(CacheError::OperationFailed)
}
}
}
pub async fn multiple_get<T: std::str::FromStr>(
&mut self,
keys: Vec<String>,
) -> Result<Vec<T>, CacheError> {
let mut connection = match self.pool.get().await {
Ok(connection) => connection,
Err(e) => {
cache_error!("(get) could not connect to redis deadpool: {e}");
return Err(CacheError::CouldNotConnect);
}
};
let result = redis::pipe()
.atomic()
.mget(keys.join(" "))
.query_async(&mut connection)
.await;
match result {
Ok(redis::Value::Bulk(values)) => {
let values = values
.iter()
.filter_map(|value| match value {
redis::Value::Data(data) => {
T::from_str(&String::from_utf8(data.to_vec()).unwrap()).ok()
}
_ => None,
})
.collect::<Vec<T>>();
if values.len() != keys.len() {
cache_error!(
"(multiple_get) Operation failed, expected {} values, got {}.",
keys.len(),
values.len()
);
return Err(CacheError::OperationFailed);
}
Ok(values)
}
Ok(value) => {
cache_error!(
"(multiple_set) Operation failed, unexpected redis response: {:?}",
value
);
Err(CacheError::OperationFailed)
}
Err(e) => {
cache_error!("(multiple_set) Operation failed, redis error: {}", e);
Err(CacheError::OperationFailed)
}
}
}
}