Skip to main content

gitpoulpi_hosting/account/
cache.rs

1//! `<config>/radar-account.json`: the last account-wide answer per
2//! integration, so the Radar opens on yesterday's rows while a fresh round
3//! runs and `hosting radar` does not hammer a host's search API.
4//!
5//! Read leniently like the workspace search's cache: a missing, corrupt,
6//! half-written or foreign-version file is an empty cache, and one bad entry
7//! drops only itself. Writes go through a temp file and a rename, merged into
8//! what is on disk, so the TUI and the CLI saving at once lose at most one
9//! entry, never the file.
10
11use std::collections::BTreeMap;
12use std::path::{Path, PathBuf};
13use std::time::Duration;
14
15use serde::{Deserialize, Serialize};
16
17use super::AccountItems;
18
19/// The file name under the config directory.
20pub const ACCOUNT_CACHE_FILE: &str = "radar-account.json";
21
22/// An entry newer than this is reused without asking the host.
23pub const ACCOUNT_TTL_SECS: u64 = 300;
24/// [`ACCOUNT_TTL_SECS`] as a duration.
25pub const ACCOUNT_TTL: Duration = Duration::from_secs(ACCOUNT_TTL_SECS);
26
27/// The cache file inside `config_dir`.
28pub fn cache_path(config_dir: &Path) -> PathBuf {
29    config_dir.join(ACCOUNT_CACHE_FILE)
30}
31
32/// One integration's last answer.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct CachedAccount {
35    /// Unix seconds.
36    pub fetched_at: u64,
37    /// [`super::AccountQuery::fingerprint`] of the question it answers.
38    pub query_hash: String,
39    pub items: AccountItems,
40}
41
42impl CachedAccount {
43    /// Younger than [`ACCOUNT_TTL`] at `now` (unix seconds).
44    pub fn is_fresh(&self, now: u64) -> bool {
45        now.saturating_sub(self.fetched_at) < ACCOUNT_TTL_SECS
46    }
47}
48
49/// Integration id -> its last answer.
50#[derive(Debug, Clone, Default, PartialEq, Eq)]
51pub struct AccountCache {
52    pub entries: BTreeMap<String, CachedAccount>,
53}
54
55impl AccountCache {
56    /// The cache at `path`; anything unreadable is empty.
57    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    /// The entry of `id` when it answers the same question, whatever its age
72    /// (a caller shows it while it refreshes).
73    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    /// [`Self::get`] restricted to entries younger than [`ACCOUNT_TTL`].
78    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    /// Stores `entry` for `id` into the file at `path`, keeping the other
83    /// integrations' entries as they are on disk right now.
84    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    /// Writes the whole cache (temp file, then rename).
91    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}