artifactize_core/remote/
pushed.rs1use std::{
5 fs,
6 io::Write,
7 path::Path,
8 time::{Duration, SystemTime, UNIX_EPOCH},
9};
10
11use serde::{Deserialize, Serialize};
12
13const FILE: &str = "remote-pushed.json";
15const KEPT: Duration = Duration::from_secs(48 * 60 * 60);
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Pushed {
21 pub at: u64,
22 pub count: usize,
23}
24
25fn now() -> u64 {
26 SystemTime::now()
27 .duration_since(UNIX_EPOCH)
28 .map_or(0, |since| {
29 u64::try_from(since.as_millis()).unwrap_or(u64::MAX)
30 })
31}
32
33pub fn recent(state: Option<&Path>) -> Vec<Pushed> {
36 crate::store::state_dir(state).map_or_else(|_| Vec::new(), |dir| kept(&dir))
37}
38
39fn kept(state: &Path) -> Vec<Pushed> {
41 let Ok(text) = fs::read_to_string(state.join(FILE)) else {
42 return Vec::new();
43 };
44 let since = now().saturating_sub(u64::try_from(KEPT.as_millis()).unwrap_or(u64::MAX));
45 serde_json::from_str::<Vec<Pushed>>(&text)
46 .unwrap_or_default()
47 .into_iter()
48 .filter(|pushed| pushed.at >= since)
49 .collect()
50}
51
52pub(crate) fn record(state: &Path, count: usize) -> Result<(), String> {
54 let mut pushes = kept(state);
55 pushes.push(Pushed { at: now(), count });
56 let mut file = tempfile::NamedTempFile::new_in(state).map_err(|e| e.to_string())?;
57 serde_json::to_writer(&mut file, &pushes).map_err(|e| e.to_string())?;
58 file.flush().map_err(|e| e.to_string())?;
59 file.persist(state.join(FILE))
60 .map_err(|e| e.error.to_string())?;
61 Ok(())
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn keeps_each_push_with_its_count_and_drops_old_ones() {
70 let state = tempfile::tempdir().expect("state");
71 assert!(kept(state.path()).is_empty());
72 record(state.path(), 3).expect("first push");
73 record(state.path(), 2).expect("second push");
74 assert_eq!(
75 kept(state.path())
76 .iter()
77 .map(|pushed| pushed.count)
78 .collect::<Vec<_>>(),
79 [3, 2]
80 );
81 let old = [Pushed { at: 1, count: 9 }];
83 fs::write(
84 state.path().join(FILE),
85 serde_json::to_string(&old).unwrap(),
86 )
87 .unwrap();
88 assert!(kept(state.path()).is_empty());
89 }
90}