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    /// A span measured on the host's steady clock, as the real-print replay's
75    /// clock would measure it.
76    ///
77    /// The replay jumps its clock from one recorded event to the next, minutes or
78    /// hours apart, in a few seconds of real time, so the agent's minimum interval,
79    /// measured across a jump, has to count the jump too, or the agent's change at
80    /// the second of two recorded events an hour apart reads as seconds after its
81    /// change at the first. Only a build of the suite's own, under
82    /// the `replay-clock` feature, with its clock file beside the program, adds
83    /// anything: every other build answers `steady` unchanged. The answer never
84    /// goes back, because a steady clock never does.
85    #[must_use]
86    // llmlint: ignore[code_lands_in_the_domain_that_owns_it] suppressions.toml has the reason.
87    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    /// The instant this many seconds after the Unix epoch.
95    ///
96    /// # Errors
97    ///
98    /// Returns an error when the count of seconds denotes no representable
99    /// instant.
100    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    /// The instant this many seconds after this one.
111    ///
112    /// Sub-second precision is kept rather than dropped: an adjustment asked to
113    /// stand for a minute stands for a minute, rather than for a minute less
114    /// however far into a second it happened to be made.
115    ///
116    /// # Errors
117    ///
118    /// Returns an error when the result is not a representable instant.
119    pub fn plus_seconds(self, seconds: i64) -> Result<Self, TimestampError> {
120        // `try_seconds` rather than `seconds`: a count of seconds that is not a
121        // representable span is answered here rather than raised, because the
122        // caller is a duration somebody asked for.
123        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    /// The latest instant this type writes as a string it reads back.
132    ///
133    /// The last moment of the year 9999: RFC 3339 spells a year in four
134    /// digits, so a later instant is written with a sign and more digits that
135    /// no RFC 3339 reader accepts — and that a store ordering instants by their
136    /// text would order before every earlier one. Reading what is due by this
137    /// instant reads everything due at any instant this type can record.
138    ///
139    /// # Panics
140    ///
141    /// Never: the instant is a fixed one every `chrono` represents.
142    #[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    /// The instant as the UTC date-time it is.
151    #[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        // `use_z` is what makes the offset a literal zero rather than `+00:00`,
166        // and `AutoSi` keeps whatever sub-second precision the instant carries
167        // so that an instant survives a round trip unchanged.
168        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/// The clock of the real-print replay: this program's wall clock moved by a file
217/// beside it. Compiled only under the `replay-clock` feature, which the suite's own
218/// build alone enables: a print replayed in minutes has to read as the hours it
219/// took, or every time the agent reads contradicts every position it reads.
220// llmlint: ignore[code_lands_in_the_domain_that_owns_it, changed_behavior_has_e2e] See suppressions.toml.
221#[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    /// The file beside the program: the milliseconds to add, and the latest instant
229    /// to answer in milliseconds since the epoch, or nothing past that for none.
230    const CLOCK_FILE: &str = "clock";
231
232    /// Set in the environment to wait in real time all the same: what the suite
233    /// compares a jumped replay against.
234    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    /// Move the clock on by `wait`: the file's offset grows by it and its
247    /// ceiling stands, written whole and then renamed into place so a reader
248    /// never sees half of it. Nothing is moved, and `false` answered, when
249    /// there is no file to move or real waits were asked for.
250    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    /// The offset the clock file holds, in milliseconds, when there is one to read.
281    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    /// What the steady clock has answered: the offset its first reading found, and
287    /// its latest answer.
288    struct Steady {
289        first_ms: Option<i64>,
290        latest: Duration,
291    }
292
293    /// `real` moved on by how far the clock file's offset has grown since the first
294    /// reading of it, and never less than the last answer. A file that cannot be read
295    /// moves nothing.
296    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}