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/// One ledger read supplies the recent records and the local day's total.
48pub struct PushHistory {
49    pub recent: Vec<Pushed>,
50    pub pushed_today: usize,
51}
52
53pub fn history_at(state: Option<&Path>, now: Timestamp) -> PushHistory {
54    history_in(state, now, crate::platform::local_day)
55}
56
57fn history_in(
58    state: Option<&Path>,
59    now: Timestamp,
60    local_day: impl Fn(time::OffsetDateTime) -> time::Date,
61) -> PushHistory {
62    let recent = recent_at(state, now);
63    let day = local_day(now.time());
64    let pushed_today = recent
65        .iter()
66        .filter(|push| push.at <= now && local_day(push.at.time()) == day)
67        .fold(0usize, |total, push| total.saturating_add(push.count));
68    PushHistory {
69        recent,
70        pushed_today,
71    }
72}
73
74/// Recent pushes, oldest first; absent or unreadable state has no history to show.
75pub fn recent(state: Option<&Path>) -> Vec<Pushed> {
76    recent_at(state, Timestamp::now())
77}
78
79/// Get the recent pushes relative to the supplied time.
80pub fn recent_at(state: Option<&Path>, now: Timestamp) -> Vec<Pushed> {
81    crate::store::state_dir(state).map_or_else(|_| Vec::new(), |dir| kept_at(&dir, now))
82}
83fn kept_at(state: &Path, now: Timestamp) -> Vec<Pushed> {
84    let Ok(text) = fs::read_to_string(state.join(FILE)) else {
85        return Vec::new();
86    };
87    serde_json::from_str::<Vec<Pushed>>(&text)
88        .unwrap_or_default()
89        .into_iter()
90        .filter(|pushed| now.since(pushed.at) <= KEPT)
91        .collect()
92}
93pub(super) fn record_at(state: &Path, count: usize, at: Timestamp) -> Result<(), String> {
94    let lock = crate::platform::open_no_follow(
95        crate::platform::private_options()
96            .read(true)
97            .write(true)
98            .create(true)
99            .truncate(false),
100        &state.join(LOCK),
101    )
102    .map_err(|error| error.to_string())?;
103    crate::platform::paths::lock(&lock).map_err(|error| error.to_string())?;
104    let mut pushes = kept_at(state, at);
105    pushes.push(Pushed { at, count });
106    let mut file = tempfile::NamedTempFile::new_in(state).map_err(|error| error.to_string())?;
107    serde_json::to_writer(&mut file, &pushes).map_err(|error| error.to_string())?;
108    file.flush().map_err(|error| error.to_string())?;
109    crate::platform::paths::replace_open_file(file, &state.join(FILE))
110        .map_err(|error| error.to_string())
111}
112#[cfg(test)]
113mod tests {
114    use super::*;
115    #[test]
116    fn ledger_today_uses_civil_days_at_each_push_not_the_current_offset() {
117        let state = crate::test_os::tempdir();
118        let stamp = |text: &str| text.parse::<Timestamp>().unwrap();
119        let before = stamp("2026-03-08T04:59:59Z");
120        let midnight = stamp("2026-03-08T05:00:00Z");
121        let daylight = stamp("2026-03-08T07:00:00Z");
122        let now = stamp("2026-03-08T16:00:00Z");
123        let future = stamp("2026-03-08T16:01:00Z");
124        for (at, count) in [(before, 9), (midnight, 3), (daylight, 2), (future, 11)] {
125            record_at(state.path(), count, at).unwrap();
126        }
127        let history = history_in(Some(state.path()), now, |instant| {
128            let hours = if instant < daylight.time() { -5 } else { -4 };
129            instant
130                .to_offset(time::UtcOffset::from_hms(hours, 0, 0).unwrap())
131                .date()
132        });
133        assert_eq!(history.recent.len(), 4);
134        assert_eq!(history.pushed_today, 5);
135    }
136
137    #[test]
138    fn concurrent_pushes_keep_all_counts() {
139        let state = crate::test_os::tempdir();
140        let at = Timestamp::new(time::OffsetDateTime::UNIX_EPOCH).unwrap();
141        let counts = 1..=8;
142        let ready = std::sync::Barrier::new(counts.clone().count());
143        std::thread::scope(|scope| {
144            for count in counts.clone() {
145                let path = state.path();
146                let ready = &ready;
147                scope.spawn(move || {
148                    ready.wait();
149                    record_at(path, count, at).unwrap();
150                });
151            }
152        });
153        let mut saved: Vec<_> = kept_at(state.path(), at)
154            .into_iter()
155            .map(|entry| entry.count)
156            .collect();
157        saved.sort_unstable();
158        assert_eq!(saved, counts.collect::<Vec<_>>());
159    }
160
161    #[test]
162    fn keeps_each_push_with_its_count_and_drops_old_ones() {
163        let state = crate::test_os::tempdir();
164        let at =
165            Timestamp::new(time::OffsetDateTime::UNIX_EPOCH + time::Duration::seconds(10)).unwrap();
166        let after = |duration| Timestamp::new(at.time() + duration).unwrap();
167        assert!(kept_at(state.path(), at).is_empty());
168        record_at(state.path(), 3, at).unwrap();
169        record_at(state.path(), 2, after(time::Duration::seconds(1))).unwrap();
170        let wire: serde_json::Value =
171            serde_json::from_str(&fs::read_to_string(state.path().join(FILE)).unwrap()).unwrap();
172        assert_eq!(
173            wire,
174            serde_json::json!([{"at":10000,"count":3},{"at":11000,"count":2}])
175        );
176        let counts = |now| {
177            kept_at(state.path(), now)
178                .into_iter()
179                .map(|push| push.count)
180                .collect::<Vec<_>>()
181        };
182        assert_eq!(counts(after(time::Duration::hours(48))), [3, 2]);
183        assert_eq!(
184            counts(after(
185                time::Duration::hours(48) + time::Duration::milliseconds(1)
186            )),
187            [2]
188        );
189        assert!(counts(after(time::Duration::hours(49))).is_empty());
190    }
191}