Skip to main content

artifactize_core/remote/
pushed.rs

1//! Recent pushes to the remote review store, retained for two days.
2use crate::types::Timestamp;
3use serde::{Deserialize, Serialize};
4use std::{fs, io::Write, path::Path, time::Duration};
5
6const FILE: &str = "remote-pushed.json";
7/// A separate lock inode stays in place across atomic history updates.
8const LOCK: &str = "remote-pushed.lock";
9/// Retain every push that could still belong to the reader's local day.
10const KEPT: Duration = Duration::from_secs(48 * 60 * 60);
11/// The existing JSON wire uses epoch milliseconds; Timestamp keeps nanoseconds internally.
12const NANOS_PER_MILLISECOND: i128 = 1_000_000;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15pub struct Pushed {
16    #[serde(with = "milliseconds")]
17    pub at: Timestamp,
18    pub count: usize,
19}
20impl Pushed {
21    /// Numeric timestamp for a JSON presentation boundary, not for time arithmetic.
22    pub fn unix_millis(self) -> i128 {
23        self.at.time().unix_timestamp_nanos() / NANOS_PER_MILLISECOND
24    }
25}
26mod milliseconds {
27    use super::*;
28    use serde::{Deserializer, Serializer};
29    pub(super) fn serialize<S: Serializer>(
30        at: &Timestamp,
31        serializer: S,
32    ) -> Result<S::Ok, S::Error> {
33        let value = u64::try_from(at.time().unix_timestamp_nanos() / NANOS_PER_MILLISECOND)
34            .map_err(serde::ser::Error::custom)?;
35        serializer.serialize_u64(value)
36    }
37    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
38        deserializer: D,
39    ) -> Result<Timestamp, D::Error> {
40        let millis = u64::deserialize(deserializer)?;
41        time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(millis) * NANOS_PER_MILLISECOND)
42            .ok()
43            .and_then(Timestamp::new)
44            .ok_or_else(|| serde::de::Error::custom("Push timestamp is out of range."))
45    }
46}
47/// Recent pushes, oldest first; absent or unreadable state has no history to show.
48pub fn recent(state: Option<&Path>) -> Vec<Pushed> {
49    recent_at(state, Timestamp::now())
50}
51
52/// Get the recent pushes relative to the supplied time.
53pub fn recent_at(state: Option<&Path>, now: Timestamp) -> Vec<Pushed> {
54    crate::store::state_dir(state).map_or_else(|_| Vec::new(), |dir| kept_at(&dir, now))
55}
56fn kept_at(state: &Path, now: Timestamp) -> Vec<Pushed> {
57    let Ok(text) = fs::read_to_string(state.join(FILE)) else {
58        return Vec::new();
59    };
60    serde_json::from_str::<Vec<Pushed>>(&text)
61        .unwrap_or_default()
62        .into_iter()
63        .filter(|pushed| now.since(pushed.at) <= KEPT)
64        .collect()
65}
66pub(super) fn record_at(state: &Path, count: usize, at: Timestamp) -> Result<(), String> {
67    let lock = crate::platform::open_no_follow(
68        crate::platform::private_options()
69            .read(true)
70            .write(true)
71            .create(true)
72            .truncate(false),
73        &state.join(LOCK),
74    )
75    .map_err(|error| error.to_string())?;
76    lock.lock().map_err(|error| error.to_string())?;
77    let mut pushes = kept_at(state, at);
78    pushes.push(Pushed { at, count });
79    let mut file = tempfile::NamedTempFile::new_in(state).map_err(|error| error.to_string())?;
80    serde_json::to_writer(&mut file, &pushes).map_err(|error| error.to_string())?;
81    file.flush().map_err(|error| error.to_string())?;
82    crate::platform::paths::replace_open_file(file, &state.join(FILE))
83        .map_err(|error| error.to_string())
84}
85#[cfg(test)]
86mod tests {
87    use super::*;
88    #[test]
89    fn concurrent_pushes_keep_all_counts() {
90        let state = crate::test_os::tempdir();
91        let at = Timestamp::new(time::OffsetDateTime::UNIX_EPOCH).unwrap();
92        let counts = 1..=8;
93        let ready = std::sync::Barrier::new(counts.clone().count());
94        std::thread::scope(|scope| {
95            for count in counts.clone() {
96                let path = state.path();
97                let ready = &ready;
98                scope.spawn(move || {
99                    ready.wait();
100                    record_at(path, count, at).unwrap();
101                });
102            }
103        });
104        let mut saved: Vec<_> = kept_at(state.path(), at)
105            .into_iter()
106            .map(|entry| entry.count)
107            .collect();
108        saved.sort_unstable();
109        assert_eq!(saved, counts.collect::<Vec<_>>());
110    }
111
112    #[test]
113    fn keeps_each_push_with_its_count_and_drops_old_ones() {
114        let state = crate::test_os::tempdir();
115        let at =
116            Timestamp::new(time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(10)).unwrap();
117        let after = |duration| Timestamp::new(at.time() + duration).unwrap();
118        assert!(kept_at(state.path(), at).is_empty());
119        record_at(state.path(), 3, at).unwrap();
120        record_at(state.path(), 2, after(time::Duration::seconds(1))).unwrap();
121        let wire: serde_json::Value =
122            serde_json::from_str(&fs::read_to_string(state.path().join(FILE)).unwrap()).unwrap();
123        assert_eq!(
124            wire,
125            serde_json::json!([{"at":10000,"count":3},{"at":11000,"count":2}])
126        );
127        let counts = |now| {
128            kept_at(state.path(), now)
129                .into_iter()
130                .map(|push| push.count)
131                .collect::<Vec<_>>()
132        };
133        assert_eq!(counts(after(time::Duration::hours(48))), [3, 2]);
134        assert_eq!(
135            counts(after(
136                time::Duration::hours(48) + time::Duration::milliseconds(1)
137            )),
138            [2]
139        );
140        assert!(counts(after(time::Duration::hours(49))).is_empty());
141    }
142}