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 #[must_use]
63 pub fn pass_replay_time(wait: core::time::Duration) -> bool {
65 #[cfg(feature = "replay-clock")]
66 return replay_clock::advance(wait);
67 #[cfg(not(feature = "replay-clock"))]
68 {
69 let _ = wait;
70 false
71 }
72 }
73
74 pub fn from_unix_seconds(seconds: i64) -> Result<Self, TimestampError> {
81 DateTime::from_timestamp(seconds, 0)
82 .map(Self)
83 .ok_or_else(|| TimestampError {
84 detail: format!(
85 "{seconds} seconds from the Unix epoch is not a representable instant"
86 ),
87 })
88 }
89
90 pub fn plus_seconds(self, seconds: i64) -> Result<Self, TimestampError> {
100 TimeDelta::try_seconds(seconds)
104 .and_then(|span| self.0.checked_add_signed(span))
105 .map(Self)
106 .ok_or_else(|| TimestampError {
107 detail: format!("{seconds} seconds after {self} is not a representable instant"),
108 })
109 }
110
111 #[must_use]
123 pub fn latest() -> Self {
124 let last_day = chrono::NaiveDate::from_ymd_opt(9999, 12, 31)
125 .and_then(|day| day.and_hms_nano_opt(23, 59, 59, 999_999_999))
126 .expect("the last moment of the year 9999 is a date-time");
127 Self(last_day.and_utc())
128 }
129
130 #[must_use]
132 pub const fn as_utc(&self) -> &DateTime<Utc> {
133 &self.0
134 }
135}
136
137impl From<DateTime<Utc>> for Timestamp {
138 fn from(instant: DateTime<Utc>) -> Self {
139 Self(instant)
140 }
141}
142
143impl fmt::Display for Timestamp {
144 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
145 write!(
149 formatter,
150 "{}",
151 self.0.to_rfc3339_opts(SecondsFormat::AutoSi, true)
152 )
153 }
154}
155
156impl FromStr for Timestamp {
157 type Err = TimestampError;
158
159 fn from_str(text: &str) -> Result<Self, Self::Err> {
160 DateTime::parse_from_rfc3339(text)
161 .map(|offset| Self(offset.with_timezone(&Utc)))
162 .map_err(|error| TimestampError {
163 detail: format!("{text:?}: {error}"),
164 })
165 }
166}
167
168impl Serialize for Timestamp {
169 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
170 serializer.collect_str(self)
171 }
172}
173
174impl<'de> Deserialize<'de> for Timestamp {
175 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
176 let text = String::deserialize(deserializer)?;
177 text.parse().map_err(D::Error::custom)
178 }
179}
180
181impl JsonSchema for Timestamp {
182 fn schema_name() -> Cow<'static, str> {
183 Cow::Borrowed("Timestamp")
184 }
185
186 fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
187 json_schema!({
188 "type": "string",
189 "format": "date-time",
190 "title": "Timestamp",
191 "description": "An instant in UTC, as an RFC 3339 string with a zero offset."
192 })
193 }
194}
195
196#[cfg(feature = "replay-clock")]
202mod replay_clock {
203 use chrono::{DateTime, TimeDelta, Utc};
204 use std::path::PathBuf;
205 use std::sync::OnceLock;
206
207 const CLOCK_FILE: &str = "clock";
210
211 const REAL_WAITS: &str = "PRINTOBSERVER_REPLAY_REAL_WAITS";
214
215 fn path() -> Option<&'static PathBuf> {
216 static PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
217 PATH.get_or_init(|| {
218 std::env::current_exe()
219 .ok()
220 .map(|program| program.with_file_name(CLOCK_FILE))
221 })
222 .as_ref()
223 }
224
225 pub(super) fn advance(wait: core::time::Duration) -> bool {
230 if std::env::var_os(REAL_WAITS).is_some() {
231 return false;
232 }
233 let Some(file) = path() else {
234 return false;
235 };
236 let Ok(text) = std::fs::read_to_string(file) else {
237 return false;
238 };
239 let mut words = text.split_whitespace();
240 let Some(Ok(offset)) = words.next().map(str::parse::<i64>) else {
241 return false;
242 };
243 let Ok(by) = i64::try_from(wait.as_millis()) else {
244 return false;
245 };
246 let ceiling = words
247 .next()
248 .map(|ceiling| format!(" {ceiling}"))
249 .unwrap_or_default();
250 let written = file.with_extension(format!("advance-{}", std::process::id()));
251 std::fs::write(
252 &written,
253 format!("{}{ceiling}\n", offset.saturating_add(by)),
254 )
255 .is_ok()
256 && std::fs::rename(&written, file).is_ok()
257 }
258
259 pub(super) fn now(real: DateTime<Utc>) -> DateTime<Utc> {
260 let Some(text) = path().and_then(|file| std::fs::read_to_string(file).ok()) else {
261 return real;
262 };
263 let mut numbers = text.split_whitespace().map(str::parse::<i64>);
264 let Some(Ok(offset)) = numbers.next() else {
265 return real;
266 };
267 let Some(moved) =
268 TimeDelta::try_milliseconds(offset).and_then(|by| real.checked_add_signed(by))
269 else {
270 return real;
271 };
272 match numbers.next() {
273 Some(Ok(ceiling)) => {
274 DateTime::from_timestamp_millis(ceiling).map_or(moved, |held| moved.min(held))
275 }
276 _ => moved,
277 }
278 }
279}