use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde::{Deserialize, Serialize};
use super::AccountItems;
pub const ACCOUNT_CACHE_FILE: &str = "radar-account.json";
pub const ACCOUNT_TTL_SECS: u64 = 300;
pub const ACCOUNT_TTL: Duration = Duration::from_secs(ACCOUNT_TTL_SECS);
pub fn cache_path(config_dir: &Path) -> PathBuf {
config_dir.join(ACCOUNT_CACHE_FILE)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CachedAccount {
pub fetched_at: u64,
pub query_hash: String,
pub items: AccountItems,
}
impl CachedAccount {
pub fn is_fresh(&self, now: u64) -> bool {
now.saturating_sub(self.fetched_at) < ACCOUNT_TTL_SECS
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AccountCache {
pub entries: BTreeMap<String, CachedAccount>,
}
impl AccountCache {
pub fn load(path: &Path) -> Self {
let Ok(raw) = std::fs::read_to_string(path) else {
return Self::default();
};
let Ok(map) = serde_json::from_str::<BTreeMap<String, serde_json::Value>>(&raw) else {
return Self::default();
};
let entries = map
.into_iter()
.filter_map(|(id, value)| Some((id, serde_json::from_value(value).ok()?)))
.collect();
Self { entries }
}
pub fn get(&self, id: &str, query_hash: &str) -> Option<&CachedAccount> {
self.entries.get(id).filter(|e| e.query_hash == query_hash)
}
pub fn fresh(&self, id: &str, query_hash: &str, now: u64) -> Option<&CachedAccount> {
self.get(id, query_hash).filter(|e| e.is_fresh(now))
}
pub fn store(path: &Path, id: &str, entry: CachedAccount) -> std::io::Result<()> {
let mut cache = Self::load(path);
cache.entries.insert(id.to_string(), entry);
cache.save(path)
}
pub fn save(&self, path: &Path) -> std::io::Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let text = serde_json::to_string(&self.entries).map_err(std::io::Error::other)?;
let tmp = path.with_extension(format!("json.{}.tmp", std::process::id()));
std::fs::write(&tmp, text)?;
std::fs::rename(&tmp, path).inspect_err(|_| {
let _ = std::fs::remove_file(&tmp);
})
}
}