artifactize-core 0.27.1

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! Recent pushes to the remote review store, retained for two days.
use crate::types::Timestamp;
use serde::{Deserialize, Serialize};
use std::{
    ffi::OsStr,
    io::{self, Read, Write},
    path::Path,
    time::Duration,
};

const FILE: &str = "remote-pushed.json";
/// A separate lock inode stays in place across atomic history updates.
const LOCK: &str = "remote-pushed.lock";
/// Retain every push that could still belong to the reader's local day.
const KEPT: Duration = Duration::from_secs(48 * 60 * 60);
/// The existing JSON wire uses epoch milliseconds; Timestamp keeps nanoseconds internally.
const NANOS_PER_MILLISECOND: i128 = 1_000_000;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Pushed {
    #[serde(with = "milliseconds")]
    pub at: Timestamp,
    pub count: usize,
}
mod milliseconds {
    use super::*;
    use serde::{Deserializer, Serializer};
    pub(super) fn serialize<S: Serializer>(
        at: &Timestamp,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        let value = u64::try_from(at.time().unix_timestamp_nanos() / NANOS_PER_MILLISECOND)
            .map_err(serde::ser::Error::custom)?;
        serializer.serialize_u64(value)
    }
    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Timestamp, D::Error> {
        let millis = u64::deserialize(deserializer)?;
        time::OffsetDateTime::from_unix_timestamp_nanos(i128::from(millis) * NANOS_PER_MILLISECOND)
            .ok()
            .and_then(Timestamp::new)
            .ok_or_else(|| serde::de::Error::custom("Push timestamp is out of range."))
    }
}
/// One ledger read supplies the recent records and the local day's total.
pub struct PushHistory {
    pub recent: Vec<Pushed>,
    pub pushed_today: usize,
}

pub fn history_at(state: Option<&Path>, now: Timestamp) -> Result<PushHistory, String> {
    history_in(state, now, crate::platform::local_day)
}

fn history_in(
    state: Option<&Path>,
    now: Timestamp,
    local_day: impl Fn(time::OffsetDateTime) -> time::Date,
) -> Result<PushHistory, String> {
    let recent = recent_at(state, now)?;
    let day = local_day(now.time());
    let pushed_today = recent
        .iter()
        .filter(|push| push.at <= now && local_day(push.at.time()) == day)
        .fold(0usize, |total, push| total.saturating_add(push.count));
    Ok(PushHistory {
        recent,
        pushed_today,
    })
}

/// Recent pushes, oldest first; a missing ledger starts empty.
pub fn recent(state: Option<&Path>) -> Result<Vec<Pushed>, String> {
    recent_at(state, Timestamp::now())
}

/// Get the recent pushes relative to the supplied time.
pub fn recent_at(state: Option<&Path>, now: Timestamp) -> Result<Vec<Pushed>, String> {
    kept_at(&crate::store::state_dir(state)?, now)
}

fn kept_at(state: &Path, now: Timestamp) -> Result<Vec<Pushed>, String> {
    use crate::platform;
    let read = || -> io::Result<String> {
        let directory = platform::open_directory(state)?;
        let mut file = platform::paths::open_regular_entry(&directory, OsStr::new(FILE))?;
        let mut text = String::new();
        file.read_to_string(&mut text)?;
        Ok(text)
    };
    let text = match read() {
        Ok(text) => text,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(error) => return Err(format!("Cannot read remote push history: {error}")),
    };
    let pushes = serde_json::from_str::<Vec<Pushed>>(&text).map_err(|error| {
        format!(
            "Invalid remote push history at line {}, column {}.",
            error.line(),
            error.column()
        )
    })?;
    Ok(pushes
        .into_iter()
        .filter(|pushed| now.since(pushed.at) <= KEPT)
        .collect())
}
pub(super) fn record_at(state: &Path, count: usize, at: Timestamp) -> Result<(), String> {
    let lock = crate::platform::open_no_follow(
        crate::platform::private_options()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false),
        &state.join(LOCK),
    )
    .map_err(|error| error.to_string())?;
    crate::platform::paths::lock(&lock).map_err(|error| error.to_string())?;
    let mut pushes = kept_at(state, at)?;
    pushes.push(Pushed { at, count });
    let mut file = tempfile::NamedTempFile::new_in(state).map_err(|error| error.to_string())?;
    serde_json::to_writer(&mut file, &pushes).map_err(|error| error.to_string())?;
    file.flush().map_err(|error| error.to_string())?;
    crate::platform::paths::replace_open_file(file, &state.join(FILE))
        .map_err(|error| error.to_string())
}
#[cfg(test)]
mod tests;