use std::{path::PathBuf, time::Duration};
use serde::{Deserialize, Serialize};
use tokio::fs;
use crate::errors::ZenmanageError;
use super::{CacheBackend, CacheFuture};
#[derive(Clone, Debug)]
pub struct FileSystemCache {
directory: PathBuf,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
struct CacheFile {
value: String,
expires_at_unix: u64,
}
impl FileSystemCache {
pub fn new(directory: impl Into<PathBuf>) -> Self {
Self {
directory: directory.into(),
}
}
fn file_path(&self, key: &str) -> PathBuf {
let safe_key: String = key
.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
ch
} else {
'_'
}
})
.collect();
self.directory.join(format!("{safe_key}.json"))
}
fn unix_now() -> u64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
}
impl CacheBackend for FileSystemCache {
fn get<'a>(&'a self, key: &'a str) -> CacheFuture<'a, Option<String>> {
Box::pin(async move {
let file_path = self.file_path(key);
let contents = match fs::read_to_string(&file_path).await {
Ok(contents) => contents,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error.into()),
};
let parsed: CacheFile = serde_json::from_str(&contents)?;
if Self::unix_now() >= parsed.expires_at_unix {
let _ = fs::remove_file(&file_path).await;
return Ok(None);
}
Ok(Some(parsed.value))
})
}
fn set<'a>(&'a self, key: &'a str, value: String, ttl: Duration) -> CacheFuture<'a, ()> {
Box::pin(async move {
fs::create_dir_all(&self.directory).await?;
let file_path = self.file_path(key);
let payload = CacheFile {
value,
expires_at_unix: Self::unix_now().saturating_add(ttl.as_secs()),
};
let encoded = serde_json::to_string(&payload).map_err(|error| {
ZenmanageError::Cache(format!("failed to serialize cache payload: {error}"))
})?;
fs::write(file_path, encoded).await?;
Ok(())
})
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
#[tokio::test]
async fn writes_and_reads_cache_file() {
let dir = std::env::temp_dir().join("zenmanage-rust-cache-test");
let _ = fs::remove_dir_all(&dir).await;
let cache = FileSystemCache::new(&dir);
cache
.set("rules", "payload".to_owned(), Duration::from_secs(30))
.await
.expect("set cache");
let value = cache.get("rules").await.expect("get cache");
assert_eq!(value, Some("payload".to_owned()));
let _ = fs::remove_dir_all(&dir).await;
}
}