use core::fmt;
use core::str::FromStr;
use std::borrow::Cow;
use chrono::{DateTime, SecondsFormat, TimeDelta, Utc};
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimestampError {
detail: String,
}
impl TimestampError {
#[must_use]
pub fn detail(&self) -> &str {
&self.detail
}
}
impl fmt::Display for TimestampError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "not an RFC 3339 instant: {}", self.detail)
}
}
impl core::error::Error for TimestampError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp(DateTime<Utc>);
impl Timestamp {
#[must_use]
pub fn now() -> Self {
#[cfg(feature = "replay-clock")]
return Self(replay_clock::now(Utc::now()));
#[cfg(not(feature = "replay-clock"))]
Self(Utc::now())
}
#[must_use]
pub fn pass_replay_time(wait: core::time::Duration) -> bool {
#[cfg(feature = "replay-clock")]
return replay_clock::advance(wait);
#[cfg(not(feature = "replay-clock"))]
{
let _ = wait;
false
}
}
pub fn from_unix_seconds(seconds: i64) -> Result<Self, TimestampError> {
DateTime::from_timestamp(seconds, 0)
.map(Self)
.ok_or_else(|| TimestampError {
detail: format!(
"{seconds} seconds from the Unix epoch is not a representable instant"
),
})
}
pub fn plus_seconds(self, seconds: i64) -> Result<Self, TimestampError> {
TimeDelta::try_seconds(seconds)
.and_then(|span| self.0.checked_add_signed(span))
.map(Self)
.ok_or_else(|| TimestampError {
detail: format!("{seconds} seconds after {self} is not a representable instant"),
})
}
#[must_use]
pub fn latest() -> Self {
let last_day = chrono::NaiveDate::from_ymd_opt(9999, 12, 31)
.and_then(|day| day.and_hms_nano_opt(23, 59, 59, 999_999_999))
.expect("the last moment of the year 9999 is a date-time");
Self(last_day.and_utc())
}
#[must_use]
pub const fn as_utc(&self) -> &DateTime<Utc> {
&self.0
}
}
impl From<DateTime<Utc>> for Timestamp {
fn from(instant: DateTime<Utc>) -> Self {
Self(instant)
}
}
impl fmt::Display for Timestamp {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"{}",
self.0.to_rfc3339_opts(SecondsFormat::AutoSi, true)
)
}
}
impl FromStr for Timestamp {
type Err = TimestampError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
DateTime::parse_from_rfc3339(text)
.map(|offset| Self(offset.with_timezone(&Utc)))
.map_err(|error| TimestampError {
detail: format!("{text:?}: {error}"),
})
}
}
impl Serialize for Timestamp {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Timestamp {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(D::Error::custom)
}
}
impl JsonSchema for Timestamp {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("Timestamp")
}
fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
json_schema!({
"type": "string",
"format": "date-time",
"title": "Timestamp",
"description": "An instant in UTC, as an RFC 3339 string with a zero offset."
})
}
}
#[cfg(feature = "replay-clock")]
mod replay_clock {
use chrono::{DateTime, TimeDelta, Utc};
use std::path::PathBuf;
use std::sync::OnceLock;
const CLOCK_FILE: &str = "clock";
const REAL_WAITS: &str = "PRINTOBSERVER_REPLAY_REAL_WAITS";
fn path() -> Option<&'static PathBuf> {
static PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
PATH.get_or_init(|| {
std::env::current_exe()
.ok()
.map(|program| program.with_file_name(CLOCK_FILE))
})
.as_ref()
}
pub(super) fn advance(wait: core::time::Duration) -> bool {
if std::env::var_os(REAL_WAITS).is_some() {
return false;
}
let Some(file) = path() else {
return false;
};
let Ok(text) = std::fs::read_to_string(file) else {
return false;
};
let mut words = text.split_whitespace();
let Some(Ok(offset)) = words.next().map(str::parse::<i64>) else {
return false;
};
let Ok(by) = i64::try_from(wait.as_millis()) else {
return false;
};
let ceiling = words
.next()
.map(|ceiling| format!(" {ceiling}"))
.unwrap_or_default();
let written = file.with_extension(format!("advance-{}", std::process::id()));
std::fs::write(
&written,
format!("{}{ceiling}\n", offset.saturating_add(by)),
)
.is_ok()
&& std::fs::rename(&written, file).is_ok()
}
pub(super) fn now(real: DateTime<Utc>) -> DateTime<Utc> {
let Some(text) = path().and_then(|file| std::fs::read_to_string(file).ok()) else {
return real;
};
let mut numbers = text.split_whitespace().map(str::parse::<i64>);
let Some(Ok(offset)) = numbers.next() else {
return real;
};
let Some(moved) =
TimeDelta::try_milliseconds(offset).and_then(|by| real.checked_add_signed(by))
else {
return real;
};
match numbers.next() {
Some(Ok(ceiling)) => {
DateTime::from_timestamp_millis(ceiling).map_or(moved, |held| moved.min(held))
}
_ => moved,
}
}
}