Skip to main content

printobserver_types/
timestamp.rs

1//! The one instant representation this vocabulary has.
2//!
3//! Every timestamp is an instant in UTC, serialized as an RFC 3339 string with
4//! a zero offset. There is no local-time representation anywhere in this crate:
5//! a string carrying a non-zero offset parses to the instant it denotes and
6//! re-emits at a zero offset, and a string carrying no offset at all is refused
7//! rather than guessed at.
8
9use 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/// Why a string is not an instant this vocabulary can hold.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct TimestampError {
20    /// What is wrong with the string.
21    detail: String,
22}
23
24impl TimestampError {
25    /// What is wrong with the string.
26    #[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/// An instant in UTC, serialized as an RFC 3339 string with a zero offset.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub struct Timestamp(DateTime<Utc>);
43
44impl Timestamp {
45    /// The instant now.
46    #[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    /// Let `wait` pass on the real-print replay's clock rather than in real
55    /// time, and answer whether it did.
56    ///
57    /// Only a build of the suite's own, under the `replay-clock` feature, with
58    /// its clock file beside the program, answers `true`: every other build
59    /// answers `false` and the caller waits as it always does. A caller asks
60    /// only when nothing could end its wait early, so passing the wait at once
61    /// moves every reading of the clock exactly as waiting it out would.
62    #[must_use]
63    // llmlint: ignore[code_lands_in_the_domain_that_owns_it] suppressions.toml has the reason.
64    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    /// The instant this many seconds after the Unix epoch.
75    ///
76    /// # Errors
77    ///
78    /// Returns an error when the count of seconds denotes no representable
79    /// instant.
80    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    /// The instant this many seconds after this one.
91    ///
92    /// Sub-second precision is kept rather than dropped: an adjustment asked to
93    /// stand for a minute stands for a minute, rather than for a minute less
94    /// however far into a second it happened to be made.
95    ///
96    /// # Errors
97    ///
98    /// Returns an error when the result is not a representable instant.
99    pub fn plus_seconds(self, seconds: i64) -> Result<Self, TimestampError> {
100        // `try_seconds` rather than `seconds`: a count of seconds that is not a
101        // representable span is answered here rather than raised, because the
102        // caller is a duration somebody asked for.
103        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    /// The latest instant this type writes as a string it reads back.
112    ///
113    /// The last moment of the year 9999: RFC 3339 spells a year in four
114    /// digits, so a later instant is written with a sign and more digits that
115    /// no RFC 3339 reader accepts — and that a store ordering instants by their
116    /// text would order before every earlier one. Reading what is due by this
117    /// instant reads everything due at any instant this type can record.
118    ///
119    /// # Panics
120    ///
121    /// Never: the instant is a fixed one every `chrono` represents.
122    #[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    /// The instant as the UTC date-time it is.
131    #[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        // `use_z` is what makes the offset a literal zero rather than `+00:00`,
146        // and `AutoSi` keeps whatever sub-second precision the instant carries
147        // so that an instant survives a round trip unchanged.
148        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/// The clock of the real-print replay: this program's wall clock moved by a file
197/// beside it. Compiled only under the `replay-clock` feature, which the suite's own
198/// build alone enables: a print replayed in minutes has to read as the hours it
199/// took, or every time the agent reads contradicts every position it reads.
200// llmlint: ignore[code_lands_in_the_domain_that_owns_it, changed_behavior_has_e2e] See suppressions.toml.
201#[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    /// The file beside the program: the milliseconds to add, and the latest instant
208    /// to answer in milliseconds since the epoch, or nothing past that for none.
209    const CLOCK_FILE: &str = "clock";
210
211    /// Set in the environment to wait in real time all the same: what the suite
212    /// compares a jumped replay against.
213    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    /// Move the clock on by `wait`: the file's offset grows by it and its
226    /// ceiling stands, written whole and then renamed into place so a reader
227    /// never sees half of it. Nothing is moved, and `false` answered, when
228    /// there is no file to move or real waits were asked for.
229    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}