Skip to main content

artifactize_core/remote/
pushed.rs

1//! What this machine pushed to the remote review store lately: each push that sent records,
2//! when and how many, kept two days so a reader can say what was pushed on its own local day.
3
4use std::{
5    fs,
6    io::Write,
7    path::Path,
8    time::{Duration, SystemTime, UNIX_EPOCH},
9};
10
11use serde::{Deserialize, Serialize};
12
13/// The file in the state directory that keeps the recent pushes.
14const FILE: &str = "remote-pushed.json";
15/// How long a push is kept: any local day still holds its own pushes.
16const KEPT: Duration = Duration::from_secs(48 * 60 * 60);
17
18/// One push that sent records: when, in milliseconds since the Unix epoch, and how many.
19#[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
33/// The pushes this machine made in the last two days, oldest first, from the state directory
34/// `state` names (the shared one by default); none when nothing was kept or it cannot be read.
35pub fn recent(state: Option<&Path>) -> Vec<Pushed> {
36    crate::store::state_dir(state).map_or_else(|_| Vec::new(), |dir| kept(&dir))
37}
38
39/// The pushes kept in the state directory `state` from the last two days, oldest first.
40fn 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
52/// Keep a push of `count` records made now, with the others of the last two days.
53pub(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        // A push older than two days is no longer kept.
82        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}