1use crate::redis::Redis;
2use json::{object, JsonValue};
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5use std::fs;
6use std::path::PathBuf;
7use std::sync::RwLock;
8use once_cell::sync::Lazy;
9
10mod redis;
11
12static GLOBAL_CONFIG: Lazy<RwLock<Config>> = Lazy::new(|| {
13 RwLock::new(Config::default())
14});
15
16#[derive(Clone)]
17pub enum Cache {
18 Redis(Redis),
19 None,
20}
21
22impl Cache {
23 pub fn new(config: Config) -> Self {
25 {
26 let mut data = GLOBAL_CONFIG.write().unwrap();
27 data.clone_from(&config);
28 }
29 let config = GLOBAL_CONFIG.read().unwrap();
30 let connection = config.connections.get(config.default.as_str()).unwrap().clone();
31 match connection.mode {
32 CacheMode::Redis => {
33 match Redis::connect(connection) {
34 Ok(e) => Cache::Redis(e),
35 Err(_) => Cache::None
36 }
37 }
38 CacheMode::None => Cache::None
39 }
40 }
41
42 pub fn create(name: &str, connection: Connection) -> Self {
44 {
45 let mut data = GLOBAL_CONFIG.write().unwrap();
46 if !data.connections.contains_key(name) {
47 data.connections.insert(name.to_string(), connection);
48 }
49 data.default = name.to_string();
50 }
51 let config = GLOBAL_CONFIG.read().unwrap();
52 let connection = config.connections.get(config.default.as_str()).unwrap().clone();
53 match connection.mode {
54 CacheMode::Redis => {
55 match Redis::connect(connection) {
56 Ok(e) => Cache::Redis(e),
57 Err(_) => Cache::None
58 }
59 }
60 CacheMode::None => Cache::None
61 }
62 }
63 pub fn connections(&mut self) -> JsonValue {
65 let mut connections = vec![];
66 let data = GLOBAL_CONFIG.read().unwrap();
67 for (item, mut value) in data.connections.clone() {
68 if value.mode.str().is_empty() {
69 continue;
70 }
71 let mut t = value.json();
72 t["name"] = item.into();
73 connections.push(t);
74 }
75 connections.into()
76 }
77 pub fn connection(&mut self, name: &str) -> Self {
79 let mut data = GLOBAL_CONFIG.write().unwrap();
80 if data.connections.contains_key(name) {
81 if name == data.default {
82 return self.clone();
83 }
84 data.default = name.to_string();
85 let connection = data.connections.get(data.default.as_str()).unwrap().clone();
86 match connection.mode {
87 CacheMode::Redis => {
88 match Redis::connect(connection) {
89 Ok(e) => Cache::Redis(e),
90 Err(_) => Cache::None
91 }
92 }
93 CacheMode::None => Cache::None
94 }
95 } else {
96 Cache::None
97 }
98 }
99 pub fn db(&mut self, db: i8) -> &mut Self{
100 match self {
101 Cache::Redis(e) => {
102 e.db(db);
103 },
104 Cache::None => {}
105 }
106 self
107 }
108
109 pub fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String> {
110 let res = match self {
111 Cache::Redis(e) => e.add(key, value, expiration_date)?,
112 Cache::None => return Err("error".to_string()),
113 };
114 Ok(res)
115 }
116 pub fn get(&mut self, key: &str) -> Result<JsonValue, String> {
117 let res = match self {
118 Cache::Redis(e) => e.get(key)?,
119 Cache::None => return Err("error".to_string()),
120 };
121 Ok(res)
122 }
123 pub fn delete(&mut self, key: &str) -> Result<bool, String> {
124 let res = match self {
125 Cache::Redis(e) => e.delete(key)?,
126 Cache::None => return Err("error".to_string()),
127 };
128 Ok(res)
129 }
130
131 pub fn exists(&mut self, key: &str) -> Result<bool, String> {
132 let res = match self {
133 Cache::Redis(e) => e.exists(key)?,
134 Cache::None => return Err("error".to_string()),
135 };
136 Ok(res)
137 }
138
139 pub fn keys(&mut self, key: &str) -> Result<JsonValue, String> {
140 let res = match self {
141 Cache::Redis(e) => e.keys(key)?,
142 Cache::None => return Err("error".to_string()),
143 };
144 Ok(res)
145 }
146
147 pub fn set_add(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
148 let res = match self {
149 Cache::Redis(e) => e.set_add(key, value)?,
150 Cache::None => return Err("error".to_string()),
151 };
152 Ok(res)
153 }
154 pub fn set_get(&mut self, key: &str) -> Result<JsonValue, String> {
155 let res = match self {
156 Cache::Redis(e) => e.set_get(key)?,
157 Cache::None => return Err("error".to_string()),
158 };
159 Ok(res)
160 }
161
162 pub fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
163 let res = match self {
164 Cache::Redis(e) => e.set_delete(key, value)?,
165 Cache::None => return Err("error".to_string()),
166 };
167 Ok(res)
168 }
169
170 pub fn set_message_queue(&mut self, key: &str, value: JsonValue) -> Result<bool, String> {
171 match self {
172 Cache::Redis(e) => e.set_message_queue(key, value),
173 Cache::None => Err("error".to_string()),
174 }
175 }
176 pub fn get_message_queue(&mut self, key: &str) -> Result<JsonValue, String> {
177 match self {
178 Cache::Redis(e) => Ok(e.get_message_queue(key)?),
179 Cache::None => Err("error".to_string()),
180 }
181 }
182 pub fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
183 let res = match self {
184 Cache::Redis(e) => e.set_object(key, field, value)?,
185 Cache::None => return Err("error".to_string()),
186 };
187 Ok(res)
188 }
189 pub fn get_object(&mut self, key: &str) -> Result<JsonValue, String> {
191 let res = match self {
192 Cache::Redis(e) => e.get_object(key)?,
193 Cache::None => return Err("error".to_string()),
194 };
195 Ok(res)
196 }
197 pub fn add_hash(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String> {
199 let res = match self {
200 Cache::Redis(e) => e.add_hash(key, field, value)?,
201 Cache::None => return Err("error".to_string()),
202 };
203 Ok(res)
204 }
205 pub fn get_hash_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String> {
207 let res = match self {
208 Cache::Redis(e) => e.get_hash_field_value(key, field)?,
209 Cache::None => return Err("error".to_string()),
210 };
211 Ok(res)
212 }
213 pub fn get_hash_fields(&mut self, key: &str) -> Result<JsonValue, String> {
215 let res = match self {
216 Cache::Redis(e) => e.get_hash_fields(key)?,
217 Cache::None => return Err("error".to_string()),
218 };
219 Ok(res)
220 }
221 pub fn delete_hash(&mut self, key: &str, field: &str) -> Result<bool, String> {
223 let res = match self {
224 Cache::Redis(e) => e.delete_hash(key, field)?,
225 Cache::None => return Err("error".to_string()),
226 };
227 Ok(res)
228 }
229 pub fn get_hash_values(&mut self, key: &str) -> Result<JsonValue, String> {
231 let res = match self {
232 Cache::Redis(e) => e.get_hash_values(key)?,
233 Cache::None => return Err("error".to_string()),
234 };
235 Ok(res)
236 }
237}
238
239
240pub trait CacheBase {
241 fn db(&mut self, db: i8) -> &mut Self;
243 fn add(&mut self, key: &str, value: JsonValue, expiration_date: u64) -> Result<bool, String>;
247 fn get(&mut self, key: &str) -> Result<JsonValue, String>;
249 fn delete(&mut self, key: &str) -> Result<bool, String>;
251 fn exists(&mut self, key: &str) -> Result<bool, String>;
254 fn keys(&mut self, key: &str) -> Result<JsonValue, String>;
257
258 fn set_add(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
260 fn set_get(&mut self, key: &str) -> Result<JsonValue, String>;
262 fn set_delete(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
264 fn set_message_queue(&mut self, key: &str, value: JsonValue) -> Result<bool, String>;
266 fn get_message_queue(&mut self, key: &str) -> Result<JsonValue, String>;
268 fn set_object(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String>;
269 fn get_object(&mut self, key: &str) -> Result<JsonValue, String>;
271 fn add_hash(&mut self, key: &str, field: &str, value: JsonValue) -> Result<bool, String>;
273 fn get_hash_field_value(&mut self, key: &str, field: &str) -> Result<JsonValue, String>;
275 fn get_hash_fields(&mut self, key: &str) -> Result<JsonValue, String>;
277 fn delete_hash(&mut self, key: &str, field: &str) -> Result<bool, String>;
279 fn get_hash_values(&mut self, key: &str) -> Result<JsonValue, String>;
281}
282
283#[derive(Clone, Debug, Deserialize, Serialize)]
284pub struct Config {
285 pub default: String,
286 pub connections: BTreeMap<String, Connection>,
287}
288
289impl Default for Config {
290 fn default() -> Self {
291 Self::new()
292 }
293}
294
295impl Config {
296 pub fn create(config_file: PathBuf, pkg_name: bool) -> Config {
300 #[derive(Clone, Debug, Deserialize, Serialize)]
301 pub struct ConfigNew {
302 pub br_cache: Config,
303 }
304 impl ConfigNew {
305 pub fn new() -> ConfigNew {
306 let mut connections = BTreeMap::new();
307 connections.insert("my_name".to_string(), Connection::default());
308 Self {
309 br_cache: Config {
310 default: "my_name".to_string(),
311 connections,
312 },
313 }
314 }
315 }
316 match fs::read_to_string(config_file.clone()) {
317 Ok(e) => {
318 if pkg_name {
319 let data = ConfigNew::new();
320 toml::from_str::<ConfigNew>(&e).unwrap_or_else(|_| {
321 let toml = toml::to_string(&data).unwrap();
322 let toml = format!("{e}\r\n{toml}");
323 let _ = fs::write(config_file.to_str().unwrap(), toml);
324 data
325 }).br_cache
326 } else {
327 Config::new()
328 }
329 }
330 Err(_) => {
331 if pkg_name {
332 let data = ConfigNew::new();
333 fs::create_dir_all(config_file.parent().unwrap()).unwrap();
334 let toml = toml::to_string(&data).unwrap();
335 let _ = fs::write(config_file.to_str().unwrap(), toml);
336 data.br_cache
337 } else {
338 let data = Config::new();
339 fs::create_dir_all(config_file.parent().unwrap()).unwrap();
340 let toml = toml::to_string(&data).unwrap();
341 let _ = fs::write(config_file.to_str().unwrap(), toml);
342 data
343 }
344 }
345 }
346 }
347 pub fn new() -> Config {
348 let mut connections = BTreeMap::new();
349 connections.insert("my_name".to_string(), Connection::default());
350 Self {
351 default: "my_name".to_string(),
352 connections,
353 }
354 }
355}
356
357#[derive(Clone, Debug, Serialize, Deserialize)]
358pub struct Connection {
359 pub mode: CacheMode,
360 pub hostname: String,
361 pub hostport: String,
362 pub userpass: String,
363}
364impl Default for Connection {
365 fn default() -> Self {
366 Self {
367 mode: CacheMode::Redis,
368 hostname: "127.0.0.1".to_string(),
369 hostport: "6379".to_string(),
370 userpass: "".to_string(),
371 }
372 }
373}
374impl Connection {
375 pub fn from(data: JsonValue) -> Connection {
376 Self {
377 mode: CacheMode::from(data["mode"].as_str().unwrap_or("")),
378 hostname: data["hostname"].to_string(),
379 hostport: data["hostport"].to_string(),
380 userpass: data["userpass"].to_string(),
381 }
382 }
383 pub fn json(&mut self) -> JsonValue {
384 let mut data = object! {};
385 data["mode"] = self.mode.str().into();
386 data["hostname"] = self.hostname.clone().into();
387 data["hostport"] = self.hostport.clone().into();
388 data["userpass"] = self.userpass.clone().into();
389 data
390 }
391}
392
393#[derive(Clone, Debug, Serialize, Deserialize)]
394pub enum CacheMode {
395 Redis,
396 None,
397}
398
399impl CacheMode {
400 pub fn str(&mut self) -> &'static str {
401 match self {
402 CacheMode::Redis => "redis",
403 CacheMode::None => ""
404 }
405 }
406 pub fn from(name: &str) -> Self {
407 match name {
408 "redis" => CacheMode::Redis,
409 _ => CacheMode::Redis,
410 }
411 }
412}