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";
const LOCK: &str = "remote-pushed.lock";
const KEPT: Duration = Duration::from_secs(48 * 60 * 60);
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."))
}
}
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,
})
}
pub fn recent(state: Option<&Path>) -> Result<Vec<Pushed>, String> {
recent_at(state, Timestamp::now())
}
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;