Skip to main content

sovereign_update/
cache.rs

1//! `~/.cache/<bin>/update-check.json`: what the last check found, and when.
2
3use crate::decide::{Candidate, Source};
4use crate::policy::Installs;
5use crate::Product;
6use std::path::{Path, PathBuf};
7
8pub const SCHEMA: &str = "sovereign-update-check/v1";
9/// Re-check at most once per this many seconds.
10pub const TTL_SECS: u64 = 24 * 60 * 60;
11
12#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
13pub struct Cache {
14    pub schema: String,
15    /// Unix seconds of the last attempt, successful or not.
16    pub checked_at: u64,
17    /// The binary the result is about. A different binary ignores it.
18    pub current_version: String,
19    pub current_sha: Option<String>,
20    pub available: Option<Candidate>,
21    /// Last failure, kept for `update --check`; never printed at startup.
22    pub error: Option<String>,
23}
24
25/// `$XDG_CACHE_HOME/<bin>/update-check.json`, else `$HOME/.cache/...`.
26#[must_use]
27pub fn path(env: &dyn Fn(&str) -> Option<String>, bin: &str) -> Option<PathBuf> {
28    let base = env("XDG_CACHE_HOME")
29        .filter(|v| !v.is_empty())
30        .map(PathBuf::from)
31        .or_else(|| {
32            env("HOME")
33                .filter(|v| !v.is_empty())
34                .map(|h| Path::new(&h).join(".cache"))
35        })?;
36    Some(base.join(bin).join("update-check.json"))
37}
38
39#[must_use]
40pub fn load(path: &Path) -> Option<Cache> {
41    let c: Cache = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
42    (c.schema == SCHEMA).then_some(c)
43}
44
45/// Write via a temp file and rename, so a reader never sees half a file.
46pub fn store(path: &Path, c: &Cache) -> std::io::Result<()> {
47    let dir = path.parent().unwrap_or_else(|| Path::new("."));
48    std::fs::create_dir_all(dir)?;
49    let tmp = dir.join(format!(".update-check.{}.tmp", std::process::id()));
50    std::fs::write(
51        &tmp,
52        serde_json::to_vec_pretty(c).map_err(std::io::Error::other)?,
53    )?;
54    std::fs::rename(&tmp, path)
55}
56
57fn same_binary(p: &Product, c: &Cache) -> bool {
58    c.current_version == p.version && c.current_sha.as_deref() == p.build_sha
59}
60
61/// True when there is no usable cache, it is older than the TTL, it is about
62/// another binary, or its timestamp is in the future (clock moved back).
63#[must_use]
64pub fn needs_refresh(p: &Product, c: Option<&Cache>, now: u64) -> bool {
65    c.is_none_or(|c| !same_binary(p, c) || c.checked_at > now || now - c.checked_at >= TTL_SECS)
66}
67
68/// The record the startup check writes before spawning its refresh: stamped
69/// now, so no other run starts one, and keeping this binary's known update.
70#[must_use]
71pub fn claim(p: &Product, old: Option<&Cache>, now: u64) -> Cache {
72    Cache {
73        schema: SCHEMA.into(),
74        checked_at: now,
75        current_version: p.version.into(),
76        current_sha: p.build_sha.map(Into::into),
77        available: old
78            .filter(|c| same_binary(p, c))
79            .and_then(|c| c.available.clone()),
80        error: Some("refresh in progress".into()),
81    }
82}
83
84/// The one stderr line, when the cache says a newer build exists for THIS binary.
85#[must_use]
86pub fn notice(p: &Product, c: &Cache, installs: &Installs) -> Option<String> {
87    let a = c.available.as_ref().filter(|_| same_binary(p, c))?;
88    let src = match a.source {
89        Source::Release => "release",
90        Source::Nightly => "nightly",
91    };
92    let bin = p.bin;
93    let tail = match installs {
94        Installs::User => format!("run `{bin} update`"),
95        Installs::Arbiter(_) => "fleet host: the arbiter installs it".to_string(),
96    };
97    Some(format!(
98        "{bin} {} -> {} available ({src}) — {tail}",
99        p.version, a.version
100    ))
101}
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    const P: Product = Product {
108        bin: "apr",
109        repo: "paiml/aprender",
110        version: "0.69.0",
111        build_sha: Some("abc"),
112        release_asset: None,
113        nightly: true,
114    };
115
116    fn cache(at: u64, ver: &str, avail: bool) -> Cache {
117        Cache {
118            schema: SCHEMA.into(),
119            checked_at: at,
120            current_version: ver.into(),
121            current_sha: Some("abc".into()),
122            available: avail.then(|| Candidate {
123                source: Source::Release,
124                version: "0.69.1".into(),
125                git_ref: "v0.69.1".into(),
126                asset_url: String::new(),
127                sha256: None,
128                bin_sha256: None,
129            }),
130            error: None,
131        }
132    }
133
134    #[test]
135    fn refresh_rows() {
136        let now = 10 * TTL_SECS;
137        assert!(needs_refresh(&P, None, now), "no cache");
138        assert!(
139            !needs_refresh(&P, Some(&cache(now - 60, "0.69.0", false)), now),
140            "fresh"
141        );
142        assert!(
143            needs_refresh(&P, Some(&cache(now - TTL_SECS, "0.69.0", false)), now),
144            "exactly 24 h"
145        );
146        assert!(
147            needs_refresh(&P, Some(&cache(now + 60, "0.69.0", false)), now),
148            "future timestamp"
149        );
150        assert!(
151            needs_refresh(&P, Some(&cache(now, "0.68.0", false)), now),
152            "another binary's cache"
153        );
154    }
155
156    #[test]
157    fn claim_rows() {
158        let now = 10 * TTL_SECS;
159        let c = claim(&P, Some(&cache(0, "0.69.0", true)), now);
160        assert!(
161            !needs_refresh(&P, Some(&c), now),
162            "a claim blocks a second refresh"
163        );
164        assert!(
165            c.available.is_some(),
166            "a claim keeps this binary's known update"
167        );
168        assert!(
169            claim(&P, Some(&cache(0, "0.68.0", true)), now)
170                .available
171                .is_none(),
172            "a claim drops another binary's update"
173        );
174        assert!(claim(&P, None, now).available.is_none());
175    }
176
177    #[test]
178    fn notice_rows() {
179        let n = notice(&P, &cache(0, "0.69.0", true), &Installs::User).expect("newer cached");
180        assert_eq!(
181            n,
182            "apr 0.69.0 -> 0.69.1 available (release) — run `apr update`"
183        );
184        let f = notice(
185            &P,
186            &cache(0, "0.69.0", true),
187            &Installs::Arbiter("x".into()),
188        )
189        .expect("fleet");
190        assert!(f.ends_with("fleet host: the arbiter installs it"), "{f}");
191        assert!(
192            notice(&P, &cache(0, "0.69.0", false), &Installs::User).is_none(),
193            "up to date"
194        );
195        assert!(
196            notice(&P, &cache(0, "0.68.0", true), &Installs::User).is_none(),
197            "a stale binary's cache is ignored"
198        );
199    }
200
201    #[test]
202    fn store_load_roundtrip_and_paths() {
203        let d = tempfile::tempdir().expect("tempdir");
204        let p = d.path().join("apr").join("update-check.json");
205        let c = cache(5, "0.69.0", true);
206        store(&p, &c).expect("store");
207        assert_eq!(load(&p), Some(c));
208        std::fs::write(&p, b"{\"schema\":\"other\"}").expect("write");
209        assert_eq!(load(&p), None, "a foreign schema is no cache");
210        let env = |k: &str| (k == "HOME").then(|| "/h".to_string());
211        assert_eq!(
212            path(&env, "apr"),
213            Some(PathBuf::from("/h/.cache/apr/update-check.json"))
214        );
215        let xdg = |k: &str| (k == "XDG_CACHE_HOME").then(|| "/x".to_string());
216        assert_eq!(
217            path(&xdg, "pv"),
218            Some(PathBuf::from("/x/pv/update-check.json"))
219        );
220        assert_eq!(path(&|_: &str| None, "pv"), None);
221    }
222}