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 #[must_use]
86 pub fn on_replay_clock(steady: core::time::Duration) -> core::time::Duration {
88 #[cfg(feature = "replay-clock")]
89 return replay_clock::steady(steady);
90 #[cfg(not(feature = "replay-clock"))]
91 steady
92 }
93
94 pub fn from_unix_seconds(seconds: i64) -> Result<Self, TimestampError> {
101 DateTime::from_timestamp(seconds, 0)
102 .map(Self)
103 .ok_or_else(|| TimestampError {
104 detail: format!(
105 "{seconds} seconds from the Unix epoch is not a representable instant"
106 ),
107 })
108 }
109
110 pub fn plus_seconds(self, seconds: i64) -> Result<Self, TimestampError> {
120 TimeDelta::try_seconds(seconds)
124 .and_then(|span| self.0.checked_add_signed(span))
125 .map(Self)
126 .ok_or_else(|| TimestampError {
127 detail: format!("{seconds} seconds after {self} is not a representable instant"),
128 })
129 }
130
131 #[must_use]
143 pub fn latest() -> Self {
144 let last_day = chrono::NaiveDate::from_ymd_opt(9999, 12, 31)
145 .and_then(|day| day.and_hms_nano_opt(23, 59, 59, 999_999_999))
146 .expect("the last moment of the year 9999 is a date-time");
147 Self(last_day.and_utc())
148 }
149
150 #[must_use]
152 pub const fn as_utc(&self) -> &DateTime<Utc> {
153 &self.0
154 }
155}
156
157impl From<DateTime<Utc>> for Timestamp {
158 fn from(instant: DateTime<Utc>) -> Self {
159 Self(instant)
160 }
161}
162
163impl fmt::Display for Timestamp {
164 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
165 write!(
169 formatter,
170 "{}",
171 self.0.to_rfc3339_opts(SecondsFormat::AutoSi, true)
172 )
173 }
174}
175
176impl FromStr for Timestamp {
177 type Err = TimestampError;
178
179 fn from_str(text: &str) -> Result<Self, Self::Err> {
180 DateTime::parse_from_rfc3339(text)
181 .map(|offset| Self(offset.with_timezone(&Utc)))
182 .map_err(|error| TimestampError {
183 detail: format!("{text:?}: {error}"),
184 })
185 }
186}
187
188impl Serialize for Timestamp {
189 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
190 serializer.collect_str(self)
191 }
192}
193
194impl<'de> Deserialize<'de> for Timestamp {
195 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
196 let text = String::deserialize(deserializer)?;
197 text.parse().map_err(D::Error::custom)
198 }
199}
200
201impl JsonSchema for Timestamp {
202 fn schema_name() -> Cow<'static, str> {
203 Cow::Borrowed("Timestamp")
204 }
205
206 fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
207 json_schema!({
208 "type": "string",
209 "format": "date-time",
210 "title": "Timestamp",
211 "description": "An instant in UTC, as an RFC 3339 string with a zero offset."
212 })
213 }
214}
215
216#[cfg(feature = "replay-clock")]
222mod replay_clock {
223 use chrono::{DateTime, TimeDelta, Utc};
224 use core::time::Duration;
225 use std::path::PathBuf;
226 use std::sync::{Mutex, OnceLock};
227
228 const CLOCK_FILE: &str = "clock";
231
232 const REAL_WAITS: &str = "PRINTOBSERVER_REPLAY_REAL_WAITS";
235
236 fn path() -> Option<&'static PathBuf> {
237 static PATH: OnceLock<Option<PathBuf>> = OnceLock::new();
238 PATH.get_or_init(|| {
239 std::env::current_exe()
240 .ok()
241 .map(|program| program.with_file_name(CLOCK_FILE))
242 })
243 .as_ref()
244 }
245
246 pub(super) fn advance(wait: core::time::Duration) -> bool {
251 if std::env::var_os(REAL_WAITS).is_some() {
252 return false;
253 }
254 let Some(file) = path() else {
255 return false;
256 };
257 let Ok(text) = std::fs::read_to_string(file) else {
258 return false;
259 };
260 let mut words = text.split_whitespace();
261 let Some(Ok(offset)) = words.next().map(str::parse::<i64>) else {
262 return false;
263 };
264 let Ok(by) = i64::try_from(wait.as_millis()) else {
265 return false;
266 };
267 let ceiling = words
268 .next()
269 .map(|ceiling| format!(" {ceiling}"))
270 .unwrap_or_default();
271 let written = file.with_extension(format!("advance-{}", std::process::id()));
272 std::fs::write(
273 &written,
274 format!("{}{ceiling}\n", offset.saturating_add(by)),
275 )
276 .is_ok()
277 && std::fs::rename(&written, file).is_ok()
278 }
279
280 fn offset_ms() -> Option<i64> {
282 let text = std::fs::read_to_string(path()?).ok()?;
283 text.split_whitespace().next()?.parse().ok()
284 }
285
286 struct Steady {
289 first_ms: Option<i64>,
290 latest: Duration,
291 }
292
293 pub(super) fn steady(real: Duration) -> Duration {
297 static STEADY: Mutex<Steady> = Mutex::new(Steady {
298 first_ms: None,
299 latest: Duration::ZERO,
300 });
301 let mut held = STEADY
302 .lock()
303 .unwrap_or_else(std::sync::PoisonError::into_inner);
304 let moved_ms = match (offset_ms(), held.first_ms) {
305 (Some(offset), Some(first)) => offset.saturating_sub(first),
306 (Some(offset), None) => {
307 held.first_ms = Some(offset);
308 0
309 }
310 (None, _) => 0,
311 };
312 let by = Duration::from_millis(moved_ms.unsigned_abs());
313 let answer = if moved_ms >= 0 {
314 real.saturating_add(by)
315 } else {
316 real.saturating_sub(by)
317 }
318 .max(held.latest);
319 held.latest = answer;
320 answer
321 }
322
323 pub(super) fn now(real: DateTime<Utc>) -> DateTime<Utc> {
324 let Some(text) = path().and_then(|file| std::fs::read_to_string(file).ok()) else {
325 return real;
326 };
327 let mut numbers = text.split_whitespace().map(str::parse::<i64>);
328 let Some(Ok(offset)) = numbers.next() else {
329 return real;
330 };
331 let Some(moved) =
332 TimeDelta::try_milliseconds(offset).and_then(|by| real.checked_add_signed(by))
333 else {
334 return real;
335 };
336 match numbers.next() {
337 Some(Ok(ceiling)) => {
338 DateTime::from_timestamp_millis(ceiling).map_or(moved, |held| moved.min(held))
339 }
340 _ => moved,
341 }
342 }
343}