printobserver_types/
timestamp.rs1use core::fmt;
10use core::str::FromStr;
11use std::borrow::Cow;
12
13use chrono::{DateTime, SecondsFormat, TimeDelta, Utc};
14use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
15use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as _};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct TimestampError {
20 detail: String,
22}
23
24impl TimestampError {
25 #[must_use]
27 pub fn detail(&self) -> &str {
28 &self.detail
29 }
30}
31
32impl fmt::Display for TimestampError {
33 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
34 write!(formatter, "not an RFC 3339 instant: {}", self.detail)
35 }
36}
37
38impl core::error::Error for TimestampError {}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct Timestamp(DateTime<Utc>);
43
44impl Timestamp {
45 #[must_use]
47 pub fn now() -> Self {
48 #[cfg(feature = "replay-clock")]
49 return Self(replay_clock::now(Utc::now()));
50 #[cfg(not(feature = "replay-clock"))]
51 Self(Utc::now())
52 }
53
54 pub fn from_unix_seconds(seconds: i64) -> Result<Self, TimestampError> {
61 DateTime::from_timestamp(seconds, 0)
62 .map(Self)
63 .ok_or_else(|| TimestampError {
64 detail: format!(
65 "{seconds} seconds from the Unix epoch is not a representable instant"
66 ),
67 })
68 }
69
70 pub fn plus_seconds(self, seconds: i64) -> Result<Self, TimestampError> {
80 TimeDelta::try_seconds(seconds)
84 .and_then(|span| self.0.checked_add_signed(span))
85 .map(Self)
86 .ok_or_else(|| TimestampError {
87 detail: format!("{seconds} seconds after {self} is not a representable instant"),
88 })
89 }
90
91 #[must_use]
103 pub fn latest() -> Self {
104 let last_day = chrono::NaiveDate::from_ymd_opt(9999, 12, 31)
105 .and_then(|day| day.and_hms_nano_opt(23, 59, 59, 999_999_999))
106 .expect("the last moment of the year 9999 is a date-time");
107 Self(last_day.and_utc())
108 }
109
110 #[must_use]
112 pub const fn as_utc(&self) -> &DateTime<Utc> {
113 &self.0
114 }
115}
116
117impl From<DateTime<Utc>> for Timestamp {
118 fn from(instant: DateTime<Utc>) -> Self {
119 Self(instant)
120 }
121}
122
123impl fmt::Display for Timestamp {
124 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
125 write!(
129 formatter,
130 "{}",
131 self.0.to_rfc3339_opts(SecondsFormat::AutoSi, true)
132 )
133 }
134}
135
136impl FromStr for Timestamp {
137 type Err = TimestampError;
138
139 fn from_str(text: &str) -> Result<Self, Self::Err> {
140 DateTime::parse_from_rfc3339(text)
141 .map(|offset| Self(offset.with_timezone(&Utc)))
142 .map_err(|error| TimestampError {
143 detail: format!("{text:?}: {error}"),
144 })
145 }
146}
147
148impl Serialize for Timestamp {
149 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
150 serializer.collect_str(self)
151 }
152}
153
154impl<'de> Deserialize<'de> for Timestamp {
155 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
156 let text = String::deserialize(deserializer)?;
157 text.parse().map_err(D::Error::custom)
158 }
159}
160
161impl JsonSchema for Timestamp {
162 fn schema_name() -> Cow<'static, str> {
163 Cow::Borrowed("Timestamp")
164 }
165
166 fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
167 json_schema!({
168 "type": "string",
169 "format": "date-time",
170 "title": "Timestamp",
171 "description": "An instant in UTC, as an RFC 3339 string with a zero offset."
172 })
173 }
174}
175
176#[cfg(feature = "replay-clock")]
182mod replay_clock {
183 use chrono::{DateTime, TimeDelta, Utc};
184 use std::path::PathBuf;
185 use std::sync::OnceLock;
186
187 const CLOCK_FILE: &str = "clock";
190
191 fn path() -> Option<&'static PathBuf> {
192 static PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
193 PATH.get_or_init(|| {
194 std::env::current_exe()
195 .ok()
196 .map(|program| program.with_file_name(CLOCK_FILE))
197 })
198 .as_ref()
199 }
200
201 pub(super) fn now(real: DateTime<Utc>) -> DateTime<Utc> {
202 let Some(text) = path().and_then(|file| std::fs::read_to_string(file).ok()) else {
203 return real;
204 };
205 let mut numbers = text.split_whitespace().map(str::parse::<i64>);
206 let Some(Ok(offset)) = numbers.next() else {
207 return real;
208 };
209 let Some(moved) =
210 TimeDelta::try_milliseconds(offset).and_then(|by| real.checked_add_signed(by))
211 else {
212 return real;
213 };
214 match numbers.next() {
215 Some(Ok(ceiling)) => {
216 DateTime::from_timestamp_millis(ceiling).map_or(moved, |held| moved.min(held))
217 }
218 _ => moved,
219 }
220 }
221}