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    /// The instant this many seconds after the Unix epoch.
55    ///
56    /// # Errors
57    ///
58    /// Returns an error when the count of seconds denotes no representable
59    /// instant.
60    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    /// The instant this many seconds after this one.
71    ///
72    /// Sub-second precision is kept rather than dropped: an adjustment asked to
73    /// stand for a minute stands for a minute, rather than for a minute less
74    /// however far into a second it happened to be made.
75    ///
76    /// # Errors
77    ///
78    /// Returns an error when the result is not a representable instant.
79    pub fn plus_seconds(self, seconds: i64) -> Result<Self, TimestampError> {
80        // `try_seconds` rather than `seconds`: a count of seconds that is not a
81        // representable span is answered here rather than raised, because the
82        // caller is a duration somebody asked for.
83        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    /// The latest instant this type writes as a string it reads back.
92    ///
93    /// The last moment of the year 9999: RFC 3339 spells a year in four
94    /// digits, so a later instant is written with a sign and more digits that
95    /// no RFC 3339 reader accepts — and that a store ordering instants by their
96    /// text would order before every earlier one. Reading what is due by this
97    /// instant reads everything due at any instant this type can record.
98    ///
99    /// # Panics
100    ///
101    /// Never: the instant is a fixed one every `chrono` represents.
102    #[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    /// The instant as the UTC date-time it is.
111    #[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        // `use_z` is what makes the offset a literal zero rather than `+00:00`,
126        // and `AutoSi` keeps whatever sub-second precision the instant carries
127        // so that an instant survives a round trip unchanged.
128        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/// The clock of the real-print replay: this program's wall clock moved by a file
177/// beside it. Compiled only under the `replay-clock` feature, which the suite's own
178/// build alone enables: a print replayed in minutes has to read as the hours it
179/// took, or every time the agent reads contradicts every position it reads.
180// llmlint: ignore[code_lands_in_the_domain_that_owns_it, changed_behavior_has_e2e] See suppressions.toml.
181#[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    /// The file beside the program: the milliseconds to add, and the latest instant
188    /// to answer in milliseconds since the epoch, or nothing past that for none.
189    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}