use crate::dao::GarrisonDao;
use crate::error::{GarrisonError, GarrisonResult};
use async_trait::async_trait;
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::sync::Mutex;
pub struct MockDao {
store: Mutex<HashMap<String, (String, Option<Instant>)>>,
}
impl MockDao {
pub fn new() -> Self {
Self {
store: Mutex::new(HashMap::new()),
}
}
}
#[async_trait]
impl GarrisonDao for MockDao {
async fn get(&self, key: &str) -> GarrisonResult<Option<String>> {
let mut store = self.store.lock().await;
match store.get(key) {
Some((value, expire_at)) => {
if let Some(deadline) = expire_at {
if Instant::now() >= *deadline {
store.remove(key);
return Ok(None);
}
}
Ok(Some(value.clone()))
},
None => Ok(None),
}
}
async fn set(&self, key: &str, value: &str, ttl_seconds: u64) -> GarrisonResult<()> {
let expire_at = if ttl_seconds == 0 {
None
} else {
Some(Instant::now() + Duration::from_secs(ttl_seconds))
};
self.store
.lock()
.await
.insert(key.to_string(), (value.to_string(), expire_at));
Ok(())
}
async fn update(&self, key: &str, value: &str) -> GarrisonResult<()> {
let mut store = self.store.lock().await;
match store.get_mut(key) {
Some((existing, _)) => {
*existing = value.to_string();
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
}
}
async fn expire(&self, key: &str, seconds: u64) -> GarrisonResult<()> {
let mut store = self.store.lock().await;
match store.get_mut(key) {
Some((_, expire_at)) => {
*expire_at = if seconds == 0 {
None
} else {
Some(Instant::now() + Duration::from_secs(seconds))
};
Ok(())
},
None => Err(GarrisonError::Dao(format!("dao-key-not-found::{}", key))),
}
}
async fn delete(&self, key: &str) -> GarrisonResult<()> {
self.store.lock().await.remove(key);
Ok(())
}
async fn get_timeout(&self, key: &str) -> GarrisonResult<Option<Duration>> {
let store = self.store.lock().await;
match store.get(key) {
Some((_, Some(deadline))) => {
let now = Instant::now();
if *deadline <= now {
Ok(None)
} else {
Ok(Some(*deadline - now))
}
},
_ => Ok(None),
}
}
async fn get_with_ttl(&self, key: &str) -> GarrisonResult<Option<(String, Option<Duration>)>> {
let mut store = self.store.lock().await;
match store.get(key) {
Some((value, expire_at)) => {
if let Some(deadline) = expire_at {
if Instant::now() >= *deadline {
store.remove(key);
return Ok(None);
}
}
let ttl = if let Some(deadline) = expire_at {
let now = Instant::now();
if *deadline > now {
Some(*deadline - now)
} else {
None
}
} else {
None
};
Ok(Some((value.clone(), ttl)))
},
None => Ok(None),
}
}
}