gabrielsimmer.com/src/cache/mod.rs
Gabriel Simmer 8a65ef8cb4
Some checks failed
Fly Deploy / Deploy app (push) Failing after 3m6s
Implement basic gossip protocol
Disabled unless peers are provided, communicates with other
instances (up to 3, and then a random selection of a third of the
available hosts). Still to do:

 - [ ] DNS based peer discovery
 - [ ] Probing of instances / healthchecks
 - [ ] Test propogation of membership changes/additions
2023-10-07 17:15:15 +01:00

59 lines
1.3 KiB
Rust

use async_trait::async_trait;
use sqlx::FromRow;
use std::{
fmt,
time::{SystemTime, UNIX_EPOCH},
};
use std::collections::HashMap;
use tokio::sync::Mutex;
#[derive(Clone, Debug, FromRow)]
pub struct CachedItem {
pub content_type: String,
pub content: String,
pub cached: i64,
}
/// 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 != ""
}
lazy_static! {
static ref CACHE: Mutex<HashMap<String, CachedItem>> = Mutex::new(HashMap::new());
}
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
}
}
None => None,
}
}
async fn rm(key: String) {
let mut data = CACHE.lock().await;
data.remove(&key);
}
pub async fn set(key: String, item: CachedItem) {
let mut data = CACHE.lock().await;
data.insert(key, item);
}