1use std::fs;
11use std::path::{Path, PathBuf};
12use std::time::{Duration, SystemTime};
13
14use serde::{Deserialize, Serialize};
15
16use super::discover::{self, Discovery};
17
18pub const SUCCESS_INTERVAL: Duration = Duration::from_secs(7 * 24 * 60 * 60);
20
21pub const RETRY_INTERVAL: Duration = Duration::from_secs(60 * 60);
23
24#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Cache {
27 pub attempted: Option<String>,
29 pub succeeded: Option<String>,
31 pub latest: Option<String>,
33 pub error: Option<String>,
35}
36
37#[derive(Debug, Clone)]
39pub struct Paths {
40 pub cache: PathBuf,
42 pub lock: PathBuf,
44}
45
46impl Paths {
47 #[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#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Outcome {
61 Cached,
63 Refreshed,
65 Locked,
67 Unwritable(String),
69}
70
71impl Outcome {
72 #[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
84fn time(text: Option<&str>) -> Option<SystemTime> {
86 let at: jiff::Timestamp = text?.parse().ok()?;
87 SystemTime::try_from(at).ok()
88}
89
90#[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
99fn age(now: SystemTime, then: SystemTime) -> Duration {
101 now.duration_since(then).unwrap_or_default()
102}
103
104#[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#[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#[must_use]
139pub fn read(path: &Path) -> Option<Cache> {
140 serde_json::from_slice(&fs::read(path).ok()?).ok()
141}
142
143fn 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#[derive(Debug, Clone)]
152pub struct Run {
153 pub outcome: Outcome,
155 pub cache: Option<Cache>,
157 pub fetched: bool,
159}
160
161#[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
173fn 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 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 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 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#[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}