2023-10-01 02:36:27 +01:00
|
|
|
use async_trait::async_trait;
|
|
|
|
use sqlx::FromRow;
|
2023-10-02 15:33:19 +01:00
|
|
|
use std::{
|
|
|
|
fmt,
|
|
|
|
time::{SystemTime, UNIX_EPOCH},
|
|
|
|
};
|
2023-10-01 02:36:27 +01:00
|
|
|
|
2023-10-07 17:15:15 +01:00
|
|
|
use std::collections::HashMap;
|
|
|
|
use tokio::sync::Mutex;
|
2023-10-01 02:36:27 +01:00
|
|
|
|
|
|
|
#[derive(Clone, Debug, FromRow)]
|
|
|
|
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.
|
|
|
|
fn should_use(item: &CachedItem) -> bool {
|
|
|
|
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 != ""
|
2023-10-01 02:36:27 +01:00
|
|
|
}
|
|
|
|
|
2023-10-07 17:15:15 +01:00
|
|
|
lazy_static! {
|
|
|
|
static ref CACHE: Mutex<HashMap<String, CachedItem>> = Mutex::new(HashMap::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> {
|
|
|
|
let data = CACHE.lock().await;
|
|
|
|
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-07 17:15:15 +01:00
|
|
|
async fn rm(key: String) {
|
|
|
|
let mut data = CACHE.lock().await;
|
|
|
|
data.remove(&key);
|
|
|
|
}
|
2023-10-01 02:36:27 +01:00
|
|
|
|
2023-10-07 17:15:15 +01:00
|
|
|
pub async fn set(key: String, item: CachedItem) {
|
|
|
|
let mut data = CACHE.lock().await;
|
|
|
|
data.insert(key, item);
|
2023-10-01 02:36:27 +01:00
|
|
|
}
|