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::{
5    ffi::OsStr,
6    io::{self, Read, Write},
7    path::Path,
8    time::Duration,
9};
10
11const FILE: &str = "remote-pushed.json";
12/// A separate lock inode stays in place across atomic history updates.
13const LOCK: &str = "remote-pushed.lock";
14/// Retain every push that could still belong to the reader's local day.
15const KEPT: Duration = Duration::from_secs(48 * 60 * 60);
16/// The existing JSON wire uses epoch milliseconds; Timestamp keeps nanoseconds internally.
17const NANOS_PER_MILLISECOND: i128 = 1_000_000;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Pushed {
21    #[serde(with = "milliseconds")]
22    pub at: Timestamp,
23    pub count: usize,
24}
25mod milliseconds {
26    use super::*;
27    use serde::{Deserializer, Serializer};
28    pub(super) fn serialize<S: Serializer>(
29        at: &Timestamp,
30        serializer: S,
31    ) -> Result<S::Ok, S::Error> {
32        let value = u64::try_from(at.time().unix_timestamp_nanos() / NANOS_PER_MILLISECOND)
33            .map_err(serde::ser::Error::custom)?;
34        serializer.serialize_u64(value)
35    }
36    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
37        deserializer: D,
38    ) -> Result<Timestamp, D::Error> {
39        let millis = u64::deserialize(deserializer)?;
40        time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(millis) * NANOS_PER_MILLISECOND)
41            .ok()
42            .and_then(Timestamp::new)
43            .ok_or_else(|| serde::de::Error::custom("Push timestamp is out of range."))
44    }
45}
46/// One ledger read supplies the recent records and the local day's total.
47pub struct PushHistory {
48    pub recent: Vec<Pushed>,
49    pub pushed_today: usize,
50}
51
52pub fn history_at(state: Option<&Path>, now: Timestamp) -> Result<PushHistory, String> {
53    history_in(state, now, crate::platform::local_day)
54}
55
56fn history_in(
57    state: Option<&Path>,
58    now: Timestamp,
59    local_day: impl Fn(time::OffsetDateTime) -> time::Date,
60) -> Result<PushHistory, String> {
61    let recent = recent_at(state, now)?;
62    let day = local_day(now.time());
63    let pushed_today = recent
64        .iter()
65        .filter(|push| push.at <= now && local_day(push.at.time()) == day)
66        .fold(0usize, |total, push| total.saturating_add(push.count));
67    Ok(PushHistory {
68        recent,
69        pushed_today,
70    })
71}
72
73/// Recent pushes, oldest first; a missing ledger starts empty.
74pub fn recent(state: Option<&Path>) -> Result<Vec<Pushed>, String> {
75    recent_at(state, Timestamp::now())
76}
77
78/// Get the recent pushes relative to the supplied time.
79pub fn recent_at(state: Option<&Path>, now: Timestamp) -> Result<Vec<Pushed>, String> {
80    kept_at(&crate::store::state_dir(state)?, now)
81}
82
83fn kept_at(state: &Path, now: Timestamp) -> Result<Vec<Pushed>, String> {
84    use crate::platform;
85    let read = || -> io::Result<String> {
86        let directory = platform::open_directory(state)?;
87        let mut file = platform::paths::open_regular_entry(&directory, OsStr::new(FILE))?;
88        let mut text = String::new();
89        file.read_to_string(&mut text)?;
90        Ok(text)
91    };
92    let text = match read() {
93        Ok(text) => text,
94        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
95        Err(error) => return Err(format!("Cannot read remote push history: {error}")),
96    };
97    let pushes = serde_json::from_str::<Vec<Pushed>>(&text).map_err(|error| {
98        format!(
99            "Invalid remote push history at line {}, column {}.",
100            error.line(),
101            error.column()
102        )
103    })?;
104    Ok(pushes
105        .into_iter()
106        .filter(|pushed| now.since(pushed.at) <= KEPT)
107        .collect())
108}
109pub(super) fn record_at(state: &Path, count: usize, at: Timestamp) -> Result<(), String> {
110    let lock = crate::platform::open_no_follow(
111        crate::platform::private_options()
112            .read(true)
113            .write(true)
114            .create(true)
115            .truncate(false),
116        &state.join(LOCK),
117    )
118    .map_err(|error| error.to_string())?;
119    crate::platform::paths::lock(&lock).map_err(|error| error.to_string())?;
120    let mut pushes = kept_at(state, at)?;
121    pushes.push(Pushed { at, count });
122    let mut file = tempfile::NamedTempFile::new_in(state).map_err(|error| error.to_string())?;
123    serde_json::to_writer(&mut file, &pushes).map_err(|error| error.to_string())?;
124    file.flush().map_err(|error| error.to_string())?;
125    crate::platform::paths::replace_open_file(file, &state.join(FILE))
126        .map_err(|error| error.to_string())
127}
128#[cfg(test)]
129mod tests;