2023-10-07 17:15:15 +01:00
|
|
|
use std::collections::HashMap;
|
2023-10-23 20:11:46 +01:00
|
|
|
use std::sync::{Mutex, OnceLock};
|
2023-10-01 02:36:27 +01:00
|
|
|
|
2023-10-23 21:26:19 +01:00
|
|
|
#[derive(Clone, Debug)]
|
2023-10-01 02:36:27 +01:00
|
|
|
pub struct CachedItem {
|
|
|
|
pub content_type: String,
|
|
|
|
pub content: String,
|
2023-10-07 17:15:15 +01:00
|
|
|
pub cached: i64,
|
2023-10-01 02:36:27 +01:00
|
|
|
}
|
|
|
|
|
2023-10-07 17:15:15 +01:00
|
|
|
/// Determine whether we should actually use the cached item or not.
|
2023-10-23 20:11:16 +01:00
|
|
|
fn should_use(_item: &CachedItem) -> bool {
|
2023-10-07 18:01:15 +01:00
|
|
|
// let current_time: i64 = SystemTime::now()
|
|
|
|
// .duration_since(UNIX_EPOCH)
|
|
|
|
// .expect("SystemTime before UNIX EPOCH!")
|
|
|
|
// .as_secs()
|
|
|
|
// .try_into()
|
|
|
|
// .unwrap();
|
|
|
|
|
|
|
|
// current_time <= (item.cached + (2*60)) && item.content != ""
|
|
|
|
true
|
2023-10-01 02:36:27 +01:00
|
|
|
}
|
|
|
|
|
2023-10-23 20:11:16 +01:00
|
|
|
static CACHE: OnceLock<Mutex<HashMap<String, CachedItem>>> = OnceLock::new();
|
2023-10-01 02:36:27 +01:00
|
|
|
|
2023-10-07 17:15:15 +01:00
|
|
|
pub async fn get(key: &String) -> Option<CachedItem> {
|
2023-10-23 20:11:46 +01:00
|
|
|
let data = CACHE
|
|
|
|
.get_or_init(|| Mutex::new(HashMap::new()))
|
|
|
|
.lock()
|
|
|
|
.unwrap();
|
2023-10-07 17:15:15 +01:00
|
|
|
dbg!(&key);
|
|
|
|
match data.get(key) {
|
|
|
|
Some(c) => {
|
|
|
|
if should_use(&c) {
|
|
|
|
Some(c.clone())
|
|
|
|
} else {
|
|
|
|
//let _rm = rm(key.to_string()).await;
|
|
|
|
None
|
2023-10-01 02:36:27 +01:00
|
|
|
}
|
|
|
|
}
|
2023-10-07 17:15:15 +01:00
|
|
|
None => None,
|
2023-10-02 15:33:19 +01:00
|
|
|
}
|
2023-10-01 02:36:27 +01:00
|
|
|
}
|
|
|
|
|
2023-10-23 20:11:16 +01:00
|
|
|
// async fn rm(key: String) {
|
|
|
|
// let mut data = CACHE.get().unwrap().clone();
|
|
|
|
// data.remove(&key);
|
|
|
|
// let _ = CACHE.set(data);
|
|
|
|
// }
|
2023-10-01 02:36:27 +01:00
|
|
|
|
2023-10-07 17:15:15 +01:00
|
|
|
pub async fn set(key: String, item: CachedItem) {
|
2023-10-23 20:11:46 +01:00
|
|
|
let mut data = CACHE
|
|
|
|
.get_or_init(|| Mutex::new(HashMap::new()))
|
|
|
|
.lock()
|
|
|
|
.unwrap();
|
2023-10-07 17:15:15 +01:00
|
|
|
data.insert(key, item);
|
2023-10-01 02:36:27 +01:00
|
|
|
}
|