gitpoulpi_hosting/account/
cache.rs1use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13use std::time::Duration;
14
15use serde::{Deserialize, Serialize};
16
17use super::AccountItems;
18
19pub const ACCOUNT_CACHE_FILE: &str = "radar-account.json";
21
22pub const ACCOUNT_TTL_SECS: u64 = 300;
24pub const ACCOUNT_TTL: Duration = Duration::from_secs(ACCOUNT_TTL_SECS);
26
27pub fn cache_path(config_dir: &Path) -> PathBuf {
29 config_dir.join(ACCOUNT_CACHE_FILE)
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct CachedAccount {
35 pub fetched_at: u64,
37 pub query_hash: String,
39 pub items: AccountItems,
40}
41
42impl CachedAccount {
43 pub fn is_fresh(&self, now: u64) -> bool {
45 now.saturating_sub(self.fetched_at) < ACCOUNT_TTL_SECS
46 }
47}
48
49#[derive(Debug, Clone, Default, PartialEq, Eq)]
51pub struct AccountCache {
52 pub entries: BTreeMap<String, CachedAccount>,
53}
54
55impl AccountCache {
56 pub fn load(path: &Path) -> Self {
58 let Ok(raw) = std::fs::read_to_string(path) else {
59 return Self::default();
60 };
61 let Ok(map) = serde_json::from_str::<BTreeMap<String, serde_json::Value>>(&raw) else {
62 return Self::default();
63 };
64 let entries = map
65 .into_iter()
66 .filter_map(|(id, value)| Some((id, serde_json::from_value(value).ok()?)))
67 .collect();
68 Self { entries }
69 }
70
71 pub fn get(&self, id: &str, query_hash: &str) -> Option<&CachedAccount> {
74 self.entries.get(id).filter(|e| e.query_hash == query_hash)
75 }
76
77 pub fn fresh(&self, id: &str, query_hash: &str, now: u64) -> Option<&CachedAccount> {
79 self.get(id, query_hash).filter(|e| e.is_fresh(now))
80 }
81
82 pub fn store(path: &Path, id: &str, entry: CachedAccount) -> std::io::Result<()> {
85 let mut cache = Self::load(path);
86 cache.entries.insert(id.to_string(), entry);
87 cache.save(path)
88 }
89
90 pub fn save(&self, path: &Path) -> std::io::Result<()> {
92 if let Some(parent) = path.parent() {
93 std::fs::create_dir_all(parent)?;
94 }
95 let text = serde_json::to_string(&self.entries).map_err(std::io::Error::other)?;
96 let tmp = path.with_extension(format!("json.{}.tmp", std::process::id()));
97 std::fs::write(&tmp, text)?;
98 std::fs::rename(&tmp, path).inspect_err(|_| {
99 let _ = std::fs::remove_file(&tmp);
100 })
101 }
102}