Skip to main content

release_kit/self_depend/
check.rs

1//! The version check the `.envrc` line runs on every directory entry.
2//!
3//! It reads one cache file per checkout and reads the network only when a
4//! refresh is due: seven days after the last success, or one hour after a
5//! failed attempt. A due refresh takes an OS file lock beside the cache
6//! first; a check that finds the lock held reads the cache it has, because
7//! another process is refreshing. It writes no file but its cache and the
8//! lock beside it, and it never moves a pin.
9
10use std::fs;
11use std::path::{Path, PathBuf};
12use std::time::{Duration, SystemTime};
13
14use serde::{Deserialize, Serialize};
15
16use super::discover::{self, Discovery};
17
18/// How long a success stays fresh.
19pub const SUCCESS_INTERVAL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
20
21/// How long a failed attempt waits before the next one.
22pub const RETRY_INTERVAL: Duration = Duration::from_secs(60 * 60);
23
24/// One checkout's cached answer.
25#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Cache {
27    /// When the last attempt started, RFC 3339 UTC.
28    pub attempted: Option<String>,
29    /// When the last successful attempt finished, RFC 3339 UTC.
30    pub succeeded: Option<String>,
31    /// The latest release that success found.
32    pub latest: Option<String>,
33    /// Why the last attempt failed, where it failed.
34    pub error: Option<String>,
35}
36
37/// The cache and its lock for one checkout.
38#[derive(Debug, Clone)]
39pub struct Paths {
40    /// The cache file.
41    pub cache: PathBuf,
42    /// The lock file beside it.
43    pub lock: PathBuf,
44}
45
46impl Paths {
47    /// The paths for the checkout `key`, where a cache root resolves.
48    #[must_use]
49    pub fn for_key(key: &str) -> Option<Self> {
50        let dir = super::check_cache_dir()?;
51        Some(Self {
52            cache: dir.join(format!("{key}.json")),
53            lock: dir.join(format!("{key}.lock")),
54        })
55    }
56}
57
58/// What one check did.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Outcome {
61    /// The cache answered; no refresh was due.
62    Cached,
63    /// A refresh read the network and recorded its answer.
64    Refreshed,
65    /// A refresh was due, and another process held the lock.
66    Locked,
67    /// The cache cannot be written, so nothing was read.
68    Unwritable(String),
69}
70
71impl Outcome {
72    /// The outcome's word in the machine report.
73    #[must_use]
74    pub const fn word(&self) -> &'static str {
75        match self {
76            Self::Cached => "cached",
77            Self::Refreshed => "refreshed",
78            Self::Locked => "locked",
79            Self::Unwritable(_) => "unwritable",
80        }
81    }
82}
83
84/// A parsed time, or `None` for an absent or unreadable one.
85fn time(text: Option<&str>) -> Option<SystemTime> {
86    let at: jiff::Timestamp = text?.parse().ok()?;
87    SystemTime::try_from(at).ok()
88}
89
90/// RFC 3339 UTC to the second.
91#[must_use]
92pub fn stamp(at: SystemTime) -> String {
93    let at = jiff::Timestamp::try_from(at).unwrap_or(jiff::Timestamp::UNIX_EPOCH);
94    jiff::Timestamp::from_second(at.as_second())
95        .unwrap_or(jiff::Timestamp::UNIX_EPOCH)
96        .to_string()
97}
98
99/// How long ago `then` was, zero for a time in the future.
100fn age(now: SystemTime, then: SystemTime) -> Duration {
101    now.duration_since(then).unwrap_or_default()
102}
103
104/// Whether the cache asks for a network read at `now`.
105///
106/// After an attempt that failed, or that never finished, a read is due
107/// only one hour after that attempt, whatever an older success says. An
108/// attempt never finished where it is later than the last success, or
109/// where no success exists, and no error was recorded. Otherwise a read is
110/// due where the cache is missing, holds no success, or holds a success
111/// seven days old or more. Times compare as times, and an unreadable time
112/// counts as missing.
113#[must_use]
114pub fn due(cache: Option<&Cache>, now: SystemTime) -> bool {
115    let Some(cache) = cache else {
116        return true;
117    };
118    let attempted = time(cache.attempted.as_deref());
119    let succeeded = time(cache.succeeded.as_deref());
120    let unfinished = match (attempted, succeeded) {
121        (Some(attempted), Some(succeeded)) => attempted > succeeded,
122        (Some(_), None) => true,
123        (None, _) => false,
124    };
125    if cache.error.is_some() || unfinished {
126        return attempted.is_none_or(|attempted| age(now, attempted) >= RETRY_INTERVAL);
127    }
128    succeeded.is_none_or(|succeeded| age(now, succeeded) >= SUCCESS_INTERVAL)
129}
130
131/// When the next attempt after a failure may read the network.
132#[must_use]
133pub fn next_try(cache: &Cache) -> Option<String> {
134    time(cache.attempted.as_deref()).map(|attempted| stamp(attempted + RETRY_INTERVAL))
135}
136
137/// The cache at `path`, or `None` where it is absent or unreadable.
138#[must_use]
139pub fn read(path: &Path) -> Option<Cache> {
140    serde_json::from_slice(&fs::read(path).ok()?).ok()
141}
142
143/// Write the cache atomically.
144fn write(path: &Path, cache: &Cache) -> std::io::Result<()> {
145    let mut bytes = serde_json::to_vec_pretty(cache).map_err(std::io::Error::other)?;
146    bytes.push(b'\n');
147    crate::atomic::write(path, &bytes)
148}
149
150/// What one run of the check found.
151#[derive(Debug, Clone)]
152pub struct Run {
153    /// What the run did.
154    pub outcome: Outcome,
155    /// The cache the warnings read from.
156    pub cache: Option<Cache>,
157    /// Whether this run read the network, whatever it could record.
158    pub fetched: bool,
159}
160
161/// Run the check for one checkout: read the cache, and refresh it where a
162/// refresh is due and the lock is free.
163#[must_use]
164pub fn run(paths: &Paths, now: SystemTime) -> Run {
165    let (outcome, cache, fetched) = refresh(paths, now);
166    Run {
167        outcome,
168        cache,
169        fetched,
170    }
171}
172
173/// The refresh behind [`run`], as the outcome, the cache, and whether the
174/// network was read.
175fn refresh(paths: &Paths, now: SystemTime) -> (Outcome, Option<Cache>, bool) {
176    let cached = read(&paths.cache);
177    if !due(cached.as_ref(), now) {
178        return (Outcome::Cached, cached, false);
179    }
180    if let Some(parent) = paths.cache.parent()
181        && let Err(source) = fs::create_dir_all(parent)
182    {
183        return (Outcome::Unwritable(source.to_string()), cached, false);
184    }
185    let lock = match fs::OpenOptions::new()
186        .create(true)
187        .truncate(false)
188        .write(true)
189        .open(&paths.lock)
190    {
191        Ok(lock) => lock,
192        Err(source) => return (Outcome::Unwritable(source.to_string()), cached, false),
193    };
194    // An OS lock, released when the file closes, so a process that dies
195    // holding it frees it: no age, no owner file, and no takeover.
196    match lock.try_lock() {
197        Ok(()) => {}
198        Err(fs::TryLockError::WouldBlock) => return (Outcome::Locked, cached, false),
199        Err(fs::TryLockError::Error(source)) => {
200            return (Outcome::Unwritable(source.to_string()), cached, false);
201        }
202    }
203    // Another process may have refreshed between the read and the lock.
204    let cached = read(&paths.cache);
205    if !due(cached.as_ref(), now) {
206        return (Outcome::Cached, cached, false);
207    }
208    let mut cache = cached.unwrap_or_default();
209    cache.attempted = Some(stamp(now));
210    // The attempt is recorded before the read, so a read that hangs or
211    // dies still postpones the next one. A cache that cannot be written
212    // reads nothing.
213    if let Err(source) = write(&paths.cache, &cache) {
214        return (
215            Outcome::Unwritable(source.to_string()),
216            read(&paths.cache),
217            false,
218        );
219    }
220    match discover::latest_tag() {
221        Discovery::Tag(tag) => {
222            cache.succeeded = Some(stamp(SystemTime::now()));
223            cache.latest = Some(tag);
224            cache.error = None;
225        }
226        Discovery::Unreachable(reason) => cache.error = Some(reason),
227        Discovery::Unparsable(answer) => {
228            cache.error = Some(format!("the release page answered no tag: {answer}"));
229        }
230    }
231    if let Err(source) = write(&paths.cache, &cache) {
232        return (Outcome::Unwritable(source.to_string()), Some(cache), true);
233    }
234    drop(lock);
235    (Outcome::Refreshed, Some(cache), true)
236}
237
238/// The warnings one check prints, from the cache it read, for the pin
239/// `pin`.
240#[must_use]
241pub fn warnings(
242    pin: Option<&str>,
243    cache: Option<&Cache>,
244    outcome: &Outcome,
245    path: &Path,
246) -> Vec<String> {
247    let mut lines = Vec::new();
248    if let Outcome::Unwritable(reason) = outcome {
249        lines.push(format!(
250            "rk cannot record its version check at {}: {reason}.",
251            path.display()
252        ));
253    }
254    let Some(cache) = cache else {
255        return lines;
256    };
257    if let (Some(pin), Some(latest)) = (pin, cache.latest.as_deref())
258        && discover::version_order(latest, pin).is_gt()
259    {
260        lines.push(super::advice::pending(latest, pin));
261    }
262    if let Some(error) = &cache.error {
263        lines.push(format!(
264            "rk could not check for a newer release: {error}. Next try after {}.",
265            next_try(cache).unwrap_or_else(|| "the next entry".to_owned())
266        ));
267    }
268    lines
269}
270
271#[cfg(test)]
272mod tests {
273    use std::time::{Duration, SystemTime};
274
275    use super::{Cache, due, stamp, time};
276
277    fn ago(secs: u64) -> String {
278        stamp(SystemTime::now() - Duration::from_secs(secs))
279    }
280
281    #[test]
282    fn a_success_is_fresh_for_seven_days() {
283        let now = SystemTime::now();
284        let cache = |secs| Cache {
285            attempted: Some(ago(secs)),
286            succeeded: Some(ago(secs)),
287            latest: Some("v0.9.15".to_owned()),
288            error: None,
289        };
290        assert!(!due(Some(&cache(6 * 86_400)), now));
291        assert!(due(Some(&cache(7 * 86_400)), now));
292        assert!(due(None, now));
293    }
294
295    #[test]
296    fn a_failure_waits_one_hour_whatever_the_success() {
297        let now = SystemTime::now();
298        let cache = |failed| Cache {
299            attempted: Some(ago(failed)),
300            succeeded: Some(ago(8 * 86_400)),
301            latest: Some("v0.9.15".to_owned()),
302            error: Some("no answer".to_owned()),
303        };
304        assert!(!due(Some(&cache(60)), now));
305        assert!(!due(Some(&cache(59 * 60)), now));
306        assert!(due(Some(&cache(60 * 60)), now));
307    }
308
309    #[test]
310    fn an_unfinished_attempt_waits_one_hour() {
311        let now = SystemTime::now();
312        let first = |secs| Cache {
313            attempted: Some(ago(secs)),
314            ..Cache::default()
315        };
316        assert!(!due(Some(&first(60)), now));
317        assert!(due(Some(&first(60 * 60)), now));
318        let overdue = |secs| Cache {
319            attempted: Some(ago(secs)),
320            succeeded: Some(ago(8 * 86_400)),
321            latest: Some("v0.9.15".to_owned()),
322            error: None,
323        };
324        assert!(!due(Some(&overdue(60)), now));
325        assert!(due(Some(&overdue(60 * 60)), now));
326    }
327
328    #[test]
329    fn an_unreadable_time_counts_as_missing() {
330        let cache = Cache {
331            attempted: Some("yesterday".to_owned()),
332            succeeded: Some("last week".to_owned()),
333            latest: None,
334            error: None,
335        };
336        assert!(due(Some(&cache), SystemTime::now()));
337    }
338
339    #[test]
340    fn a_stamp_is_utc_to_the_second_and_reads_back() {
341        let at = SystemTime::UNIX_EPOCH + Duration::from_millis(1_794_874_301_750);
342        let text = stamp(at);
343        assert_eq!(text, "2026-11-17T00:11:41Z");
344        assert_eq!(
345            time(Some(&text)),
346            Some(SystemTime::UNIX_EPOCH + Duration::from_secs(1_794_874_301))
347        );
348    }
349}